1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Expr constant evaluator.
10 //
11 // Constant expression evaluation produces four main results:
12 //
13 //  * A success/failure flag indicating whether constant folding was successful.
14 //    This is the 'bool' return value used by most of the code in this file. A
15 //    'false' return value indicates that constant folding has failed, and any
16 //    appropriate diagnostic has already been produced.
17 //
18 //  * An evaluated result, valid only if constant folding has not failed.
19 //
20 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
21 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
22 //    where it is possible to determine the evaluated result regardless.
23 //
24 //  * A set of notes indicating why the evaluation was not a constant expression
25 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
26 //    too, why the expression could not be folded.
27 //
28 // If we are checking for a potential constant expression, failure to constant
29 // fold a potential constant sub-expression will be indicated by a 'false'
30 // return value (the expression could not be folded) and no diagnostic (the
31 // expression is not necessarily non-constant).
32 //
33 //===----------------------------------------------------------------------===//
34 
35 #include "Interp/Context.h"
36 #include "Interp/Frame.h"
37 #include "Interp/State.h"
38 #include "clang/AST/APValue.h"
39 #include "clang/AST/ASTContext.h"
40 #include "clang/AST/ASTDiagnostic.h"
41 #include "clang/AST/ASTLambda.h"
42 #include "clang/AST/Attr.h"
43 #include "clang/AST/CXXInheritance.h"
44 #include "clang/AST/CharUnits.h"
45 #include "clang/AST/CurrentSourceLocExprScope.h"
46 #include "clang/AST/Expr.h"
47 #include "clang/AST/OSLog.h"
48 #include "clang/AST/OptionalDiagnostic.h"
49 #include "clang/AST/RecordLayout.h"
50 #include "clang/AST/StmtVisitor.h"
51 #include "clang/AST/TypeLoc.h"
52 #include "clang/Basic/Builtins.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "llvm/ADT/APFixedPoint.h"
55 #include "llvm/ADT/Optional.h"
56 #include "llvm/ADT/SmallBitVector.h"
57 #include "llvm/Support/Debug.h"
58 #include "llvm/Support/SaveAndRestore.h"
59 #include "llvm/Support/raw_ostream.h"
60 #include <cstring>
61 #include <functional>
62 
63 #define DEBUG_TYPE "exprconstant"
64 
65 using namespace clang;
66 using llvm::APFixedPoint;
67 using llvm::APInt;
68 using llvm::APSInt;
69 using llvm::APFloat;
70 using llvm::FixedPointSemantics;
71 using llvm::Optional;
72 
73 namespace {
74   struct LValue;
75   class CallStackFrame;
76   class EvalInfo;
77 
78   using SourceLocExprScopeGuard =
79       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
80 
81   static QualType getType(APValue::LValueBase B) {
82     return B.getType();
83   }
84 
85   /// Get an LValue path entry, which is known to not be an array index, as a
86   /// field declaration.
87   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
88     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
89   }
90   /// Get an LValue path entry, which is known to not be an array index, as a
91   /// base class declaration.
92   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
93     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
94   }
95   /// Determine whether this LValue path entry for a base class names a virtual
96   /// base class.
97   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
98     return E.getAsBaseOrMember().getInt();
99   }
100 
101   /// Given an expression, determine the type used to store the result of
102   /// evaluating that expression.
103   static QualType getStorageType(const ASTContext &Ctx, const Expr *E) {
104     if (E->isPRValue())
105       return E->getType();
106     return Ctx.getLValueReferenceType(E->getType());
107   }
108 
109   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
110   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
111     if (const FunctionDecl *DirectCallee = CE->getDirectCallee())
112       return DirectCallee->getAttr<AllocSizeAttr>();
113     if (const Decl *IndirectCallee = CE->getCalleeDecl())
114       return IndirectCallee->getAttr<AllocSizeAttr>();
115     return nullptr;
116   }
117 
118   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
119   /// This will look through a single cast.
120   ///
121   /// Returns null if we couldn't unwrap a function with alloc_size.
122   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
123     if (!E->getType()->isPointerType())
124       return nullptr;
125 
126     E = E->IgnoreParens();
127     // If we're doing a variable assignment from e.g. malloc(N), there will
128     // probably be a cast of some kind. In exotic cases, we might also see a
129     // top-level ExprWithCleanups. Ignore them either way.
130     if (const auto *FE = dyn_cast<FullExpr>(E))
131       E = FE->getSubExpr()->IgnoreParens();
132 
133     if (const auto *Cast = dyn_cast<CastExpr>(E))
134       E = Cast->getSubExpr()->IgnoreParens();
135 
136     if (const auto *CE = dyn_cast<CallExpr>(E))
137       return getAllocSizeAttr(CE) ? CE : nullptr;
138     return nullptr;
139   }
140 
141   /// Determines whether or not the given Base contains a call to a function
142   /// with the alloc_size attribute.
143   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
144     const auto *E = Base.dyn_cast<const Expr *>();
145     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
146   }
147 
148   /// Determines whether the given kind of constant expression is only ever
149   /// used for name mangling. If so, it's permitted to reference things that we
150   /// can't generate code for (in particular, dllimported functions).
151   static bool isForManglingOnly(ConstantExprKind Kind) {
152     switch (Kind) {
153     case ConstantExprKind::Normal:
154     case ConstantExprKind::ClassTemplateArgument:
155     case ConstantExprKind::ImmediateInvocation:
156       // Note that non-type template arguments of class type are emitted as
157       // template parameter objects.
158       return false;
159 
160     case ConstantExprKind::NonClassTemplateArgument:
161       return true;
162     }
163     llvm_unreachable("unknown ConstantExprKind");
164   }
165 
166   static bool isTemplateArgument(ConstantExprKind Kind) {
167     switch (Kind) {
168     case ConstantExprKind::Normal:
169     case ConstantExprKind::ImmediateInvocation:
170       return false;
171 
172     case ConstantExprKind::ClassTemplateArgument:
173     case ConstantExprKind::NonClassTemplateArgument:
174       return true;
175     }
176     llvm_unreachable("unknown ConstantExprKind");
177   }
178 
179   /// The bound to claim that an array of unknown bound has.
180   /// The value in MostDerivedArraySize is undefined in this case. So, set it
181   /// to an arbitrary value that's likely to loudly break things if it's used.
182   static const uint64_t AssumedSizeForUnsizedArray =
183       std::numeric_limits<uint64_t>::max() / 2;
184 
185   /// Determines if an LValue with the given LValueBase will have an unsized
186   /// array in its designator.
187   /// Find the path length and type of the most-derived subobject in the given
188   /// path, and find the size of the containing array, if any.
189   static unsigned
190   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
191                            ArrayRef<APValue::LValuePathEntry> Path,
192                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
193                            bool &FirstEntryIsUnsizedArray) {
194     // This only accepts LValueBases from APValues, and APValues don't support
195     // arrays that lack size info.
196     assert(!isBaseAnAllocSizeCall(Base) &&
197            "Unsized arrays shouldn't appear here");
198     unsigned MostDerivedLength = 0;
199     Type = getType(Base);
200 
201     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
202       if (Type->isArrayType()) {
203         const ArrayType *AT = Ctx.getAsArrayType(Type);
204         Type = AT->getElementType();
205         MostDerivedLength = I + 1;
206         IsArray = true;
207 
208         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
209           ArraySize = CAT->getSize().getZExtValue();
210         } else {
211           assert(I == 0 && "unexpected unsized array designator");
212           FirstEntryIsUnsizedArray = true;
213           ArraySize = AssumedSizeForUnsizedArray;
214         }
215       } else if (Type->isAnyComplexType()) {
216         const ComplexType *CT = Type->castAs<ComplexType>();
217         Type = CT->getElementType();
218         ArraySize = 2;
219         MostDerivedLength = I + 1;
220         IsArray = true;
221       } else if (const FieldDecl *FD = getAsField(Path[I])) {
222         Type = FD->getType();
223         ArraySize = 0;
224         MostDerivedLength = I + 1;
225         IsArray = false;
226       } else {
227         // Path[I] describes a base class.
228         ArraySize = 0;
229         IsArray = false;
230       }
231     }
232     return MostDerivedLength;
233   }
234 
235   /// A path from a glvalue to a subobject of that glvalue.
236   struct SubobjectDesignator {
237     /// True if the subobject was named in a manner not supported by C++11. Such
238     /// lvalues can still be folded, but they are not core constant expressions
239     /// and we cannot perform lvalue-to-rvalue conversions on them.
240     unsigned Invalid : 1;
241 
242     /// Is this a pointer one past the end of an object?
243     unsigned IsOnePastTheEnd : 1;
244 
245     /// Indicator of whether the first entry is an unsized array.
246     unsigned FirstEntryIsAnUnsizedArray : 1;
247 
248     /// Indicator of whether the most-derived object is an array element.
249     unsigned MostDerivedIsArrayElement : 1;
250 
251     /// The length of the path to the most-derived object of which this is a
252     /// subobject.
253     unsigned MostDerivedPathLength : 28;
254 
255     /// The size of the array of which the most-derived object is an element.
256     /// This will always be 0 if the most-derived object is not an array
257     /// element. 0 is not an indicator of whether or not the most-derived object
258     /// is an array, however, because 0-length arrays are allowed.
259     ///
260     /// If the current array is an unsized array, the value of this is
261     /// undefined.
262     uint64_t MostDerivedArraySize;
263 
264     /// The type of the most derived object referred to by this address.
265     QualType MostDerivedType;
266 
267     typedef APValue::LValuePathEntry PathEntry;
268 
269     /// The entries on the path from the glvalue to the designated subobject.
270     SmallVector<PathEntry, 8> Entries;
271 
272     SubobjectDesignator() : Invalid(true) {}
273 
274     explicit SubobjectDesignator(QualType T)
275         : Invalid(false), IsOnePastTheEnd(false),
276           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
277           MostDerivedPathLength(0), MostDerivedArraySize(0),
278           MostDerivedType(T) {}
279 
280     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
281         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
282           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
283           MostDerivedPathLength(0), MostDerivedArraySize(0) {
284       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
285       if (!Invalid) {
286         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
287         ArrayRef<PathEntry> VEntries = V.getLValuePath();
288         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
289         if (V.getLValueBase()) {
290           bool IsArray = false;
291           bool FirstIsUnsizedArray = false;
292           MostDerivedPathLength = findMostDerivedSubobject(
293               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
294               MostDerivedType, IsArray, FirstIsUnsizedArray);
295           MostDerivedIsArrayElement = IsArray;
296           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
297         }
298       }
299     }
300 
301     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
302                   unsigned NewLength) {
303       if (Invalid)
304         return;
305 
306       assert(Base && "cannot truncate path for null pointer");
307       assert(NewLength <= Entries.size() && "not a truncation");
308 
309       if (NewLength == Entries.size())
310         return;
311       Entries.resize(NewLength);
312 
313       bool IsArray = false;
314       bool FirstIsUnsizedArray = false;
315       MostDerivedPathLength = findMostDerivedSubobject(
316           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
317           FirstIsUnsizedArray);
318       MostDerivedIsArrayElement = IsArray;
319       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
320     }
321 
322     void setInvalid() {
323       Invalid = true;
324       Entries.clear();
325     }
326 
327     /// Determine whether the most derived subobject is an array without a
328     /// known bound.
329     bool isMostDerivedAnUnsizedArray() const {
330       assert(!Invalid && "Calling this makes no sense on invalid designators");
331       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
332     }
333 
334     /// Determine what the most derived array's size is. Results in an assertion
335     /// failure if the most derived array lacks a size.
336     uint64_t getMostDerivedArraySize() const {
337       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
338       return MostDerivedArraySize;
339     }
340 
341     /// Determine whether this is a one-past-the-end pointer.
342     bool isOnePastTheEnd() const {
343       assert(!Invalid);
344       if (IsOnePastTheEnd)
345         return true;
346       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
347           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
348               MostDerivedArraySize)
349         return true;
350       return false;
351     }
352 
353     /// Get the range of valid index adjustments in the form
354     ///   {maximum value that can be subtracted from this pointer,
355     ///    maximum value that can be added to this pointer}
356     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
357       if (Invalid || isMostDerivedAnUnsizedArray())
358         return {0, 0};
359 
360       // [expr.add]p4: For the purposes of these operators, a pointer to a
361       // nonarray object behaves the same as a pointer to the first element of
362       // an array of length one with the type of the object as its element type.
363       bool IsArray = MostDerivedPathLength == Entries.size() &&
364                      MostDerivedIsArrayElement;
365       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
366                                     : (uint64_t)IsOnePastTheEnd;
367       uint64_t ArraySize =
368           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
369       return {ArrayIndex, ArraySize - ArrayIndex};
370     }
371 
372     /// Check that this refers to a valid subobject.
373     bool isValidSubobject() const {
374       if (Invalid)
375         return false;
376       return !isOnePastTheEnd();
377     }
378     /// Check that this refers to a valid subobject, and if not, produce a
379     /// relevant diagnostic and set the designator as invalid.
380     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
381 
382     /// Get the type of the designated object.
383     QualType getType(ASTContext &Ctx) const {
384       assert(!Invalid && "invalid designator has no subobject type");
385       return MostDerivedPathLength == Entries.size()
386                  ? MostDerivedType
387                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
388     }
389 
390     /// Update this designator to refer to the first element within this array.
391     void addArrayUnchecked(const ConstantArrayType *CAT) {
392       Entries.push_back(PathEntry::ArrayIndex(0));
393 
394       // This is a most-derived object.
395       MostDerivedType = CAT->getElementType();
396       MostDerivedIsArrayElement = true;
397       MostDerivedArraySize = CAT->getSize().getZExtValue();
398       MostDerivedPathLength = Entries.size();
399     }
400     /// Update this designator to refer to the first element within the array of
401     /// elements of type T. This is an array of unknown size.
402     void addUnsizedArrayUnchecked(QualType ElemTy) {
403       Entries.push_back(PathEntry::ArrayIndex(0));
404 
405       MostDerivedType = ElemTy;
406       MostDerivedIsArrayElement = true;
407       // The value in MostDerivedArraySize is undefined in this case. So, set it
408       // to an arbitrary value that's likely to loudly break things if it's
409       // used.
410       MostDerivedArraySize = AssumedSizeForUnsizedArray;
411       MostDerivedPathLength = Entries.size();
412     }
413     /// Update this designator to refer to the given base or member of this
414     /// object.
415     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
416       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
417 
418       // If this isn't a base class, it's a new most-derived object.
419       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
420         MostDerivedType = FD->getType();
421         MostDerivedIsArrayElement = false;
422         MostDerivedArraySize = 0;
423         MostDerivedPathLength = Entries.size();
424       }
425     }
426     /// Update this designator to refer to the given complex component.
427     void addComplexUnchecked(QualType EltTy, bool Imag) {
428       Entries.push_back(PathEntry::ArrayIndex(Imag));
429 
430       // This is technically a most-derived object, though in practice this
431       // is unlikely to matter.
432       MostDerivedType = EltTy;
433       MostDerivedIsArrayElement = true;
434       MostDerivedArraySize = 2;
435       MostDerivedPathLength = Entries.size();
436     }
437     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
438     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
439                                    const APSInt &N);
440     /// Add N to the address of this subobject.
441     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
442       if (Invalid || !N) return;
443       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
444       if (isMostDerivedAnUnsizedArray()) {
445         diagnoseUnsizedArrayPointerArithmetic(Info, E);
446         // Can't verify -- trust that the user is doing the right thing (or if
447         // not, trust that the caller will catch the bad behavior).
448         // FIXME: Should we reject if this overflows, at least?
449         Entries.back() = PathEntry::ArrayIndex(
450             Entries.back().getAsArrayIndex() + TruncatedN);
451         return;
452       }
453 
454       // [expr.add]p4: For the purposes of these operators, a pointer to a
455       // nonarray object behaves the same as a pointer to the first element of
456       // an array of length one with the type of the object as its element type.
457       bool IsArray = MostDerivedPathLength == Entries.size() &&
458                      MostDerivedIsArrayElement;
459       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
460                                     : (uint64_t)IsOnePastTheEnd;
461       uint64_t ArraySize =
462           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
463 
464       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
465         // Calculate the actual index in a wide enough type, so we can include
466         // it in the note.
467         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
468         (llvm::APInt&)N += ArrayIndex;
469         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
470         diagnosePointerArithmetic(Info, E, N);
471         setInvalid();
472         return;
473       }
474 
475       ArrayIndex += TruncatedN;
476       assert(ArrayIndex <= ArraySize &&
477              "bounds check succeeded for out-of-bounds index");
478 
479       if (IsArray)
480         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
481       else
482         IsOnePastTheEnd = (ArrayIndex != 0);
483     }
484   };
485 
486   /// A scope at the end of which an object can need to be destroyed.
487   enum class ScopeKind {
488     Block,
489     FullExpression,
490     Call
491   };
492 
493   /// A reference to a particular call and its arguments.
494   struct CallRef {
495     CallRef() : OrigCallee(), CallIndex(0), Version() {}
496     CallRef(const FunctionDecl *Callee, unsigned CallIndex, unsigned Version)
497         : OrigCallee(Callee), CallIndex(CallIndex), Version(Version) {}
498 
499     explicit operator bool() const { return OrigCallee; }
500 
501     /// Get the parameter that the caller initialized, corresponding to the
502     /// given parameter in the callee.
503     const ParmVarDecl *getOrigParam(const ParmVarDecl *PVD) const {
504       return OrigCallee ? OrigCallee->getParamDecl(PVD->getFunctionScopeIndex())
505                         : PVD;
506     }
507 
508     /// The callee at the point where the arguments were evaluated. This might
509     /// be different from the actual callee (a different redeclaration, or a
510     /// virtual override), but this function's parameters are the ones that
511     /// appear in the parameter map.
512     const FunctionDecl *OrigCallee;
513     /// The call index of the frame that holds the argument values.
514     unsigned CallIndex;
515     /// The version of the parameters corresponding to this call.
516     unsigned Version;
517   };
518 
519   /// A stack frame in the constexpr call stack.
520   class CallStackFrame : public interp::Frame {
521   public:
522     EvalInfo &Info;
523 
524     /// Parent - The caller of this stack frame.
525     CallStackFrame *Caller;
526 
527     /// Callee - The function which was called.
528     const FunctionDecl *Callee;
529 
530     /// This - The binding for the this pointer in this call, if any.
531     const LValue *This;
532 
533     /// Information on how to find the arguments to this call. Our arguments
534     /// are stored in our parent's CallStackFrame, using the ParmVarDecl* as a
535     /// key and this value as the version.
536     CallRef Arguments;
537 
538     /// Source location information about the default argument or default
539     /// initializer expression we're evaluating, if any.
540     CurrentSourceLocExprScope CurSourceLocExprScope;
541 
542     // Note that we intentionally use std::map here so that references to
543     // values are stable.
544     typedef std::pair<const void *, unsigned> MapKeyTy;
545     typedef std::map<MapKeyTy, APValue> MapTy;
546     /// Temporaries - Temporary lvalues materialized within this stack frame.
547     MapTy Temporaries;
548 
549     /// CallLoc - The location of the call expression for this call.
550     SourceLocation CallLoc;
551 
552     /// Index - The call index of this call.
553     unsigned Index;
554 
555     /// The stack of integers for tracking version numbers for temporaries.
556     SmallVector<unsigned, 2> TempVersionStack = {1};
557     unsigned CurTempVersion = TempVersionStack.back();
558 
559     unsigned getTempVersion() const { return TempVersionStack.back(); }
560 
561     void pushTempVersion() {
562       TempVersionStack.push_back(++CurTempVersion);
563     }
564 
565     void popTempVersion() {
566       TempVersionStack.pop_back();
567     }
568 
569     CallRef createCall(const FunctionDecl *Callee) {
570       return {Callee, Index, ++CurTempVersion};
571     }
572 
573     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
574     // on the overall stack usage of deeply-recursing constexpr evaluations.
575     // (We should cache this map rather than recomputing it repeatedly.)
576     // But let's try this and see how it goes; we can look into caching the map
577     // as a later change.
578 
579     /// LambdaCaptureFields - Mapping from captured variables/this to
580     /// corresponding data members in the closure class.
581     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
582     FieldDecl *LambdaThisCaptureField;
583 
584     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
585                    const FunctionDecl *Callee, const LValue *This,
586                    CallRef Arguments);
587     ~CallStackFrame();
588 
589     // Return the temporary for Key whose version number is Version.
590     APValue *getTemporary(const void *Key, unsigned Version) {
591       MapKeyTy KV(Key, Version);
592       auto LB = Temporaries.lower_bound(KV);
593       if (LB != Temporaries.end() && LB->first == KV)
594         return &LB->second;
595       // Pair (Key,Version) wasn't found in the map. Check that no elements
596       // in the map have 'Key' as their key.
597       assert((LB == Temporaries.end() || LB->first.first != Key) &&
598              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
599              "Element with key 'Key' found in map");
600       return nullptr;
601     }
602 
603     // Return the current temporary for Key in the map.
604     APValue *getCurrentTemporary(const void *Key) {
605       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
606       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
607         return &std::prev(UB)->second;
608       return nullptr;
609     }
610 
611     // Return the version number of the current temporary for Key.
612     unsigned getCurrentTemporaryVersion(const void *Key) const {
613       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
614       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
615         return std::prev(UB)->first.second;
616       return 0;
617     }
618 
619     /// Allocate storage for an object of type T in this stack frame.
620     /// Populates LV with a handle to the created object. Key identifies
621     /// the temporary within the stack frame, and must not be reused without
622     /// bumping the temporary version number.
623     template<typename KeyT>
624     APValue &createTemporary(const KeyT *Key, QualType T,
625                              ScopeKind Scope, LValue &LV);
626 
627     /// Allocate storage for a parameter of a function call made in this frame.
628     APValue &createParam(CallRef Args, const ParmVarDecl *PVD, LValue &LV);
629 
630     void describe(llvm::raw_ostream &OS) override;
631 
632     Frame *getCaller() const override { return Caller; }
633     SourceLocation getCallLocation() const override { return CallLoc; }
634     const FunctionDecl *getCallee() const override { return Callee; }
635 
636     bool isStdFunction() const {
637       for (const DeclContext *DC = Callee; DC; DC = DC->getParent())
638         if (DC->isStdNamespace())
639           return true;
640       return false;
641     }
642 
643   private:
644     APValue &createLocal(APValue::LValueBase Base, const void *Key, QualType T,
645                          ScopeKind Scope);
646   };
647 
648   /// Temporarily override 'this'.
649   class ThisOverrideRAII {
650   public:
651     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
652         : Frame(Frame), OldThis(Frame.This) {
653       if (Enable)
654         Frame.This = NewThis;
655     }
656     ~ThisOverrideRAII() {
657       Frame.This = OldThis;
658     }
659   private:
660     CallStackFrame &Frame;
661     const LValue *OldThis;
662   };
663 }
664 
665 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
666                               const LValue &This, QualType ThisType);
667 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
668                               APValue::LValueBase LVBase, APValue &Value,
669                               QualType T);
670 
671 namespace {
672   /// A cleanup, and a flag indicating whether it is lifetime-extended.
673   class Cleanup {
674     llvm::PointerIntPair<APValue*, 2, ScopeKind> Value;
675     APValue::LValueBase Base;
676     QualType T;
677 
678   public:
679     Cleanup(APValue *Val, APValue::LValueBase Base, QualType T,
680             ScopeKind Scope)
681         : Value(Val, Scope), Base(Base), T(T) {}
682 
683     /// Determine whether this cleanup should be performed at the end of the
684     /// given kind of scope.
685     bool isDestroyedAtEndOf(ScopeKind K) const {
686       return (int)Value.getInt() >= (int)K;
687     }
688     bool endLifetime(EvalInfo &Info, bool RunDestructors) {
689       if (RunDestructors) {
690         SourceLocation Loc;
691         if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>())
692           Loc = VD->getLocation();
693         else if (const Expr *E = Base.dyn_cast<const Expr*>())
694           Loc = E->getExprLoc();
695         return HandleDestruction(Info, Loc, Base, *Value.getPointer(), T);
696       }
697       *Value.getPointer() = APValue();
698       return true;
699     }
700 
701     bool hasSideEffect() {
702       return T.isDestructedType();
703     }
704   };
705 
706   /// A reference to an object whose construction we are currently evaluating.
707   struct ObjectUnderConstruction {
708     APValue::LValueBase Base;
709     ArrayRef<APValue::LValuePathEntry> Path;
710     friend bool operator==(const ObjectUnderConstruction &LHS,
711                            const ObjectUnderConstruction &RHS) {
712       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
713     }
714     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
715       return llvm::hash_combine(Obj.Base, Obj.Path);
716     }
717   };
718   enum class ConstructionPhase {
719     None,
720     Bases,
721     AfterBases,
722     AfterFields,
723     Destroying,
724     DestroyingBases
725   };
726 }
727 
728 namespace llvm {
729 template<> struct DenseMapInfo<ObjectUnderConstruction> {
730   using Base = DenseMapInfo<APValue::LValueBase>;
731   static ObjectUnderConstruction getEmptyKey() {
732     return {Base::getEmptyKey(), {}}; }
733   static ObjectUnderConstruction getTombstoneKey() {
734     return {Base::getTombstoneKey(), {}};
735   }
736   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
737     return hash_value(Object);
738   }
739   static bool isEqual(const ObjectUnderConstruction &LHS,
740                       const ObjectUnderConstruction &RHS) {
741     return LHS == RHS;
742   }
743 };
744 }
745 
746 namespace {
747   /// A dynamically-allocated heap object.
748   struct DynAlloc {
749     /// The value of this heap-allocated object.
750     APValue Value;
751     /// The allocating expression; used for diagnostics. Either a CXXNewExpr
752     /// or a CallExpr (the latter is for direct calls to operator new inside
753     /// std::allocator<T>::allocate).
754     const Expr *AllocExpr = nullptr;
755 
756     enum Kind {
757       New,
758       ArrayNew,
759       StdAllocator
760     };
761 
762     /// Get the kind of the allocation. This must match between allocation
763     /// and deallocation.
764     Kind getKind() const {
765       if (auto *NE = dyn_cast<CXXNewExpr>(AllocExpr))
766         return NE->isArray() ? ArrayNew : New;
767       assert(isa<CallExpr>(AllocExpr));
768       return StdAllocator;
769     }
770   };
771 
772   struct DynAllocOrder {
773     bool operator()(DynamicAllocLValue L, DynamicAllocLValue R) const {
774       return L.getIndex() < R.getIndex();
775     }
776   };
777 
778   /// EvalInfo - This is a private struct used by the evaluator to capture
779   /// information about a subexpression as it is folded.  It retains information
780   /// about the AST context, but also maintains information about the folded
781   /// expression.
782   ///
783   /// If an expression could be evaluated, it is still possible it is not a C
784   /// "integer constant expression" or constant expression.  If not, this struct
785   /// captures information about how and why not.
786   ///
787   /// One bit of information passed *into* the request for constant folding
788   /// indicates whether the subexpression is "evaluated" or not according to C
789   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
790   /// evaluate the expression regardless of what the RHS is, but C only allows
791   /// certain things in certain situations.
792   class EvalInfo : public interp::State {
793   public:
794     ASTContext &Ctx;
795 
796     /// EvalStatus - Contains information about the evaluation.
797     Expr::EvalStatus &EvalStatus;
798 
799     /// CurrentCall - The top of the constexpr call stack.
800     CallStackFrame *CurrentCall;
801 
802     /// CallStackDepth - The number of calls in the call stack right now.
803     unsigned CallStackDepth;
804 
805     /// NextCallIndex - The next call index to assign.
806     unsigned NextCallIndex;
807 
808     /// StepsLeft - The remaining number of evaluation steps we're permitted
809     /// to perform. This is essentially a limit for the number of statements
810     /// we will evaluate.
811     unsigned StepsLeft;
812 
813     /// Enable the experimental new constant interpreter. If an expression is
814     /// not supported by the interpreter, an error is triggered.
815     bool EnableNewConstInterp;
816 
817     /// BottomFrame - The frame in which evaluation started. This must be
818     /// initialized after CurrentCall and CallStackDepth.
819     CallStackFrame BottomFrame;
820 
821     /// A stack of values whose lifetimes end at the end of some surrounding
822     /// evaluation frame.
823     llvm::SmallVector<Cleanup, 16> CleanupStack;
824 
825     /// EvaluatingDecl - This is the declaration whose initializer is being
826     /// evaluated, if any.
827     APValue::LValueBase EvaluatingDecl;
828 
829     enum class EvaluatingDeclKind {
830       None,
831       /// We're evaluating the construction of EvaluatingDecl.
832       Ctor,
833       /// We're evaluating the destruction of EvaluatingDecl.
834       Dtor,
835     };
836     EvaluatingDeclKind IsEvaluatingDecl = EvaluatingDeclKind::None;
837 
838     /// EvaluatingDeclValue - This is the value being constructed for the
839     /// declaration whose initializer is being evaluated, if any.
840     APValue *EvaluatingDeclValue;
841 
842     /// Set of objects that are currently being constructed.
843     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
844         ObjectsUnderConstruction;
845 
846     /// Current heap allocations, along with the location where each was
847     /// allocated. We use std::map here because we need stable addresses
848     /// for the stored APValues.
849     std::map<DynamicAllocLValue, DynAlloc, DynAllocOrder> HeapAllocs;
850 
851     /// The number of heap allocations performed so far in this evaluation.
852     unsigned NumHeapAllocs = 0;
853 
854     struct EvaluatingConstructorRAII {
855       EvalInfo &EI;
856       ObjectUnderConstruction Object;
857       bool DidInsert;
858       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
859                                 bool HasBases)
860           : EI(EI), Object(Object) {
861         DidInsert =
862             EI.ObjectsUnderConstruction
863                 .insert({Object, HasBases ? ConstructionPhase::Bases
864                                           : ConstructionPhase::AfterBases})
865                 .second;
866       }
867       void finishedConstructingBases() {
868         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
869       }
870       void finishedConstructingFields() {
871         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterFields;
872       }
873       ~EvaluatingConstructorRAII() {
874         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
875       }
876     };
877 
878     struct EvaluatingDestructorRAII {
879       EvalInfo &EI;
880       ObjectUnderConstruction Object;
881       bool DidInsert;
882       EvaluatingDestructorRAII(EvalInfo &EI, ObjectUnderConstruction Object)
883           : EI(EI), Object(Object) {
884         DidInsert = EI.ObjectsUnderConstruction
885                         .insert({Object, ConstructionPhase::Destroying})
886                         .second;
887       }
888       void startedDestroyingBases() {
889         EI.ObjectsUnderConstruction[Object] =
890             ConstructionPhase::DestroyingBases;
891       }
892       ~EvaluatingDestructorRAII() {
893         if (DidInsert)
894           EI.ObjectsUnderConstruction.erase(Object);
895       }
896     };
897 
898     ConstructionPhase
899     isEvaluatingCtorDtor(APValue::LValueBase Base,
900                          ArrayRef<APValue::LValuePathEntry> Path) {
901       return ObjectsUnderConstruction.lookup({Base, Path});
902     }
903 
904     /// If we're currently speculatively evaluating, the outermost call stack
905     /// depth at which we can mutate state, otherwise 0.
906     unsigned SpeculativeEvaluationDepth = 0;
907 
908     /// The current array initialization index, if we're performing array
909     /// initialization.
910     uint64_t ArrayInitIndex = -1;
911 
912     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
913     /// notes attached to it will also be stored, otherwise they will not be.
914     bool HasActiveDiagnostic;
915 
916     /// Have we emitted a diagnostic explaining why we couldn't constant
917     /// fold (not just why it's not strictly a constant expression)?
918     bool HasFoldFailureDiagnostic;
919 
920     /// Whether or not we're in a context where the front end requires a
921     /// constant value.
922     bool InConstantContext;
923 
924     /// Whether we're checking that an expression is a potential constant
925     /// expression. If so, do not fail on constructs that could become constant
926     /// later on (such as a use of an undefined global).
927     bool CheckingPotentialConstantExpression = false;
928 
929     /// Whether we're checking for an expression that has undefined behavior.
930     /// If so, we will produce warnings if we encounter an operation that is
931     /// always undefined.
932     ///
933     /// Note that we still need to evaluate the expression normally when this
934     /// is set; this is used when evaluating ICEs in C.
935     bool CheckingForUndefinedBehavior = false;
936 
937     enum EvaluationMode {
938       /// Evaluate as a constant expression. Stop if we find that the expression
939       /// is not a constant expression.
940       EM_ConstantExpression,
941 
942       /// Evaluate as a constant expression. Stop if we find that the expression
943       /// is not a constant expression. Some expressions can be retried in the
944       /// optimizer if we don't constant fold them here, but in an unevaluated
945       /// context we try to fold them immediately since the optimizer never
946       /// gets a chance to look at it.
947       EM_ConstantExpressionUnevaluated,
948 
949       /// Fold the expression to a constant. Stop if we hit a side-effect that
950       /// we can't model.
951       EM_ConstantFold,
952 
953       /// Evaluate in any way we know how. Don't worry about side-effects that
954       /// can't be modeled.
955       EM_IgnoreSideEffects,
956     } EvalMode;
957 
958     /// Are we checking whether the expression is a potential constant
959     /// expression?
960     bool checkingPotentialConstantExpression() const override  {
961       return CheckingPotentialConstantExpression;
962     }
963 
964     /// Are we checking an expression for overflow?
965     // FIXME: We should check for any kind of undefined or suspicious behavior
966     // in such constructs, not just overflow.
967     bool checkingForUndefinedBehavior() const override {
968       return CheckingForUndefinedBehavior;
969     }
970 
971     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
972         : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
973           CallStackDepth(0), NextCallIndex(1),
974           StepsLeft(C.getLangOpts().ConstexprStepLimit),
975           EnableNewConstInterp(C.getLangOpts().EnableNewConstInterp),
976           BottomFrame(*this, SourceLocation(), nullptr, nullptr, CallRef()),
977           EvaluatingDecl((const ValueDecl *)nullptr),
978           EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
979           HasFoldFailureDiagnostic(false), InConstantContext(false),
980           EvalMode(Mode) {}
981 
982     ~EvalInfo() {
983       discardCleanups();
984     }
985 
986     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value,
987                            EvaluatingDeclKind EDK = EvaluatingDeclKind::Ctor) {
988       EvaluatingDecl = Base;
989       IsEvaluatingDecl = EDK;
990       EvaluatingDeclValue = &Value;
991     }
992 
993     bool CheckCallLimit(SourceLocation Loc) {
994       // Don't perform any constexpr calls (other than the call we're checking)
995       // when checking a potential constant expression.
996       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
997         return false;
998       if (NextCallIndex == 0) {
999         // NextCallIndex has wrapped around.
1000         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
1001         return false;
1002       }
1003       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
1004         return true;
1005       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
1006         << getLangOpts().ConstexprCallDepth;
1007       return false;
1008     }
1009 
1010     std::pair<CallStackFrame *, unsigned>
1011     getCallFrameAndDepth(unsigned CallIndex) {
1012       assert(CallIndex && "no call index in getCallFrameAndDepth");
1013       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
1014       // be null in this loop.
1015       unsigned Depth = CallStackDepth;
1016       CallStackFrame *Frame = CurrentCall;
1017       while (Frame->Index > CallIndex) {
1018         Frame = Frame->Caller;
1019         --Depth;
1020       }
1021       if (Frame->Index == CallIndex)
1022         return {Frame, Depth};
1023       return {nullptr, 0};
1024     }
1025 
1026     bool nextStep(const Stmt *S) {
1027       if (!StepsLeft) {
1028         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
1029         return false;
1030       }
1031       --StepsLeft;
1032       return true;
1033     }
1034 
1035     APValue *createHeapAlloc(const Expr *E, QualType T, LValue &LV);
1036 
1037     Optional<DynAlloc*> lookupDynamicAlloc(DynamicAllocLValue DA) {
1038       Optional<DynAlloc*> Result;
1039       auto It = HeapAllocs.find(DA);
1040       if (It != HeapAllocs.end())
1041         Result = &It->second;
1042       return Result;
1043     }
1044 
1045     /// Get the allocated storage for the given parameter of the given call.
1046     APValue *getParamSlot(CallRef Call, const ParmVarDecl *PVD) {
1047       CallStackFrame *Frame = getCallFrameAndDepth(Call.CallIndex).first;
1048       return Frame ? Frame->getTemporary(Call.getOrigParam(PVD), Call.Version)
1049                    : nullptr;
1050     }
1051 
1052     /// Information about a stack frame for std::allocator<T>::[de]allocate.
1053     struct StdAllocatorCaller {
1054       unsigned FrameIndex;
1055       QualType ElemType;
1056       explicit operator bool() const { return FrameIndex != 0; };
1057     };
1058 
1059     StdAllocatorCaller getStdAllocatorCaller(StringRef FnName) const {
1060       for (const CallStackFrame *Call = CurrentCall; Call != &BottomFrame;
1061            Call = Call->Caller) {
1062         const auto *MD = dyn_cast_or_null<CXXMethodDecl>(Call->Callee);
1063         if (!MD)
1064           continue;
1065         const IdentifierInfo *FnII = MD->getIdentifier();
1066         if (!FnII || !FnII->isStr(FnName))
1067           continue;
1068 
1069         const auto *CTSD =
1070             dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
1071         if (!CTSD)
1072           continue;
1073 
1074         const IdentifierInfo *ClassII = CTSD->getIdentifier();
1075         const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
1076         if (CTSD->isInStdNamespace() && ClassII &&
1077             ClassII->isStr("allocator") && TAL.size() >= 1 &&
1078             TAL[0].getKind() == TemplateArgument::Type)
1079           return {Call->Index, TAL[0].getAsType()};
1080       }
1081 
1082       return {};
1083     }
1084 
1085     void performLifetimeExtension() {
1086       // Disable the cleanups for lifetime-extended temporaries.
1087       CleanupStack.erase(std::remove_if(CleanupStack.begin(),
1088                                         CleanupStack.end(),
1089                                         [](Cleanup &C) {
1090                                           return !C.isDestroyedAtEndOf(
1091                                               ScopeKind::FullExpression);
1092                                         }),
1093                          CleanupStack.end());
1094      }
1095 
1096     /// Throw away any remaining cleanups at the end of evaluation. If any
1097     /// cleanups would have had a side-effect, note that as an unmodeled
1098     /// side-effect and return false. Otherwise, return true.
1099     bool discardCleanups() {
1100       for (Cleanup &C : CleanupStack) {
1101         if (C.hasSideEffect() && !noteSideEffect()) {
1102           CleanupStack.clear();
1103           return false;
1104         }
1105       }
1106       CleanupStack.clear();
1107       return true;
1108     }
1109 
1110   private:
1111     interp::Frame *getCurrentFrame() override { return CurrentCall; }
1112     const interp::Frame *getBottomFrame() const override { return &BottomFrame; }
1113 
1114     bool hasActiveDiagnostic() override { return HasActiveDiagnostic; }
1115     void setActiveDiagnostic(bool Flag) override { HasActiveDiagnostic = Flag; }
1116 
1117     void setFoldFailureDiagnostic(bool Flag) override {
1118       HasFoldFailureDiagnostic = Flag;
1119     }
1120 
1121     Expr::EvalStatus &getEvalStatus() const override { return EvalStatus; }
1122 
1123     ASTContext &getCtx() const override { return Ctx; }
1124 
1125     // If we have a prior diagnostic, it will be noting that the expression
1126     // isn't a constant expression. This diagnostic is more important,
1127     // unless we require this evaluation to produce a constant expression.
1128     //
1129     // FIXME: We might want to show both diagnostics to the user in
1130     // EM_ConstantFold mode.
1131     bool hasPriorDiagnostic() override {
1132       if (!EvalStatus.Diag->empty()) {
1133         switch (EvalMode) {
1134         case EM_ConstantFold:
1135         case EM_IgnoreSideEffects:
1136           if (!HasFoldFailureDiagnostic)
1137             break;
1138           // We've already failed to fold something. Keep that diagnostic.
1139           LLVM_FALLTHROUGH;
1140         case EM_ConstantExpression:
1141         case EM_ConstantExpressionUnevaluated:
1142           setActiveDiagnostic(false);
1143           return true;
1144         }
1145       }
1146       return false;
1147     }
1148 
1149     unsigned getCallStackDepth() override { return CallStackDepth; }
1150 
1151   public:
1152     /// Should we continue evaluation after encountering a side-effect that we
1153     /// couldn't model?
1154     bool keepEvaluatingAfterSideEffect() {
1155       switch (EvalMode) {
1156       case EM_IgnoreSideEffects:
1157         return true;
1158 
1159       case EM_ConstantExpression:
1160       case EM_ConstantExpressionUnevaluated:
1161       case EM_ConstantFold:
1162         // By default, assume any side effect might be valid in some other
1163         // evaluation of this expression from a different context.
1164         return checkingPotentialConstantExpression() ||
1165                checkingForUndefinedBehavior();
1166       }
1167       llvm_unreachable("Missed EvalMode case");
1168     }
1169 
1170     /// Note that we have had a side-effect, and determine whether we should
1171     /// keep evaluating.
1172     bool noteSideEffect() {
1173       EvalStatus.HasSideEffects = true;
1174       return keepEvaluatingAfterSideEffect();
1175     }
1176 
1177     /// Should we continue evaluation after encountering undefined behavior?
1178     bool keepEvaluatingAfterUndefinedBehavior() {
1179       switch (EvalMode) {
1180       case EM_IgnoreSideEffects:
1181       case EM_ConstantFold:
1182         return true;
1183 
1184       case EM_ConstantExpression:
1185       case EM_ConstantExpressionUnevaluated:
1186         return checkingForUndefinedBehavior();
1187       }
1188       llvm_unreachable("Missed EvalMode case");
1189     }
1190 
1191     /// Note that we hit something that was technically undefined behavior, but
1192     /// that we can evaluate past it (such as signed overflow or floating-point
1193     /// division by zero.)
1194     bool noteUndefinedBehavior() override {
1195       EvalStatus.HasUndefinedBehavior = true;
1196       return keepEvaluatingAfterUndefinedBehavior();
1197     }
1198 
1199     /// Should we continue evaluation as much as possible after encountering a
1200     /// construct which can't be reduced to a value?
1201     bool keepEvaluatingAfterFailure() const override {
1202       if (!StepsLeft)
1203         return false;
1204 
1205       switch (EvalMode) {
1206       case EM_ConstantExpression:
1207       case EM_ConstantExpressionUnevaluated:
1208       case EM_ConstantFold:
1209       case EM_IgnoreSideEffects:
1210         return checkingPotentialConstantExpression() ||
1211                checkingForUndefinedBehavior();
1212       }
1213       llvm_unreachable("Missed EvalMode case");
1214     }
1215 
1216     /// Notes that we failed to evaluate an expression that other expressions
1217     /// directly depend on, and determine if we should keep evaluating. This
1218     /// should only be called if we actually intend to keep evaluating.
1219     ///
1220     /// Call noteSideEffect() instead if we may be able to ignore the value that
1221     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1222     ///
1223     /// (Foo(), 1)      // use noteSideEffect
1224     /// (Foo() || true) // use noteSideEffect
1225     /// Foo() + 1       // use noteFailure
1226     LLVM_NODISCARD bool noteFailure() {
1227       // Failure when evaluating some expression often means there is some
1228       // subexpression whose evaluation was skipped. Therefore, (because we
1229       // don't track whether we skipped an expression when unwinding after an
1230       // evaluation failure) every evaluation failure that bubbles up from a
1231       // subexpression implies that a side-effect has potentially happened. We
1232       // skip setting the HasSideEffects flag to true until we decide to
1233       // continue evaluating after that point, which happens here.
1234       bool KeepGoing = keepEvaluatingAfterFailure();
1235       EvalStatus.HasSideEffects |= KeepGoing;
1236       return KeepGoing;
1237     }
1238 
1239     class ArrayInitLoopIndex {
1240       EvalInfo &Info;
1241       uint64_t OuterIndex;
1242 
1243     public:
1244       ArrayInitLoopIndex(EvalInfo &Info)
1245           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1246         Info.ArrayInitIndex = 0;
1247       }
1248       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1249 
1250       operator uint64_t&() { return Info.ArrayInitIndex; }
1251     };
1252   };
1253 
1254   /// Object used to treat all foldable expressions as constant expressions.
1255   struct FoldConstant {
1256     EvalInfo &Info;
1257     bool Enabled;
1258     bool HadNoPriorDiags;
1259     EvalInfo::EvaluationMode OldMode;
1260 
1261     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1262       : Info(Info),
1263         Enabled(Enabled),
1264         HadNoPriorDiags(Info.EvalStatus.Diag &&
1265                         Info.EvalStatus.Diag->empty() &&
1266                         !Info.EvalStatus.HasSideEffects),
1267         OldMode(Info.EvalMode) {
1268       if (Enabled)
1269         Info.EvalMode = EvalInfo::EM_ConstantFold;
1270     }
1271     void keepDiagnostics() { Enabled = false; }
1272     ~FoldConstant() {
1273       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1274           !Info.EvalStatus.HasSideEffects)
1275         Info.EvalStatus.Diag->clear();
1276       Info.EvalMode = OldMode;
1277     }
1278   };
1279 
1280   /// RAII object used to set the current evaluation mode to ignore
1281   /// side-effects.
1282   struct IgnoreSideEffectsRAII {
1283     EvalInfo &Info;
1284     EvalInfo::EvaluationMode OldMode;
1285     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1286         : Info(Info), OldMode(Info.EvalMode) {
1287       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1288     }
1289 
1290     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1291   };
1292 
1293   /// RAII object used to optionally suppress diagnostics and side-effects from
1294   /// a speculative evaluation.
1295   class SpeculativeEvaluationRAII {
1296     EvalInfo *Info = nullptr;
1297     Expr::EvalStatus OldStatus;
1298     unsigned OldSpeculativeEvaluationDepth;
1299 
1300     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1301       Info = Other.Info;
1302       OldStatus = Other.OldStatus;
1303       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1304       Other.Info = nullptr;
1305     }
1306 
1307     void maybeRestoreState() {
1308       if (!Info)
1309         return;
1310 
1311       Info->EvalStatus = OldStatus;
1312       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1313     }
1314 
1315   public:
1316     SpeculativeEvaluationRAII() = default;
1317 
1318     SpeculativeEvaluationRAII(
1319         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1320         : Info(&Info), OldStatus(Info.EvalStatus),
1321           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1322       Info.EvalStatus.Diag = NewDiag;
1323       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1324     }
1325 
1326     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1327     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1328       moveFromAndCancel(std::move(Other));
1329     }
1330 
1331     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1332       maybeRestoreState();
1333       moveFromAndCancel(std::move(Other));
1334       return *this;
1335     }
1336 
1337     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1338   };
1339 
1340   /// RAII object wrapping a full-expression or block scope, and handling
1341   /// the ending of the lifetime of temporaries created within it.
1342   template<ScopeKind Kind>
1343   class ScopeRAII {
1344     EvalInfo &Info;
1345     unsigned OldStackSize;
1346   public:
1347     ScopeRAII(EvalInfo &Info)
1348         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1349       // Push a new temporary version. This is needed to distinguish between
1350       // temporaries created in different iterations of a loop.
1351       Info.CurrentCall->pushTempVersion();
1352     }
1353     bool destroy(bool RunDestructors = true) {
1354       bool OK = cleanup(Info, RunDestructors, OldStackSize);
1355       OldStackSize = -1U;
1356       return OK;
1357     }
1358     ~ScopeRAII() {
1359       if (OldStackSize != -1U)
1360         destroy(false);
1361       // Body moved to a static method to encourage the compiler to inline away
1362       // instances of this class.
1363       Info.CurrentCall->popTempVersion();
1364     }
1365   private:
1366     static bool cleanup(EvalInfo &Info, bool RunDestructors,
1367                         unsigned OldStackSize) {
1368       assert(OldStackSize <= Info.CleanupStack.size() &&
1369              "running cleanups out of order?");
1370 
1371       // Run all cleanups for a block scope, and non-lifetime-extended cleanups
1372       // for a full-expression scope.
1373       bool Success = true;
1374       for (unsigned I = Info.CleanupStack.size(); I > OldStackSize; --I) {
1375         if (Info.CleanupStack[I - 1].isDestroyedAtEndOf(Kind)) {
1376           if (!Info.CleanupStack[I - 1].endLifetime(Info, RunDestructors)) {
1377             Success = false;
1378             break;
1379           }
1380         }
1381       }
1382 
1383       // Compact any retained cleanups.
1384       auto NewEnd = Info.CleanupStack.begin() + OldStackSize;
1385       if (Kind != ScopeKind::Block)
1386         NewEnd =
1387             std::remove_if(NewEnd, Info.CleanupStack.end(), [](Cleanup &C) {
1388               return C.isDestroyedAtEndOf(Kind);
1389             });
1390       Info.CleanupStack.erase(NewEnd, Info.CleanupStack.end());
1391       return Success;
1392     }
1393   };
1394   typedef ScopeRAII<ScopeKind::Block> BlockScopeRAII;
1395   typedef ScopeRAII<ScopeKind::FullExpression> FullExpressionRAII;
1396   typedef ScopeRAII<ScopeKind::Call> CallScopeRAII;
1397 }
1398 
1399 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1400                                          CheckSubobjectKind CSK) {
1401   if (Invalid)
1402     return false;
1403   if (isOnePastTheEnd()) {
1404     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1405       << CSK;
1406     setInvalid();
1407     return false;
1408   }
1409   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1410   // must actually be at least one array element; even a VLA cannot have a
1411   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1412   return true;
1413 }
1414 
1415 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1416                                                                 const Expr *E) {
1417   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1418   // Do not set the designator as invalid: we can represent this situation,
1419   // and correct handling of __builtin_object_size requires us to do so.
1420 }
1421 
1422 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1423                                                     const Expr *E,
1424                                                     const APSInt &N) {
1425   // If we're complaining, we must be able to statically determine the size of
1426   // the most derived array.
1427   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1428     Info.CCEDiag(E, diag::note_constexpr_array_index)
1429       << N << /*array*/ 0
1430       << static_cast<unsigned>(getMostDerivedArraySize());
1431   else
1432     Info.CCEDiag(E, diag::note_constexpr_array_index)
1433       << N << /*non-array*/ 1;
1434   setInvalid();
1435 }
1436 
1437 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1438                                const FunctionDecl *Callee, const LValue *This,
1439                                CallRef Call)
1440     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1441       Arguments(Call), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1442   Info.CurrentCall = this;
1443   ++Info.CallStackDepth;
1444 }
1445 
1446 CallStackFrame::~CallStackFrame() {
1447   assert(Info.CurrentCall == this && "calls retired out of order");
1448   --Info.CallStackDepth;
1449   Info.CurrentCall = Caller;
1450 }
1451 
1452 static bool isRead(AccessKinds AK) {
1453   return AK == AK_Read || AK == AK_ReadObjectRepresentation;
1454 }
1455 
1456 static bool isModification(AccessKinds AK) {
1457   switch (AK) {
1458   case AK_Read:
1459   case AK_ReadObjectRepresentation:
1460   case AK_MemberCall:
1461   case AK_DynamicCast:
1462   case AK_TypeId:
1463     return false;
1464   case AK_Assign:
1465   case AK_Increment:
1466   case AK_Decrement:
1467   case AK_Construct:
1468   case AK_Destroy:
1469     return true;
1470   }
1471   llvm_unreachable("unknown access kind");
1472 }
1473 
1474 static bool isAnyAccess(AccessKinds AK) {
1475   return isRead(AK) || isModification(AK);
1476 }
1477 
1478 /// Is this an access per the C++ definition?
1479 static bool isFormalAccess(AccessKinds AK) {
1480   return isAnyAccess(AK) && AK != AK_Construct && AK != AK_Destroy;
1481 }
1482 
1483 /// Is this kind of axcess valid on an indeterminate object value?
1484 static bool isValidIndeterminateAccess(AccessKinds AK) {
1485   switch (AK) {
1486   case AK_Read:
1487   case AK_Increment:
1488   case AK_Decrement:
1489     // These need the object's value.
1490     return false;
1491 
1492   case AK_ReadObjectRepresentation:
1493   case AK_Assign:
1494   case AK_Construct:
1495   case AK_Destroy:
1496     // Construction and destruction don't need the value.
1497     return true;
1498 
1499   case AK_MemberCall:
1500   case AK_DynamicCast:
1501   case AK_TypeId:
1502     // These aren't really meaningful on scalars.
1503     return true;
1504   }
1505   llvm_unreachable("unknown access kind");
1506 }
1507 
1508 namespace {
1509   struct ComplexValue {
1510   private:
1511     bool IsInt;
1512 
1513   public:
1514     APSInt IntReal, IntImag;
1515     APFloat FloatReal, FloatImag;
1516 
1517     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1518 
1519     void makeComplexFloat() { IsInt = false; }
1520     bool isComplexFloat() const { return !IsInt; }
1521     APFloat &getComplexFloatReal() { return FloatReal; }
1522     APFloat &getComplexFloatImag() { return FloatImag; }
1523 
1524     void makeComplexInt() { IsInt = true; }
1525     bool isComplexInt() const { return IsInt; }
1526     APSInt &getComplexIntReal() { return IntReal; }
1527     APSInt &getComplexIntImag() { return IntImag; }
1528 
1529     void moveInto(APValue &v) const {
1530       if (isComplexFloat())
1531         v = APValue(FloatReal, FloatImag);
1532       else
1533         v = APValue(IntReal, IntImag);
1534     }
1535     void setFrom(const APValue &v) {
1536       assert(v.isComplexFloat() || v.isComplexInt());
1537       if (v.isComplexFloat()) {
1538         makeComplexFloat();
1539         FloatReal = v.getComplexFloatReal();
1540         FloatImag = v.getComplexFloatImag();
1541       } else {
1542         makeComplexInt();
1543         IntReal = v.getComplexIntReal();
1544         IntImag = v.getComplexIntImag();
1545       }
1546     }
1547   };
1548 
1549   struct LValue {
1550     APValue::LValueBase Base;
1551     CharUnits Offset;
1552     SubobjectDesignator Designator;
1553     bool IsNullPtr : 1;
1554     bool InvalidBase : 1;
1555 
1556     const APValue::LValueBase getLValueBase() const { return Base; }
1557     CharUnits &getLValueOffset() { return Offset; }
1558     const CharUnits &getLValueOffset() const { return Offset; }
1559     SubobjectDesignator &getLValueDesignator() { return Designator; }
1560     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1561     bool isNullPointer() const { return IsNullPtr;}
1562 
1563     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1564     unsigned getLValueVersion() const { return Base.getVersion(); }
1565 
1566     void moveInto(APValue &V) const {
1567       if (Designator.Invalid)
1568         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1569       else {
1570         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1571         V = APValue(Base, Offset, Designator.Entries,
1572                     Designator.IsOnePastTheEnd, IsNullPtr);
1573       }
1574     }
1575     void setFrom(ASTContext &Ctx, const APValue &V) {
1576       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1577       Base = V.getLValueBase();
1578       Offset = V.getLValueOffset();
1579       InvalidBase = false;
1580       Designator = SubobjectDesignator(Ctx, V);
1581       IsNullPtr = V.isNullPointer();
1582     }
1583 
1584     void set(APValue::LValueBase B, bool BInvalid = false) {
1585 #ifndef NDEBUG
1586       // We only allow a few types of invalid bases. Enforce that here.
1587       if (BInvalid) {
1588         const auto *E = B.get<const Expr *>();
1589         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1590                "Unexpected type of invalid base");
1591       }
1592 #endif
1593 
1594       Base = B;
1595       Offset = CharUnits::fromQuantity(0);
1596       InvalidBase = BInvalid;
1597       Designator = SubobjectDesignator(getType(B));
1598       IsNullPtr = false;
1599     }
1600 
1601     void setNull(ASTContext &Ctx, QualType PointerTy) {
1602       Base = (const ValueDecl *)nullptr;
1603       Offset =
1604           CharUnits::fromQuantity(Ctx.getTargetNullPointerValue(PointerTy));
1605       InvalidBase = false;
1606       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1607       IsNullPtr = true;
1608     }
1609 
1610     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1611       set(B, true);
1612     }
1613 
1614     std::string toString(ASTContext &Ctx, QualType T) const {
1615       APValue Printable;
1616       moveInto(Printable);
1617       return Printable.getAsString(Ctx, T);
1618     }
1619 
1620   private:
1621     // Check that this LValue is not based on a null pointer. If it is, produce
1622     // a diagnostic and mark the designator as invalid.
1623     template <typename GenDiagType>
1624     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1625       if (Designator.Invalid)
1626         return false;
1627       if (IsNullPtr) {
1628         GenDiag();
1629         Designator.setInvalid();
1630         return false;
1631       }
1632       return true;
1633     }
1634 
1635   public:
1636     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1637                           CheckSubobjectKind CSK) {
1638       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1639         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1640       });
1641     }
1642 
1643     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1644                                        AccessKinds AK) {
1645       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1646         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1647       });
1648     }
1649 
1650     // Check this LValue refers to an object. If not, set the designator to be
1651     // invalid and emit a diagnostic.
1652     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1653       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1654              Designator.checkSubobject(Info, E, CSK);
1655     }
1656 
1657     void addDecl(EvalInfo &Info, const Expr *E,
1658                  const Decl *D, bool Virtual = false) {
1659       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1660         Designator.addDeclUnchecked(D, Virtual);
1661     }
1662     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1663       if (!Designator.Entries.empty()) {
1664         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1665         Designator.setInvalid();
1666         return;
1667       }
1668       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1669         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1670         Designator.FirstEntryIsAnUnsizedArray = true;
1671         Designator.addUnsizedArrayUnchecked(ElemTy);
1672       }
1673     }
1674     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1675       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1676         Designator.addArrayUnchecked(CAT);
1677     }
1678     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1679       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1680         Designator.addComplexUnchecked(EltTy, Imag);
1681     }
1682     void clearIsNullPointer() {
1683       IsNullPtr = false;
1684     }
1685     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1686                               const APSInt &Index, CharUnits ElementSize) {
1687       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1688       // but we're not required to diagnose it and it's valid in C++.)
1689       if (!Index)
1690         return;
1691 
1692       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1693       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1694       // offsets.
1695       uint64_t Offset64 = Offset.getQuantity();
1696       uint64_t ElemSize64 = ElementSize.getQuantity();
1697       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1698       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1699 
1700       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1701         Designator.adjustIndex(Info, E, Index);
1702       clearIsNullPointer();
1703     }
1704     void adjustOffset(CharUnits N) {
1705       Offset += N;
1706       if (N.getQuantity())
1707         clearIsNullPointer();
1708     }
1709   };
1710 
1711   struct MemberPtr {
1712     MemberPtr() {}
1713     explicit MemberPtr(const ValueDecl *Decl) :
1714       DeclAndIsDerivedMember(Decl, false), Path() {}
1715 
1716     /// The member or (direct or indirect) field referred to by this member
1717     /// pointer, or 0 if this is a null member pointer.
1718     const ValueDecl *getDecl() const {
1719       return DeclAndIsDerivedMember.getPointer();
1720     }
1721     /// Is this actually a member of some type derived from the relevant class?
1722     bool isDerivedMember() const {
1723       return DeclAndIsDerivedMember.getInt();
1724     }
1725     /// Get the class which the declaration actually lives in.
1726     const CXXRecordDecl *getContainingRecord() const {
1727       return cast<CXXRecordDecl>(
1728           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1729     }
1730 
1731     void moveInto(APValue &V) const {
1732       V = APValue(getDecl(), isDerivedMember(), Path);
1733     }
1734     void setFrom(const APValue &V) {
1735       assert(V.isMemberPointer());
1736       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1737       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1738       Path.clear();
1739       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1740       Path.insert(Path.end(), P.begin(), P.end());
1741     }
1742 
1743     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1744     /// whether the member is a member of some class derived from the class type
1745     /// of the member pointer.
1746     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1747     /// Path - The path of base/derived classes from the member declaration's
1748     /// class (exclusive) to the class type of the member pointer (inclusive).
1749     SmallVector<const CXXRecordDecl*, 4> Path;
1750 
1751     /// Perform a cast towards the class of the Decl (either up or down the
1752     /// hierarchy).
1753     bool castBack(const CXXRecordDecl *Class) {
1754       assert(!Path.empty());
1755       const CXXRecordDecl *Expected;
1756       if (Path.size() >= 2)
1757         Expected = Path[Path.size() - 2];
1758       else
1759         Expected = getContainingRecord();
1760       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1761         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1762         // if B does not contain the original member and is not a base or
1763         // derived class of the class containing the original member, the result
1764         // of the cast is undefined.
1765         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1766         // (D::*). We consider that to be a language defect.
1767         return false;
1768       }
1769       Path.pop_back();
1770       return true;
1771     }
1772     /// Perform a base-to-derived member pointer cast.
1773     bool castToDerived(const CXXRecordDecl *Derived) {
1774       if (!getDecl())
1775         return true;
1776       if (!isDerivedMember()) {
1777         Path.push_back(Derived);
1778         return true;
1779       }
1780       if (!castBack(Derived))
1781         return false;
1782       if (Path.empty())
1783         DeclAndIsDerivedMember.setInt(false);
1784       return true;
1785     }
1786     /// Perform a derived-to-base member pointer cast.
1787     bool castToBase(const CXXRecordDecl *Base) {
1788       if (!getDecl())
1789         return true;
1790       if (Path.empty())
1791         DeclAndIsDerivedMember.setInt(true);
1792       if (isDerivedMember()) {
1793         Path.push_back(Base);
1794         return true;
1795       }
1796       return castBack(Base);
1797     }
1798   };
1799 
1800   /// Compare two member pointers, which are assumed to be of the same type.
1801   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1802     if (!LHS.getDecl() || !RHS.getDecl())
1803       return !LHS.getDecl() && !RHS.getDecl();
1804     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1805       return false;
1806     return LHS.Path == RHS.Path;
1807   }
1808 }
1809 
1810 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1811 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1812                             const LValue &This, const Expr *E,
1813                             bool AllowNonLiteralTypes = false);
1814 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1815                            bool InvalidBaseOK = false);
1816 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1817                             bool InvalidBaseOK = false);
1818 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1819                                   EvalInfo &Info);
1820 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1821 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1822 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1823                                     EvalInfo &Info);
1824 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1825 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1826 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1827                            EvalInfo &Info);
1828 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1829 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
1830                                   EvalInfo &Info);
1831 
1832 /// Evaluate an integer or fixed point expression into an APResult.
1833 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1834                                         EvalInfo &Info);
1835 
1836 /// Evaluate only a fixed point expression into an APResult.
1837 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1838                                EvalInfo &Info);
1839 
1840 //===----------------------------------------------------------------------===//
1841 // Misc utilities
1842 //===----------------------------------------------------------------------===//
1843 
1844 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1845 /// preserving its value (by extending by up to one bit as needed).
1846 static void negateAsSigned(APSInt &Int) {
1847   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1848     Int = Int.extend(Int.getBitWidth() + 1);
1849     Int.setIsSigned(true);
1850   }
1851   Int = -Int;
1852 }
1853 
1854 template<typename KeyT>
1855 APValue &CallStackFrame::createTemporary(const KeyT *Key, QualType T,
1856                                          ScopeKind Scope, LValue &LV) {
1857   unsigned Version = getTempVersion();
1858   APValue::LValueBase Base(Key, Index, Version);
1859   LV.set(Base);
1860   return createLocal(Base, Key, T, Scope);
1861 }
1862 
1863 /// Allocate storage for a parameter of a function call made in this frame.
1864 APValue &CallStackFrame::createParam(CallRef Args, const ParmVarDecl *PVD,
1865                                      LValue &LV) {
1866   assert(Args.CallIndex == Index && "creating parameter in wrong frame");
1867   APValue::LValueBase Base(PVD, Index, Args.Version);
1868   LV.set(Base);
1869   // We always destroy parameters at the end of the call, even if we'd allow
1870   // them to live to the end of the full-expression at runtime, in order to
1871   // give portable results and match other compilers.
1872   return createLocal(Base, PVD, PVD->getType(), ScopeKind::Call);
1873 }
1874 
1875 APValue &CallStackFrame::createLocal(APValue::LValueBase Base, const void *Key,
1876                                      QualType T, ScopeKind Scope) {
1877   assert(Base.getCallIndex() == Index && "lvalue for wrong frame");
1878   unsigned Version = Base.getVersion();
1879   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1880   assert(Result.isAbsent() && "local created multiple times");
1881 
1882   // If we're creating a local immediately in the operand of a speculative
1883   // evaluation, don't register a cleanup to be run outside the speculative
1884   // evaluation context, since we won't actually be able to initialize this
1885   // object.
1886   if (Index <= Info.SpeculativeEvaluationDepth) {
1887     if (T.isDestructedType())
1888       Info.noteSideEffect();
1889   } else {
1890     Info.CleanupStack.push_back(Cleanup(&Result, Base, T, Scope));
1891   }
1892   return Result;
1893 }
1894 
1895 APValue *EvalInfo::createHeapAlloc(const Expr *E, QualType T, LValue &LV) {
1896   if (NumHeapAllocs > DynamicAllocLValue::getMaxIndex()) {
1897     FFDiag(E, diag::note_constexpr_heap_alloc_limit_exceeded);
1898     return nullptr;
1899   }
1900 
1901   DynamicAllocLValue DA(NumHeapAllocs++);
1902   LV.set(APValue::LValueBase::getDynamicAlloc(DA, T));
1903   auto Result = HeapAllocs.emplace(std::piecewise_construct,
1904                                    std::forward_as_tuple(DA), std::tuple<>());
1905   assert(Result.second && "reused a heap alloc index?");
1906   Result.first->second.AllocExpr = E;
1907   return &Result.first->second.Value;
1908 }
1909 
1910 /// Produce a string describing the given constexpr call.
1911 void CallStackFrame::describe(raw_ostream &Out) {
1912   unsigned ArgIndex = 0;
1913   bool IsMemberCall = isa<CXXMethodDecl>(Callee) &&
1914                       !isa<CXXConstructorDecl>(Callee) &&
1915                       cast<CXXMethodDecl>(Callee)->isInstance();
1916 
1917   if (!IsMemberCall)
1918     Out << *Callee << '(';
1919 
1920   if (This && IsMemberCall) {
1921     APValue Val;
1922     This->moveInto(Val);
1923     Val.printPretty(Out, Info.Ctx,
1924                     This->Designator.MostDerivedType);
1925     // FIXME: Add parens around Val if needed.
1926     Out << "->" << *Callee << '(';
1927     IsMemberCall = false;
1928   }
1929 
1930   for (FunctionDecl::param_const_iterator I = Callee->param_begin(),
1931        E = Callee->param_end(); I != E; ++I, ++ArgIndex) {
1932     if (ArgIndex > (unsigned)IsMemberCall)
1933       Out << ", ";
1934 
1935     const ParmVarDecl *Param = *I;
1936     APValue *V = Info.getParamSlot(Arguments, Param);
1937     if (V)
1938       V->printPretty(Out, Info.Ctx, Param->getType());
1939     else
1940       Out << "<...>";
1941 
1942     if (ArgIndex == 0 && IsMemberCall)
1943       Out << "->" << *Callee << '(';
1944   }
1945 
1946   Out << ')';
1947 }
1948 
1949 /// Evaluate an expression to see if it had side-effects, and discard its
1950 /// result.
1951 /// \return \c true if the caller should keep evaluating.
1952 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1953   assert(!E->isValueDependent());
1954   APValue Scratch;
1955   if (!Evaluate(Scratch, Info, E))
1956     // We don't need the value, but we might have skipped a side effect here.
1957     return Info.noteSideEffect();
1958   return true;
1959 }
1960 
1961 /// Should this call expression be treated as a string literal?
1962 static bool IsStringLiteralCall(const CallExpr *E) {
1963   unsigned Builtin = E->getBuiltinCallee();
1964   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1965           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1966 }
1967 
1968 static bool IsGlobalLValue(APValue::LValueBase B) {
1969   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1970   // constant expression of pointer type that evaluates to...
1971 
1972   // ... a null pointer value, or a prvalue core constant expression of type
1973   // std::nullptr_t.
1974   if (!B) return true;
1975 
1976   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1977     // ... the address of an object with static storage duration,
1978     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1979       return VD->hasGlobalStorage();
1980     if (isa<TemplateParamObjectDecl>(D))
1981       return true;
1982     // ... the address of a function,
1983     // ... the address of a GUID [MS extension],
1984     return isa<FunctionDecl>(D) || isa<MSGuidDecl>(D);
1985   }
1986 
1987   if (B.is<TypeInfoLValue>() || B.is<DynamicAllocLValue>())
1988     return true;
1989 
1990   const Expr *E = B.get<const Expr*>();
1991   switch (E->getStmtClass()) {
1992   default:
1993     return false;
1994   case Expr::CompoundLiteralExprClass: {
1995     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1996     return CLE->isFileScope() && CLE->isLValue();
1997   }
1998   case Expr::MaterializeTemporaryExprClass:
1999     // A materialized temporary might have been lifetime-extended to static
2000     // storage duration.
2001     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
2002   // A string literal has static storage duration.
2003   case Expr::StringLiteralClass:
2004   case Expr::PredefinedExprClass:
2005   case Expr::ObjCStringLiteralClass:
2006   case Expr::ObjCEncodeExprClass:
2007     return true;
2008   case Expr::ObjCBoxedExprClass:
2009     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
2010   case Expr::CallExprClass:
2011     return IsStringLiteralCall(cast<CallExpr>(E));
2012   // For GCC compatibility, &&label has static storage duration.
2013   case Expr::AddrLabelExprClass:
2014     return true;
2015   // A Block literal expression may be used as the initialization value for
2016   // Block variables at global or local static scope.
2017   case Expr::BlockExprClass:
2018     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
2019   case Expr::ImplicitValueInitExprClass:
2020     // FIXME:
2021     // We can never form an lvalue with an implicit value initialization as its
2022     // base through expression evaluation, so these only appear in one case: the
2023     // implicit variable declaration we invent when checking whether a constexpr
2024     // constructor can produce a constant expression. We must assume that such
2025     // an expression might be a global lvalue.
2026     return true;
2027   }
2028 }
2029 
2030 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
2031   return LVal.Base.dyn_cast<const ValueDecl*>();
2032 }
2033 
2034 static bool IsLiteralLValue(const LValue &Value) {
2035   if (Value.getLValueCallIndex())
2036     return false;
2037   const Expr *E = Value.Base.dyn_cast<const Expr*>();
2038   return E && !isa<MaterializeTemporaryExpr>(E);
2039 }
2040 
2041 static bool IsWeakLValue(const LValue &Value) {
2042   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2043   return Decl && Decl->isWeak();
2044 }
2045 
2046 static bool isZeroSized(const LValue &Value) {
2047   const ValueDecl *Decl = GetLValueBaseDecl(Value);
2048   if (Decl && isa<VarDecl>(Decl)) {
2049     QualType Ty = Decl->getType();
2050     if (Ty->isArrayType())
2051       return Ty->isIncompleteType() ||
2052              Decl->getASTContext().getTypeSize(Ty) == 0;
2053   }
2054   return false;
2055 }
2056 
2057 static bool HasSameBase(const LValue &A, const LValue &B) {
2058   if (!A.getLValueBase())
2059     return !B.getLValueBase();
2060   if (!B.getLValueBase())
2061     return false;
2062 
2063   if (A.getLValueBase().getOpaqueValue() !=
2064       B.getLValueBase().getOpaqueValue())
2065     return false;
2066 
2067   return A.getLValueCallIndex() == B.getLValueCallIndex() &&
2068          A.getLValueVersion() == B.getLValueVersion();
2069 }
2070 
2071 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
2072   assert(Base && "no location for a null lvalue");
2073   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2074 
2075   // For a parameter, find the corresponding call stack frame (if it still
2076   // exists), and point at the parameter of the function definition we actually
2077   // invoked.
2078   if (auto *PVD = dyn_cast_or_null<ParmVarDecl>(VD)) {
2079     unsigned Idx = PVD->getFunctionScopeIndex();
2080     for (CallStackFrame *F = Info.CurrentCall; F; F = F->Caller) {
2081       if (F->Arguments.CallIndex == Base.getCallIndex() &&
2082           F->Arguments.Version == Base.getVersion() && F->Callee &&
2083           Idx < F->Callee->getNumParams()) {
2084         VD = F->Callee->getParamDecl(Idx);
2085         break;
2086       }
2087     }
2088   }
2089 
2090   if (VD)
2091     Info.Note(VD->getLocation(), diag::note_declared_at);
2092   else if (const Expr *E = Base.dyn_cast<const Expr*>())
2093     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
2094   else if (DynamicAllocLValue DA = Base.dyn_cast<DynamicAllocLValue>()) {
2095     // FIXME: Produce a note for dangling pointers too.
2096     if (Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA))
2097       Info.Note((*Alloc)->AllocExpr->getExprLoc(),
2098                 diag::note_constexpr_dynamic_alloc_here);
2099   }
2100   // We have no information to show for a typeid(T) object.
2101 }
2102 
2103 enum class CheckEvaluationResultKind {
2104   ConstantExpression,
2105   FullyInitialized,
2106 };
2107 
2108 /// Materialized temporaries that we've already checked to determine if they're
2109 /// initializsed by a constant expression.
2110 using CheckedTemporaries =
2111     llvm::SmallPtrSet<const MaterializeTemporaryExpr *, 8>;
2112 
2113 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2114                                   EvalInfo &Info, SourceLocation DiagLoc,
2115                                   QualType Type, const APValue &Value,
2116                                   ConstantExprKind Kind,
2117                                   SourceLocation SubobjectLoc,
2118                                   CheckedTemporaries &CheckedTemps);
2119 
2120 /// Check that this reference or pointer core constant expression is a valid
2121 /// value for an address or reference constant expression. Return true if we
2122 /// can fold this expression, whether or not it's a constant expression.
2123 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
2124                                           QualType Type, const LValue &LVal,
2125                                           ConstantExprKind Kind,
2126                                           CheckedTemporaries &CheckedTemps) {
2127   bool IsReferenceType = Type->isReferenceType();
2128 
2129   APValue::LValueBase Base = LVal.getLValueBase();
2130   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
2131 
2132   const Expr *BaseE = Base.dyn_cast<const Expr *>();
2133   const ValueDecl *BaseVD = Base.dyn_cast<const ValueDecl*>();
2134 
2135   // Additional restrictions apply in a template argument. We only enforce the
2136   // C++20 restrictions here; additional syntactic and semantic restrictions
2137   // are applied elsewhere.
2138   if (isTemplateArgument(Kind)) {
2139     int InvalidBaseKind = -1;
2140     StringRef Ident;
2141     if (Base.is<TypeInfoLValue>())
2142       InvalidBaseKind = 0;
2143     else if (isa_and_nonnull<StringLiteral>(BaseE))
2144       InvalidBaseKind = 1;
2145     else if (isa_and_nonnull<MaterializeTemporaryExpr>(BaseE) ||
2146              isa_and_nonnull<LifetimeExtendedTemporaryDecl>(BaseVD))
2147       InvalidBaseKind = 2;
2148     else if (auto *PE = dyn_cast_or_null<PredefinedExpr>(BaseE)) {
2149       InvalidBaseKind = 3;
2150       Ident = PE->getIdentKindName();
2151     }
2152 
2153     if (InvalidBaseKind != -1) {
2154       Info.FFDiag(Loc, diag::note_constexpr_invalid_template_arg)
2155           << IsReferenceType << !Designator.Entries.empty() << InvalidBaseKind
2156           << Ident;
2157       return false;
2158     }
2159   }
2160 
2161   if (auto *FD = dyn_cast_or_null<FunctionDecl>(BaseVD)) {
2162     if (FD->isConsteval()) {
2163       Info.FFDiag(Loc, diag::note_consteval_address_accessible)
2164           << !Type->isAnyPointerType();
2165       Info.Note(FD->getLocation(), diag::note_declared_at);
2166       return false;
2167     }
2168   }
2169 
2170   // Check that the object is a global. Note that the fake 'this' object we
2171   // manufacture when checking potential constant expressions is conservatively
2172   // assumed to be global here.
2173   if (!IsGlobalLValue(Base)) {
2174     if (Info.getLangOpts().CPlusPlus11) {
2175       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
2176       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
2177         << IsReferenceType << !Designator.Entries.empty()
2178         << !!VD << VD;
2179 
2180       auto *VarD = dyn_cast_or_null<VarDecl>(VD);
2181       if (VarD && VarD->isConstexpr()) {
2182         // Non-static local constexpr variables have unintuitive semantics:
2183         //   constexpr int a = 1;
2184         //   constexpr const int *p = &a;
2185         // ... is invalid because the address of 'a' is not constant. Suggest
2186         // adding a 'static' in this case.
2187         Info.Note(VarD->getLocation(), diag::note_constexpr_not_static)
2188             << VarD
2189             << FixItHint::CreateInsertion(VarD->getBeginLoc(), "static ");
2190       } else {
2191         NoteLValueLocation(Info, Base);
2192       }
2193     } else {
2194       Info.FFDiag(Loc);
2195     }
2196     // Don't allow references to temporaries to escape.
2197     return false;
2198   }
2199   assert((Info.checkingPotentialConstantExpression() ||
2200           LVal.getLValueCallIndex() == 0) &&
2201          "have call index for global lvalue");
2202 
2203   if (Base.is<DynamicAllocLValue>()) {
2204     Info.FFDiag(Loc, diag::note_constexpr_dynamic_alloc)
2205         << IsReferenceType << !Designator.Entries.empty();
2206     NoteLValueLocation(Info, Base);
2207     return false;
2208   }
2209 
2210   if (BaseVD) {
2211     if (const VarDecl *Var = dyn_cast<const VarDecl>(BaseVD)) {
2212       // Check if this is a thread-local variable.
2213       if (Var->getTLSKind())
2214         // FIXME: Diagnostic!
2215         return false;
2216 
2217       // A dllimport variable never acts like a constant, unless we're
2218       // evaluating a value for use only in name mangling.
2219       if (!isForManglingOnly(Kind) && Var->hasAttr<DLLImportAttr>())
2220         // FIXME: Diagnostic!
2221         return false;
2222     }
2223     if (const auto *FD = dyn_cast<const FunctionDecl>(BaseVD)) {
2224       // __declspec(dllimport) must be handled very carefully:
2225       // We must never initialize an expression with the thunk in C++.
2226       // Doing otherwise would allow the same id-expression to yield
2227       // different addresses for the same function in different translation
2228       // units.  However, this means that we must dynamically initialize the
2229       // expression with the contents of the import address table at runtime.
2230       //
2231       // The C language has no notion of ODR; furthermore, it has no notion of
2232       // dynamic initialization.  This means that we are permitted to
2233       // perform initialization with the address of the thunk.
2234       if (Info.getLangOpts().CPlusPlus && !isForManglingOnly(Kind) &&
2235           FD->hasAttr<DLLImportAttr>())
2236         // FIXME: Diagnostic!
2237         return false;
2238     }
2239   } else if (const auto *MTE =
2240                  dyn_cast_or_null<MaterializeTemporaryExpr>(BaseE)) {
2241     if (CheckedTemps.insert(MTE).second) {
2242       QualType TempType = getType(Base);
2243       if (TempType.isDestructedType()) {
2244         Info.FFDiag(MTE->getExprLoc(),
2245                     diag::note_constexpr_unsupported_temporary_nontrivial_dtor)
2246             << TempType;
2247         return false;
2248       }
2249 
2250       APValue *V = MTE->getOrCreateValue(false);
2251       assert(V && "evasluation result refers to uninitialised temporary");
2252       if (!CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2253                                  Info, MTE->getExprLoc(), TempType, *V,
2254                                  Kind, SourceLocation(), CheckedTemps))
2255         return false;
2256     }
2257   }
2258 
2259   // Allow address constant expressions to be past-the-end pointers. This is
2260   // an extension: the standard requires them to point to an object.
2261   if (!IsReferenceType)
2262     return true;
2263 
2264   // A reference constant expression must refer to an object.
2265   if (!Base) {
2266     // FIXME: diagnostic
2267     Info.CCEDiag(Loc);
2268     return true;
2269   }
2270 
2271   // Does this refer one past the end of some object?
2272   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
2273     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
2274       << !Designator.Entries.empty() << !!BaseVD << BaseVD;
2275     NoteLValueLocation(Info, Base);
2276   }
2277 
2278   return true;
2279 }
2280 
2281 /// Member pointers are constant expressions unless they point to a
2282 /// non-virtual dllimport member function.
2283 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
2284                                                  SourceLocation Loc,
2285                                                  QualType Type,
2286                                                  const APValue &Value,
2287                                                  ConstantExprKind Kind) {
2288   const ValueDecl *Member = Value.getMemberPointerDecl();
2289   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
2290   if (!FD)
2291     return true;
2292   if (FD->isConsteval()) {
2293     Info.FFDiag(Loc, diag::note_consteval_address_accessible) << /*pointer*/ 0;
2294     Info.Note(FD->getLocation(), diag::note_declared_at);
2295     return false;
2296   }
2297   return isForManglingOnly(Kind) || FD->isVirtual() ||
2298          !FD->hasAttr<DLLImportAttr>();
2299 }
2300 
2301 /// Check that this core constant expression is of literal type, and if not,
2302 /// produce an appropriate diagnostic.
2303 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
2304                              const LValue *This = nullptr) {
2305   if (!E->isPRValue() || E->getType()->isLiteralType(Info.Ctx))
2306     return true;
2307 
2308   // C++1y: A constant initializer for an object o [...] may also invoke
2309   // constexpr constructors for o and its subobjects even if those objects
2310   // are of non-literal class types.
2311   //
2312   // C++11 missed this detail for aggregates, so classes like this:
2313   //   struct foo_t { union { int i; volatile int j; } u; };
2314   // are not (obviously) initializable like so:
2315   //   __attribute__((__require_constant_initialization__))
2316   //   static const foo_t x = {{0}};
2317   // because "i" is a subobject with non-literal initialization (due to the
2318   // volatile member of the union). See:
2319   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2320   // Therefore, we use the C++1y behavior.
2321   if (This && Info.EvaluatingDecl == This->getLValueBase())
2322     return true;
2323 
2324   // Prvalue constant expressions must be of literal types.
2325   if (Info.getLangOpts().CPlusPlus11)
2326     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2327       << E->getType();
2328   else
2329     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2330   return false;
2331 }
2332 
2333 static bool CheckEvaluationResult(CheckEvaluationResultKind CERK,
2334                                   EvalInfo &Info, SourceLocation DiagLoc,
2335                                   QualType Type, const APValue &Value,
2336                                   ConstantExprKind Kind,
2337                                   SourceLocation SubobjectLoc,
2338                                   CheckedTemporaries &CheckedTemps) {
2339   if (!Value.hasValue()) {
2340     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2341       << true << Type;
2342     if (SubobjectLoc.isValid())
2343       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2344     return false;
2345   }
2346 
2347   // We allow _Atomic(T) to be initialized from anything that T can be
2348   // initialized from.
2349   if (const AtomicType *AT = Type->getAs<AtomicType>())
2350     Type = AT->getValueType();
2351 
2352   // Core issue 1454: For a literal constant expression of array or class type,
2353   // each subobject of its value shall have been initialized by a constant
2354   // expression.
2355   if (Value.isArray()) {
2356     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2357     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2358       if (!CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2359                                  Value.getArrayInitializedElt(I), Kind,
2360                                  SubobjectLoc, CheckedTemps))
2361         return false;
2362     }
2363     if (!Value.hasArrayFiller())
2364       return true;
2365     return CheckEvaluationResult(CERK, Info, DiagLoc, EltTy,
2366                                  Value.getArrayFiller(), Kind, SubobjectLoc,
2367                                  CheckedTemps);
2368   }
2369   if (Value.isUnion() && Value.getUnionField()) {
2370     return CheckEvaluationResult(
2371         CERK, Info, DiagLoc, Value.getUnionField()->getType(),
2372         Value.getUnionValue(), Kind, Value.getUnionField()->getLocation(),
2373         CheckedTemps);
2374   }
2375   if (Value.isStruct()) {
2376     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2377     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2378       unsigned BaseIndex = 0;
2379       for (const CXXBaseSpecifier &BS : CD->bases()) {
2380         if (!CheckEvaluationResult(CERK, Info, DiagLoc, BS.getType(),
2381                                    Value.getStructBase(BaseIndex), Kind,
2382                                    BS.getBeginLoc(), CheckedTemps))
2383           return false;
2384         ++BaseIndex;
2385       }
2386     }
2387     for (const auto *I : RD->fields()) {
2388       if (I->isUnnamedBitfield())
2389         continue;
2390 
2391       if (!CheckEvaluationResult(CERK, Info, DiagLoc, I->getType(),
2392                                  Value.getStructField(I->getFieldIndex()),
2393                                  Kind, I->getLocation(), CheckedTemps))
2394         return false;
2395     }
2396   }
2397 
2398   if (Value.isLValue() &&
2399       CERK == CheckEvaluationResultKind::ConstantExpression) {
2400     LValue LVal;
2401     LVal.setFrom(Info.Ctx, Value);
2402     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Kind,
2403                                          CheckedTemps);
2404   }
2405 
2406   if (Value.isMemberPointer() &&
2407       CERK == CheckEvaluationResultKind::ConstantExpression)
2408     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Kind);
2409 
2410   // Everything else is fine.
2411   return true;
2412 }
2413 
2414 /// Check that this core constant expression value is a valid value for a
2415 /// constant expression. If not, report an appropriate diagnostic. Does not
2416 /// check that the expression is of literal type.
2417 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
2418                                     QualType Type, const APValue &Value,
2419                                     ConstantExprKind Kind) {
2420   // Nothing to check for a constant expression of type 'cv void'.
2421   if (Type->isVoidType())
2422     return true;
2423 
2424   CheckedTemporaries CheckedTemps;
2425   return CheckEvaluationResult(CheckEvaluationResultKind::ConstantExpression,
2426                                Info, DiagLoc, Type, Value, Kind,
2427                                SourceLocation(), CheckedTemps);
2428 }
2429 
2430 /// Check that this evaluated value is fully-initialized and can be loaded by
2431 /// an lvalue-to-rvalue conversion.
2432 static bool CheckFullyInitialized(EvalInfo &Info, SourceLocation DiagLoc,
2433                                   QualType Type, const APValue &Value) {
2434   CheckedTemporaries CheckedTemps;
2435   return CheckEvaluationResult(
2436       CheckEvaluationResultKind::FullyInitialized, Info, DiagLoc, Type, Value,
2437       ConstantExprKind::Normal, SourceLocation(), CheckedTemps);
2438 }
2439 
2440 /// Enforce C++2a [expr.const]/4.17, which disallows new-expressions unless
2441 /// "the allocated storage is deallocated within the evaluation".
2442 static bool CheckMemoryLeaks(EvalInfo &Info) {
2443   if (!Info.HeapAllocs.empty()) {
2444     // We can still fold to a constant despite a compile-time memory leak,
2445     // so long as the heap allocation isn't referenced in the result (we check
2446     // that in CheckConstantExpression).
2447     Info.CCEDiag(Info.HeapAllocs.begin()->second.AllocExpr,
2448                  diag::note_constexpr_memory_leak)
2449         << unsigned(Info.HeapAllocs.size() - 1);
2450   }
2451   return true;
2452 }
2453 
2454 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2455   // A null base expression indicates a null pointer.  These are always
2456   // evaluatable, and they are false unless the offset is zero.
2457   if (!Value.getLValueBase()) {
2458     Result = !Value.getLValueOffset().isZero();
2459     return true;
2460   }
2461 
2462   // We have a non-null base.  These are generally known to be true, but if it's
2463   // a weak declaration it can be null at runtime.
2464   Result = true;
2465   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2466   return !Decl || !Decl->isWeak();
2467 }
2468 
2469 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2470   switch (Val.getKind()) {
2471   case APValue::None:
2472   case APValue::Indeterminate:
2473     return false;
2474   case APValue::Int:
2475     Result = Val.getInt().getBoolValue();
2476     return true;
2477   case APValue::FixedPoint:
2478     Result = Val.getFixedPoint().getBoolValue();
2479     return true;
2480   case APValue::Float:
2481     Result = !Val.getFloat().isZero();
2482     return true;
2483   case APValue::ComplexInt:
2484     Result = Val.getComplexIntReal().getBoolValue() ||
2485              Val.getComplexIntImag().getBoolValue();
2486     return true;
2487   case APValue::ComplexFloat:
2488     Result = !Val.getComplexFloatReal().isZero() ||
2489              !Val.getComplexFloatImag().isZero();
2490     return true;
2491   case APValue::LValue:
2492     return EvalPointerValueAsBool(Val, Result);
2493   case APValue::MemberPointer:
2494     Result = Val.getMemberPointerDecl();
2495     return true;
2496   case APValue::Vector:
2497   case APValue::Array:
2498   case APValue::Struct:
2499   case APValue::Union:
2500   case APValue::AddrLabelDiff:
2501     return false;
2502   }
2503 
2504   llvm_unreachable("unknown APValue kind");
2505 }
2506 
2507 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2508                                        EvalInfo &Info) {
2509   assert(!E->isValueDependent());
2510   assert(E->isPRValue() && "missing lvalue-to-rvalue conv in bool condition");
2511   APValue Val;
2512   if (!Evaluate(Val, Info, E))
2513     return false;
2514   return HandleConversionToBool(Val, Result);
2515 }
2516 
2517 template<typename T>
2518 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2519                            const T &SrcValue, QualType DestType) {
2520   Info.CCEDiag(E, diag::note_constexpr_overflow)
2521     << SrcValue << DestType;
2522   return Info.noteUndefinedBehavior();
2523 }
2524 
2525 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2526                                  QualType SrcType, const APFloat &Value,
2527                                  QualType DestType, APSInt &Result) {
2528   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2529   // Determine whether we are converting to unsigned or signed.
2530   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2531 
2532   Result = APSInt(DestWidth, !DestSigned);
2533   bool ignored;
2534   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2535       & APFloat::opInvalidOp)
2536     return HandleOverflow(Info, E, Value, DestType);
2537   return true;
2538 }
2539 
2540 /// Get rounding mode used for evaluation of the specified expression.
2541 /// \param[out] DynamicRM Is set to true is the requested rounding mode is
2542 ///                       dynamic.
2543 /// If rounding mode is unknown at compile time, still try to evaluate the
2544 /// expression. If the result is exact, it does not depend on rounding mode.
2545 /// So return "tonearest" mode instead of "dynamic".
2546 static llvm::RoundingMode getActiveRoundingMode(EvalInfo &Info, const Expr *E,
2547                                                 bool &DynamicRM) {
2548   llvm::RoundingMode RM =
2549       E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).getRoundingMode();
2550   DynamicRM = (RM == llvm::RoundingMode::Dynamic);
2551   if (DynamicRM)
2552     RM = llvm::RoundingMode::NearestTiesToEven;
2553   return RM;
2554 }
2555 
2556 /// Check if the given evaluation result is allowed for constant evaluation.
2557 static bool checkFloatingPointResult(EvalInfo &Info, const Expr *E,
2558                                      APFloat::opStatus St) {
2559   // In a constant context, assume that any dynamic rounding mode or FP
2560   // exception state matches the default floating-point environment.
2561   if (Info.InConstantContext)
2562     return true;
2563 
2564   FPOptions FPO = E->getFPFeaturesInEffect(Info.Ctx.getLangOpts());
2565   if ((St & APFloat::opInexact) &&
2566       FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
2567     // Inexact result means that it depends on rounding mode. If the requested
2568     // mode is dynamic, the evaluation cannot be made in compile time.
2569     Info.FFDiag(E, diag::note_constexpr_dynamic_rounding);
2570     return false;
2571   }
2572 
2573   if ((St != APFloat::opOK) &&
2574       (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
2575        FPO.getFPExceptionMode() != LangOptions::FPE_Ignore ||
2576        FPO.getAllowFEnvAccess())) {
2577     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2578     return false;
2579   }
2580 
2581   if ((St & APFloat::opStatus::opInvalidOp) &&
2582       FPO.getFPExceptionMode() != LangOptions::FPE_Ignore) {
2583     // There is no usefully definable result.
2584     Info.FFDiag(E);
2585     return false;
2586   }
2587 
2588   // FIXME: if:
2589   // - evaluation triggered other FP exception, and
2590   // - exception mode is not "ignore", and
2591   // - the expression being evaluated is not a part of global variable
2592   //   initializer,
2593   // the evaluation probably need to be rejected.
2594   return true;
2595 }
2596 
2597 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2598                                    QualType SrcType, QualType DestType,
2599                                    APFloat &Result) {
2600   assert(isa<CastExpr>(E) || isa<CompoundAssignOperator>(E));
2601   bool DynamicRM;
2602   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2603   APFloat::opStatus St;
2604   APFloat Value = Result;
2605   bool ignored;
2606   St = Result.convert(Info.Ctx.getFloatTypeSemantics(DestType), RM, &ignored);
2607   return checkFloatingPointResult(Info, E, St);
2608 }
2609 
2610 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2611                                  QualType DestType, QualType SrcType,
2612                                  const APSInt &Value) {
2613   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2614   // Figure out if this is a truncate, extend or noop cast.
2615   // If the input is signed, do a sign extend, noop, or truncate.
2616   APSInt Result = Value.extOrTrunc(DestWidth);
2617   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2618   if (DestType->isBooleanType())
2619     Result = Value.getBoolValue();
2620   return Result;
2621 }
2622 
2623 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2624                                  const FPOptions FPO,
2625                                  QualType SrcType, const APSInt &Value,
2626                                  QualType DestType, APFloat &Result) {
2627   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2628   APFloat::opStatus St = Result.convertFromAPInt(Value, Value.isSigned(),
2629        APFloat::rmNearestTiesToEven);
2630   if (!Info.InConstantContext && St != llvm::APFloatBase::opOK &&
2631       FPO.isFPConstrained()) {
2632     Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
2633     return false;
2634   }
2635   return true;
2636 }
2637 
2638 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2639                                   APValue &Value, const FieldDecl *FD) {
2640   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2641 
2642   if (!Value.isInt()) {
2643     // Trying to store a pointer-cast-to-integer into a bitfield.
2644     // FIXME: In this case, we should provide the diagnostic for casting
2645     // a pointer to an integer.
2646     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2647     Info.FFDiag(E);
2648     return false;
2649   }
2650 
2651   APSInt &Int = Value.getInt();
2652   unsigned OldBitWidth = Int.getBitWidth();
2653   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2654   if (NewBitWidth < OldBitWidth)
2655     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2656   return true;
2657 }
2658 
2659 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2660                                   llvm::APInt &Res) {
2661   APValue SVal;
2662   if (!Evaluate(SVal, Info, E))
2663     return false;
2664   if (SVal.isInt()) {
2665     Res = SVal.getInt();
2666     return true;
2667   }
2668   if (SVal.isFloat()) {
2669     Res = SVal.getFloat().bitcastToAPInt();
2670     return true;
2671   }
2672   if (SVal.isVector()) {
2673     QualType VecTy = E->getType();
2674     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2675     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2676     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2677     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2678     Res = llvm::APInt::getZero(VecSize);
2679     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2680       APValue &Elt = SVal.getVectorElt(i);
2681       llvm::APInt EltAsInt;
2682       if (Elt.isInt()) {
2683         EltAsInt = Elt.getInt();
2684       } else if (Elt.isFloat()) {
2685         EltAsInt = Elt.getFloat().bitcastToAPInt();
2686       } else {
2687         // Don't try to handle vectors of anything other than int or float
2688         // (not sure if it's possible to hit this case).
2689         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2690         return false;
2691       }
2692       unsigned BaseEltSize = EltAsInt.getBitWidth();
2693       if (BigEndian)
2694         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2695       else
2696         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2697     }
2698     return true;
2699   }
2700   // Give up if the input isn't an int, float, or vector.  For example, we
2701   // reject "(v4i16)(intptr_t)&a".
2702   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2703   return false;
2704 }
2705 
2706 /// Perform the given integer operation, which is known to need at most BitWidth
2707 /// bits, and check for overflow in the original type (if that type was not an
2708 /// unsigned type).
2709 template<typename Operation>
2710 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2711                                  const APSInt &LHS, const APSInt &RHS,
2712                                  unsigned BitWidth, Operation Op,
2713                                  APSInt &Result) {
2714   if (LHS.isUnsigned()) {
2715     Result = Op(LHS, RHS);
2716     return true;
2717   }
2718 
2719   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2720   Result = Value.trunc(LHS.getBitWidth());
2721   if (Result.extend(BitWidth) != Value) {
2722     if (Info.checkingForUndefinedBehavior())
2723       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2724                                        diag::warn_integer_constant_overflow)
2725           << toString(Result, 10) << E->getType();
2726     return HandleOverflow(Info, E, Value, E->getType());
2727   }
2728   return true;
2729 }
2730 
2731 /// Perform the given binary integer operation.
2732 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2733                               BinaryOperatorKind Opcode, APSInt RHS,
2734                               APSInt &Result) {
2735   switch (Opcode) {
2736   default:
2737     Info.FFDiag(E);
2738     return false;
2739   case BO_Mul:
2740     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2741                                 std::multiplies<APSInt>(), Result);
2742   case BO_Add:
2743     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2744                                 std::plus<APSInt>(), Result);
2745   case BO_Sub:
2746     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2747                                 std::minus<APSInt>(), Result);
2748   case BO_And: Result = LHS & RHS; return true;
2749   case BO_Xor: Result = LHS ^ RHS; return true;
2750   case BO_Or:  Result = LHS | RHS; return true;
2751   case BO_Div:
2752   case BO_Rem:
2753     if (RHS == 0) {
2754       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2755       return false;
2756     }
2757     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2758     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2759     // this operation and gives the two's complement result.
2760     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2761         LHS.isSigned() && LHS.isMinSignedValue())
2762       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2763                             E->getType());
2764     return true;
2765   case BO_Shl: {
2766     if (Info.getLangOpts().OpenCL)
2767       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2768       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2769                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2770                     RHS.isUnsigned());
2771     else if (RHS.isSigned() && RHS.isNegative()) {
2772       // During constant-folding, a negative shift is an opposite shift. Such
2773       // a shift is not a constant expression.
2774       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2775       RHS = -RHS;
2776       goto shift_right;
2777     }
2778   shift_left:
2779     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2780     // the shifted type.
2781     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2782     if (SA != RHS) {
2783       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2784         << RHS << E->getType() << LHS.getBitWidth();
2785     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus20) {
2786       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2787       // operand, and must not overflow the corresponding unsigned type.
2788       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2789       // E1 x 2^E2 module 2^N.
2790       if (LHS.isNegative())
2791         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2792       else if (LHS.countLeadingZeros() < SA)
2793         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2794     }
2795     Result = LHS << SA;
2796     return true;
2797   }
2798   case BO_Shr: {
2799     if (Info.getLangOpts().OpenCL)
2800       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2801       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2802                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2803                     RHS.isUnsigned());
2804     else if (RHS.isSigned() && RHS.isNegative()) {
2805       // During constant-folding, a negative shift is an opposite shift. Such a
2806       // shift is not a constant expression.
2807       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2808       RHS = -RHS;
2809       goto shift_left;
2810     }
2811   shift_right:
2812     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2813     // shifted type.
2814     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2815     if (SA != RHS)
2816       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2817         << RHS << E->getType() << LHS.getBitWidth();
2818     Result = LHS >> SA;
2819     return true;
2820   }
2821 
2822   case BO_LT: Result = LHS < RHS; return true;
2823   case BO_GT: Result = LHS > RHS; return true;
2824   case BO_LE: Result = LHS <= RHS; return true;
2825   case BO_GE: Result = LHS >= RHS; return true;
2826   case BO_EQ: Result = LHS == RHS; return true;
2827   case BO_NE: Result = LHS != RHS; return true;
2828   case BO_Cmp:
2829     llvm_unreachable("BO_Cmp should be handled elsewhere");
2830   }
2831 }
2832 
2833 /// Perform the given binary floating-point operation, in-place, on LHS.
2834 static bool handleFloatFloatBinOp(EvalInfo &Info, const BinaryOperator *E,
2835                                   APFloat &LHS, BinaryOperatorKind Opcode,
2836                                   const APFloat &RHS) {
2837   bool DynamicRM;
2838   llvm::RoundingMode RM = getActiveRoundingMode(Info, E, DynamicRM);
2839   APFloat::opStatus St;
2840   switch (Opcode) {
2841   default:
2842     Info.FFDiag(E);
2843     return false;
2844   case BO_Mul:
2845     St = LHS.multiply(RHS, RM);
2846     break;
2847   case BO_Add:
2848     St = LHS.add(RHS, RM);
2849     break;
2850   case BO_Sub:
2851     St = LHS.subtract(RHS, RM);
2852     break;
2853   case BO_Div:
2854     // [expr.mul]p4:
2855     //   If the second operand of / or % is zero the behavior is undefined.
2856     if (RHS.isZero())
2857       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2858     St = LHS.divide(RHS, RM);
2859     break;
2860   }
2861 
2862   // [expr.pre]p4:
2863   //   If during the evaluation of an expression, the result is not
2864   //   mathematically defined [...], the behavior is undefined.
2865   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2866   if (LHS.isNaN()) {
2867     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2868     return Info.noteUndefinedBehavior();
2869   }
2870 
2871   return checkFloatingPointResult(Info, E, St);
2872 }
2873 
2874 static bool handleLogicalOpForVector(const APInt &LHSValue,
2875                                      BinaryOperatorKind Opcode,
2876                                      const APInt &RHSValue, APInt &Result) {
2877   bool LHS = (LHSValue != 0);
2878   bool RHS = (RHSValue != 0);
2879 
2880   if (Opcode == BO_LAnd)
2881     Result = LHS && RHS;
2882   else
2883     Result = LHS || RHS;
2884   return true;
2885 }
2886 static bool handleLogicalOpForVector(const APFloat &LHSValue,
2887                                      BinaryOperatorKind Opcode,
2888                                      const APFloat &RHSValue, APInt &Result) {
2889   bool LHS = !LHSValue.isZero();
2890   bool RHS = !RHSValue.isZero();
2891 
2892   if (Opcode == BO_LAnd)
2893     Result = LHS && RHS;
2894   else
2895     Result = LHS || RHS;
2896   return true;
2897 }
2898 
2899 static bool handleLogicalOpForVector(const APValue &LHSValue,
2900                                      BinaryOperatorKind Opcode,
2901                                      const APValue &RHSValue, APInt &Result) {
2902   // The result is always an int type, however operands match the first.
2903   if (LHSValue.getKind() == APValue::Int)
2904     return handleLogicalOpForVector(LHSValue.getInt(), Opcode,
2905                                     RHSValue.getInt(), Result);
2906   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2907   return handleLogicalOpForVector(LHSValue.getFloat(), Opcode,
2908                                   RHSValue.getFloat(), Result);
2909 }
2910 
2911 template <typename APTy>
2912 static bool
2913 handleCompareOpForVectorHelper(const APTy &LHSValue, BinaryOperatorKind Opcode,
2914                                const APTy &RHSValue, APInt &Result) {
2915   switch (Opcode) {
2916   default:
2917     llvm_unreachable("unsupported binary operator");
2918   case BO_EQ:
2919     Result = (LHSValue == RHSValue);
2920     break;
2921   case BO_NE:
2922     Result = (LHSValue != RHSValue);
2923     break;
2924   case BO_LT:
2925     Result = (LHSValue < RHSValue);
2926     break;
2927   case BO_GT:
2928     Result = (LHSValue > RHSValue);
2929     break;
2930   case BO_LE:
2931     Result = (LHSValue <= RHSValue);
2932     break;
2933   case BO_GE:
2934     Result = (LHSValue >= RHSValue);
2935     break;
2936   }
2937 
2938   return true;
2939 }
2940 
2941 static bool handleCompareOpForVector(const APValue &LHSValue,
2942                                      BinaryOperatorKind Opcode,
2943                                      const APValue &RHSValue, APInt &Result) {
2944   // The result is always an int type, however operands match the first.
2945   if (LHSValue.getKind() == APValue::Int)
2946     return handleCompareOpForVectorHelper(LHSValue.getInt(), Opcode,
2947                                           RHSValue.getInt(), Result);
2948   assert(LHSValue.getKind() == APValue::Float && "Should be no other options");
2949   return handleCompareOpForVectorHelper(LHSValue.getFloat(), Opcode,
2950                                         RHSValue.getFloat(), Result);
2951 }
2952 
2953 // Perform binary operations for vector types, in place on the LHS.
2954 static bool handleVectorVectorBinOp(EvalInfo &Info, const BinaryOperator *E,
2955                                     BinaryOperatorKind Opcode,
2956                                     APValue &LHSValue,
2957                                     const APValue &RHSValue) {
2958   assert(Opcode != BO_PtrMemD && Opcode != BO_PtrMemI &&
2959          "Operation not supported on vector types");
2960 
2961   const auto *VT = E->getType()->castAs<VectorType>();
2962   unsigned NumElements = VT->getNumElements();
2963   QualType EltTy = VT->getElementType();
2964 
2965   // In the cases (typically C as I've observed) where we aren't evaluating
2966   // constexpr but are checking for cases where the LHS isn't yet evaluatable,
2967   // just give up.
2968   if (!LHSValue.isVector()) {
2969     assert(LHSValue.isLValue() &&
2970            "A vector result that isn't a vector OR uncalculated LValue");
2971     Info.FFDiag(E);
2972     return false;
2973   }
2974 
2975   assert(LHSValue.getVectorLength() == NumElements &&
2976          RHSValue.getVectorLength() == NumElements && "Different vector sizes");
2977 
2978   SmallVector<APValue, 4> ResultElements;
2979 
2980   for (unsigned EltNum = 0; EltNum < NumElements; ++EltNum) {
2981     APValue LHSElt = LHSValue.getVectorElt(EltNum);
2982     APValue RHSElt = RHSValue.getVectorElt(EltNum);
2983 
2984     if (EltTy->isIntegerType()) {
2985       APSInt EltResult{Info.Ctx.getIntWidth(EltTy),
2986                        EltTy->isUnsignedIntegerType()};
2987       bool Success = true;
2988 
2989       if (BinaryOperator::isLogicalOp(Opcode))
2990         Success = handleLogicalOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2991       else if (BinaryOperator::isComparisonOp(Opcode))
2992         Success = handleCompareOpForVector(LHSElt, Opcode, RHSElt, EltResult);
2993       else
2994         Success = handleIntIntBinOp(Info, E, LHSElt.getInt(), Opcode,
2995                                     RHSElt.getInt(), EltResult);
2996 
2997       if (!Success) {
2998         Info.FFDiag(E);
2999         return false;
3000       }
3001       ResultElements.emplace_back(EltResult);
3002 
3003     } else if (EltTy->isFloatingType()) {
3004       assert(LHSElt.getKind() == APValue::Float &&
3005              RHSElt.getKind() == APValue::Float &&
3006              "Mismatched LHS/RHS/Result Type");
3007       APFloat LHSFloat = LHSElt.getFloat();
3008 
3009       if (!handleFloatFloatBinOp(Info, E, LHSFloat, Opcode,
3010                                  RHSElt.getFloat())) {
3011         Info.FFDiag(E);
3012         return false;
3013       }
3014 
3015       ResultElements.emplace_back(LHSFloat);
3016     }
3017   }
3018 
3019   LHSValue = APValue(ResultElements.data(), ResultElements.size());
3020   return true;
3021 }
3022 
3023 /// Cast an lvalue referring to a base subobject to a derived class, by
3024 /// truncating the lvalue's path to the given length.
3025 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
3026                                const RecordDecl *TruncatedType,
3027                                unsigned TruncatedElements) {
3028   SubobjectDesignator &D = Result.Designator;
3029 
3030   // Check we actually point to a derived class object.
3031   if (TruncatedElements == D.Entries.size())
3032     return true;
3033   assert(TruncatedElements >= D.MostDerivedPathLength &&
3034          "not casting to a derived class");
3035   if (!Result.checkSubobject(Info, E, CSK_Derived))
3036     return false;
3037 
3038   // Truncate the path to the subobject, and remove any derived-to-base offsets.
3039   const RecordDecl *RD = TruncatedType;
3040   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
3041     if (RD->isInvalidDecl()) return false;
3042     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3043     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
3044     if (isVirtualBaseClass(D.Entries[I]))
3045       Result.Offset -= Layout.getVBaseClassOffset(Base);
3046     else
3047       Result.Offset -= Layout.getBaseClassOffset(Base);
3048     RD = Base;
3049   }
3050   D.Entries.resize(TruncatedElements);
3051   return true;
3052 }
3053 
3054 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3055                                    const CXXRecordDecl *Derived,
3056                                    const CXXRecordDecl *Base,
3057                                    const ASTRecordLayout *RL = nullptr) {
3058   if (!RL) {
3059     if (Derived->isInvalidDecl()) return false;
3060     RL = &Info.Ctx.getASTRecordLayout(Derived);
3061   }
3062 
3063   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
3064   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
3065   return true;
3066 }
3067 
3068 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
3069                              const CXXRecordDecl *DerivedDecl,
3070                              const CXXBaseSpecifier *Base) {
3071   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
3072 
3073   if (!Base->isVirtual())
3074     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
3075 
3076   SubobjectDesignator &D = Obj.Designator;
3077   if (D.Invalid)
3078     return false;
3079 
3080   // Extract most-derived object and corresponding type.
3081   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
3082   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
3083     return false;
3084 
3085   // Find the virtual base class.
3086   if (DerivedDecl->isInvalidDecl()) return false;
3087   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
3088   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
3089   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
3090   return true;
3091 }
3092 
3093 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
3094                                  QualType Type, LValue &Result) {
3095   for (CastExpr::path_const_iterator PathI = E->path_begin(),
3096                                      PathE = E->path_end();
3097        PathI != PathE; ++PathI) {
3098     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3099                           *PathI))
3100       return false;
3101     Type = (*PathI)->getType();
3102   }
3103   return true;
3104 }
3105 
3106 /// Cast an lvalue referring to a derived class to a known base subobject.
3107 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
3108                             const CXXRecordDecl *DerivedRD,
3109                             const CXXRecordDecl *BaseRD) {
3110   CXXBasePaths Paths(/*FindAmbiguities=*/false,
3111                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
3112   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
3113     llvm_unreachable("Class must be derived from the passed in base class!");
3114 
3115   for (CXXBasePathElement &Elem : Paths.front())
3116     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
3117       return false;
3118   return true;
3119 }
3120 
3121 /// Update LVal to refer to the given field, which must be a member of the type
3122 /// currently described by LVal.
3123 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
3124                                const FieldDecl *FD,
3125                                const ASTRecordLayout *RL = nullptr) {
3126   if (!RL) {
3127     if (FD->getParent()->isInvalidDecl()) return false;
3128     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
3129   }
3130 
3131   unsigned I = FD->getFieldIndex();
3132   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
3133   LVal.addDecl(Info, E, FD);
3134   return true;
3135 }
3136 
3137 /// Update LVal to refer to the given indirect field.
3138 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
3139                                        LValue &LVal,
3140                                        const IndirectFieldDecl *IFD) {
3141   for (const auto *C : IFD->chain())
3142     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
3143       return false;
3144   return true;
3145 }
3146 
3147 /// Get the size of the given type in char units.
3148 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
3149                          QualType Type, CharUnits &Size) {
3150   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
3151   // extension.
3152   if (Type->isVoidType() || Type->isFunctionType()) {
3153     Size = CharUnits::One();
3154     return true;
3155   }
3156 
3157   if (Type->isDependentType()) {
3158     Info.FFDiag(Loc);
3159     return false;
3160   }
3161 
3162   if (!Type->isConstantSizeType()) {
3163     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
3164     // FIXME: Better diagnostic.
3165     Info.FFDiag(Loc);
3166     return false;
3167   }
3168 
3169   Size = Info.Ctx.getTypeSizeInChars(Type);
3170   return true;
3171 }
3172 
3173 /// Update a pointer value to model pointer arithmetic.
3174 /// \param Info - Information about the ongoing evaluation.
3175 /// \param E - The expression being evaluated, for diagnostic purposes.
3176 /// \param LVal - The pointer value to be updated.
3177 /// \param EltTy - The pointee type represented by LVal.
3178 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
3179 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3180                                         LValue &LVal, QualType EltTy,
3181                                         APSInt Adjustment) {
3182   CharUnits SizeOfPointee;
3183   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
3184     return false;
3185 
3186   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
3187   return true;
3188 }
3189 
3190 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
3191                                         LValue &LVal, QualType EltTy,
3192                                         int64_t Adjustment) {
3193   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
3194                                      APSInt::get(Adjustment));
3195 }
3196 
3197 /// Update an lvalue to refer to a component of a complex number.
3198 /// \param Info - Information about the ongoing evaluation.
3199 /// \param LVal - The lvalue to be updated.
3200 /// \param EltTy - The complex number's component type.
3201 /// \param Imag - False for the real component, true for the imaginary.
3202 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
3203                                        LValue &LVal, QualType EltTy,
3204                                        bool Imag) {
3205   if (Imag) {
3206     CharUnits SizeOfComponent;
3207     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
3208       return false;
3209     LVal.Offset += SizeOfComponent;
3210   }
3211   LVal.addComplex(Info, E, EltTy, Imag);
3212   return true;
3213 }
3214 
3215 /// Try to evaluate the initializer for a variable declaration.
3216 ///
3217 /// \param Info   Information about the ongoing evaluation.
3218 /// \param E      An expression to be used when printing diagnostics.
3219 /// \param VD     The variable whose initializer should be obtained.
3220 /// \param Version The version of the variable within the frame.
3221 /// \param Frame  The frame in which the variable was created. Must be null
3222 ///               if this variable is not local to the evaluation.
3223 /// \param Result Filled in with a pointer to the value of the variable.
3224 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
3225                                 const VarDecl *VD, CallStackFrame *Frame,
3226                                 unsigned Version, APValue *&Result) {
3227   APValue::LValueBase Base(VD, Frame ? Frame->Index : 0, Version);
3228 
3229   // If this is a local variable, dig out its value.
3230   if (Frame) {
3231     Result = Frame->getTemporary(VD, Version);
3232     if (Result)
3233       return true;
3234 
3235     if (!isa<ParmVarDecl>(VD)) {
3236       // Assume variables referenced within a lambda's call operator that were
3237       // not declared within the call operator are captures and during checking
3238       // of a potential constant expression, assume they are unknown constant
3239       // expressions.
3240       assert(isLambdaCallOperator(Frame->Callee) &&
3241              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
3242              "missing value for local variable");
3243       if (Info.checkingPotentialConstantExpression())
3244         return false;
3245       // FIXME: This diagnostic is bogus; we do support captures. Is this code
3246       // still reachable at all?
3247       Info.FFDiag(E->getBeginLoc(),
3248                   diag::note_unimplemented_constexpr_lambda_feature_ast)
3249           << "captures not currently allowed";
3250       return false;
3251     }
3252   }
3253 
3254   // If we're currently evaluating the initializer of this declaration, use that
3255   // in-flight value.
3256   if (Info.EvaluatingDecl == Base) {
3257     Result = Info.EvaluatingDeclValue;
3258     return true;
3259   }
3260 
3261   if (isa<ParmVarDecl>(VD)) {
3262     // Assume parameters of a potential constant expression are usable in
3263     // constant expressions.
3264     if (!Info.checkingPotentialConstantExpression() ||
3265         !Info.CurrentCall->Callee ||
3266         !Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
3267       if (Info.getLangOpts().CPlusPlus11) {
3268         Info.FFDiag(E, diag::note_constexpr_function_param_value_unknown)
3269             << VD;
3270         NoteLValueLocation(Info, Base);
3271       } else {
3272         Info.FFDiag(E);
3273       }
3274     }
3275     return false;
3276   }
3277 
3278   // Dig out the initializer, and use the declaration which it's attached to.
3279   // FIXME: We should eventually check whether the variable has a reachable
3280   // initializing declaration.
3281   const Expr *Init = VD->getAnyInitializer(VD);
3282   if (!Init) {
3283     // Don't diagnose during potential constant expression checking; an
3284     // initializer might be added later.
3285     if (!Info.checkingPotentialConstantExpression()) {
3286       Info.FFDiag(E, diag::note_constexpr_var_init_unknown, 1)
3287         << VD;
3288       NoteLValueLocation(Info, Base);
3289     }
3290     return false;
3291   }
3292 
3293   if (Init->isValueDependent()) {
3294     // The DeclRefExpr is not value-dependent, but the variable it refers to
3295     // has a value-dependent initializer. This should only happen in
3296     // constant-folding cases, where the variable is not actually of a suitable
3297     // type for use in a constant expression (otherwise the DeclRefExpr would
3298     // have been value-dependent too), so diagnose that.
3299     assert(!VD->mightBeUsableInConstantExpressions(Info.Ctx));
3300     if (!Info.checkingPotentialConstantExpression()) {
3301       Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
3302                          ? diag::note_constexpr_ltor_non_constexpr
3303                          : diag::note_constexpr_ltor_non_integral, 1)
3304           << VD << VD->getType();
3305       NoteLValueLocation(Info, Base);
3306     }
3307     return false;
3308   }
3309 
3310   // Check that we can fold the initializer. In C++, we will have already done
3311   // this in the cases where it matters for conformance.
3312   if (!VD->evaluateValue()) {
3313     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3314     NoteLValueLocation(Info, Base);
3315     return false;
3316   }
3317 
3318   // Check that the variable is actually usable in constant expressions. For a
3319   // const integral variable or a reference, we might have a non-constant
3320   // initializer that we can nonetheless evaluate the initializer for. Such
3321   // variables are not usable in constant expressions. In C++98, the
3322   // initializer also syntactically needs to be an ICE.
3323   //
3324   // FIXME: We don't diagnose cases that aren't potentially usable in constant
3325   // expressions here; doing so would regress diagnostics for things like
3326   // reading from a volatile constexpr variable.
3327   if ((Info.getLangOpts().CPlusPlus && !VD->hasConstantInitialization() &&
3328        VD->mightBeUsableInConstantExpressions(Info.Ctx)) ||
3329       ((Info.getLangOpts().CPlusPlus || Info.getLangOpts().OpenCL) &&
3330        !Info.getLangOpts().CPlusPlus11 && !VD->hasICEInitializer(Info.Ctx))) {
3331     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant, 1) << VD;
3332     NoteLValueLocation(Info, Base);
3333   }
3334 
3335   // Never use the initializer of a weak variable, not even for constant
3336   // folding. We can't be sure that this is the definition that will be used.
3337   if (VD->isWeak()) {
3338     Info.FFDiag(E, diag::note_constexpr_var_init_weak) << VD;
3339     NoteLValueLocation(Info, Base);
3340     return false;
3341   }
3342 
3343   Result = VD->getEvaluatedValue();
3344   return true;
3345 }
3346 
3347 /// Get the base index of the given base class within an APValue representing
3348 /// the given derived class.
3349 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
3350                              const CXXRecordDecl *Base) {
3351   Base = Base->getCanonicalDecl();
3352   unsigned Index = 0;
3353   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
3354          E = Derived->bases_end(); I != E; ++I, ++Index) {
3355     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
3356       return Index;
3357   }
3358 
3359   llvm_unreachable("base class missing from derived class's bases list");
3360 }
3361 
3362 /// Extract the value of a character from a string literal.
3363 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
3364                                             uint64_t Index) {
3365   assert(!isa<SourceLocExpr>(Lit) &&
3366          "SourceLocExpr should have already been converted to a StringLiteral");
3367 
3368   // FIXME: Support MakeStringConstant
3369   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
3370     std::string Str;
3371     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
3372     assert(Index <= Str.size() && "Index too large");
3373     return APSInt::getUnsigned(Str.c_str()[Index]);
3374   }
3375 
3376   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
3377     Lit = PE->getFunctionName();
3378   const StringLiteral *S = cast<StringLiteral>(Lit);
3379   const ConstantArrayType *CAT =
3380       Info.Ctx.getAsConstantArrayType(S->getType());
3381   assert(CAT && "string literal isn't an array");
3382   QualType CharType = CAT->getElementType();
3383   assert(CharType->isIntegerType() && "unexpected character type");
3384 
3385   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3386                CharType->isUnsignedIntegerType());
3387   if (Index < S->getLength())
3388     Value = S->getCodeUnit(Index);
3389   return Value;
3390 }
3391 
3392 // Expand a string literal into an array of characters.
3393 //
3394 // FIXME: This is inefficient; we should probably introduce something similar
3395 // to the LLVM ConstantDataArray to make this cheaper.
3396 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
3397                                 APValue &Result,
3398                                 QualType AllocType = QualType()) {
3399   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
3400       AllocType.isNull() ? S->getType() : AllocType);
3401   assert(CAT && "string literal isn't an array");
3402   QualType CharType = CAT->getElementType();
3403   assert(CharType->isIntegerType() && "unexpected character type");
3404 
3405   unsigned Elts = CAT->getSize().getZExtValue();
3406   Result = APValue(APValue::UninitArray(),
3407                    std::min(S->getLength(), Elts), Elts);
3408   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
3409                CharType->isUnsignedIntegerType());
3410   if (Result.hasArrayFiller())
3411     Result.getArrayFiller() = APValue(Value);
3412   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
3413     Value = S->getCodeUnit(I);
3414     Result.getArrayInitializedElt(I) = APValue(Value);
3415   }
3416 }
3417 
3418 // Expand an array so that it has more than Index filled elements.
3419 static void expandArray(APValue &Array, unsigned Index) {
3420   unsigned Size = Array.getArraySize();
3421   assert(Index < Size);
3422 
3423   // Always at least double the number of elements for which we store a value.
3424   unsigned OldElts = Array.getArrayInitializedElts();
3425   unsigned NewElts = std::max(Index+1, OldElts * 2);
3426   NewElts = std::min(Size, std::max(NewElts, 8u));
3427 
3428   // Copy the data across.
3429   APValue NewValue(APValue::UninitArray(), NewElts, Size);
3430   for (unsigned I = 0; I != OldElts; ++I)
3431     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
3432   for (unsigned I = OldElts; I != NewElts; ++I)
3433     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
3434   if (NewValue.hasArrayFiller())
3435     NewValue.getArrayFiller() = Array.getArrayFiller();
3436   Array.swap(NewValue);
3437 }
3438 
3439 /// Determine whether a type would actually be read by an lvalue-to-rvalue
3440 /// conversion. If it's of class type, we may assume that the copy operation
3441 /// is trivial. Note that this is never true for a union type with fields
3442 /// (because the copy always "reads" the active member) and always true for
3443 /// a non-class type.
3444 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD);
3445 static bool isReadByLvalueToRvalueConversion(QualType T) {
3446   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3447   return !RD || isReadByLvalueToRvalueConversion(RD);
3448 }
3449 static bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD) {
3450   // FIXME: A trivial copy of a union copies the object representation, even if
3451   // the union is empty.
3452   if (RD->isUnion())
3453     return !RD->field_empty();
3454   if (RD->isEmpty())
3455     return false;
3456 
3457   for (auto *Field : RD->fields())
3458     if (!Field->isUnnamedBitfield() &&
3459         isReadByLvalueToRvalueConversion(Field->getType()))
3460       return true;
3461 
3462   for (auto &BaseSpec : RD->bases())
3463     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
3464       return true;
3465 
3466   return false;
3467 }
3468 
3469 /// Diagnose an attempt to read from any unreadable field within the specified
3470 /// type, which might be a class type.
3471 static bool diagnoseMutableFields(EvalInfo &Info, const Expr *E, AccessKinds AK,
3472                                   QualType T) {
3473   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3474   if (!RD)
3475     return false;
3476 
3477   if (!RD->hasMutableFields())
3478     return false;
3479 
3480   for (auto *Field : RD->fields()) {
3481     // If we're actually going to read this field in some way, then it can't
3482     // be mutable. If we're in a union, then assigning to a mutable field
3483     // (even an empty one) can change the active member, so that's not OK.
3484     // FIXME: Add core issue number for the union case.
3485     if (Field->isMutable() &&
3486         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
3487       Info.FFDiag(E, diag::note_constexpr_access_mutable, 1) << AK << Field;
3488       Info.Note(Field->getLocation(), diag::note_declared_at);
3489       return true;
3490     }
3491 
3492     if (diagnoseMutableFields(Info, E, AK, Field->getType()))
3493       return true;
3494   }
3495 
3496   for (auto &BaseSpec : RD->bases())
3497     if (diagnoseMutableFields(Info, E, AK, BaseSpec.getType()))
3498       return true;
3499 
3500   // All mutable fields were empty, and thus not actually read.
3501   return false;
3502 }
3503 
3504 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
3505                                         APValue::LValueBase Base,
3506                                         bool MutableSubobject = false) {
3507   // A temporary or transient heap allocation we created.
3508   if (Base.getCallIndex() || Base.is<DynamicAllocLValue>())
3509     return true;
3510 
3511   switch (Info.IsEvaluatingDecl) {
3512   case EvalInfo::EvaluatingDeclKind::None:
3513     return false;
3514 
3515   case EvalInfo::EvaluatingDeclKind::Ctor:
3516     // The variable whose initializer we're evaluating.
3517     if (Info.EvaluatingDecl == Base)
3518       return true;
3519 
3520     // A temporary lifetime-extended by the variable whose initializer we're
3521     // evaluating.
3522     if (auto *BaseE = Base.dyn_cast<const Expr *>())
3523       if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
3524         return Info.EvaluatingDecl == BaseMTE->getExtendingDecl();
3525     return false;
3526 
3527   case EvalInfo::EvaluatingDeclKind::Dtor:
3528     // C++2a [expr.const]p6:
3529     //   [during constant destruction] the lifetime of a and its non-mutable
3530     //   subobjects (but not its mutable subobjects) [are] considered to start
3531     //   within e.
3532     if (MutableSubobject || Base != Info.EvaluatingDecl)
3533       return false;
3534     // FIXME: We can meaningfully extend this to cover non-const objects, but
3535     // we will need special handling: we should be able to access only
3536     // subobjects of such objects that are themselves declared const.
3537     QualType T = getType(Base);
3538     return T.isConstQualified() || T->isReferenceType();
3539   }
3540 
3541   llvm_unreachable("unknown evaluating decl kind");
3542 }
3543 
3544 namespace {
3545 /// A handle to a complete object (an object that is not a subobject of
3546 /// another object).
3547 struct CompleteObject {
3548   /// The identity of the object.
3549   APValue::LValueBase Base;
3550   /// The value of the complete object.
3551   APValue *Value;
3552   /// The type of the complete object.
3553   QualType Type;
3554 
3555   CompleteObject() : Value(nullptr) {}
3556   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
3557       : Base(Base), Value(Value), Type(Type) {}
3558 
3559   bool mayAccessMutableMembers(EvalInfo &Info, AccessKinds AK) const {
3560     // If this isn't a "real" access (eg, if it's just accessing the type
3561     // info), allow it. We assume the type doesn't change dynamically for
3562     // subobjects of constexpr objects (even though we'd hit UB here if it
3563     // did). FIXME: Is this right?
3564     if (!isAnyAccess(AK))
3565       return true;
3566 
3567     // In C++14 onwards, it is permitted to read a mutable member whose
3568     // lifetime began within the evaluation.
3569     // FIXME: Should we also allow this in C++11?
3570     if (!Info.getLangOpts().CPlusPlus14)
3571       return false;
3572     return lifetimeStartedInEvaluation(Info, Base, /*MutableSubobject*/true);
3573   }
3574 
3575   explicit operator bool() const { return !Type.isNull(); }
3576 };
3577 } // end anonymous namespace
3578 
3579 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
3580                                  bool IsMutable = false) {
3581   // C++ [basic.type.qualifier]p1:
3582   // - A const object is an object of type const T or a non-mutable subobject
3583   //   of a const object.
3584   if (ObjType.isConstQualified() && !IsMutable)
3585     SubobjType.addConst();
3586   // - A volatile object is an object of type const T or a subobject of a
3587   //   volatile object.
3588   if (ObjType.isVolatileQualified())
3589     SubobjType.addVolatile();
3590   return SubobjType;
3591 }
3592 
3593 /// Find the designated sub-object of an rvalue.
3594 template<typename SubobjectHandler>
3595 typename SubobjectHandler::result_type
3596 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
3597               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
3598   if (Sub.Invalid)
3599     // A diagnostic will have already been produced.
3600     return handler.failed();
3601   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
3602     if (Info.getLangOpts().CPlusPlus11)
3603       Info.FFDiag(E, Sub.isOnePastTheEnd()
3604                          ? diag::note_constexpr_access_past_end
3605                          : diag::note_constexpr_access_unsized_array)
3606           << handler.AccessKind;
3607     else
3608       Info.FFDiag(E);
3609     return handler.failed();
3610   }
3611 
3612   APValue *O = Obj.Value;
3613   QualType ObjType = Obj.Type;
3614   const FieldDecl *LastField = nullptr;
3615   const FieldDecl *VolatileField = nullptr;
3616 
3617   // Walk the designator's path to find the subobject.
3618   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
3619     // Reading an indeterminate value is undefined, but assigning over one is OK.
3620     if ((O->isAbsent() && !(handler.AccessKind == AK_Construct && I == N)) ||
3621         (O->isIndeterminate() &&
3622          !isValidIndeterminateAccess(handler.AccessKind))) {
3623       if (!Info.checkingPotentialConstantExpression())
3624         Info.FFDiag(E, diag::note_constexpr_access_uninit)
3625             << handler.AccessKind << O->isIndeterminate();
3626       return handler.failed();
3627     }
3628 
3629     // C++ [class.ctor]p5, C++ [class.dtor]p5:
3630     //    const and volatile semantics are not applied on an object under
3631     //    {con,de}struction.
3632     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
3633         ObjType->isRecordType() &&
3634         Info.isEvaluatingCtorDtor(
3635             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
3636                                          Sub.Entries.begin() + I)) !=
3637                           ConstructionPhase::None) {
3638       ObjType = Info.Ctx.getCanonicalType(ObjType);
3639       ObjType.removeLocalConst();
3640       ObjType.removeLocalVolatile();
3641     }
3642 
3643     // If this is our last pass, check that the final object type is OK.
3644     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3645       // Accesses to volatile objects are prohibited.
3646       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3647         if (Info.getLangOpts().CPlusPlus) {
3648           int DiagKind;
3649           SourceLocation Loc;
3650           const NamedDecl *Decl = nullptr;
3651           if (VolatileField) {
3652             DiagKind = 2;
3653             Loc = VolatileField->getLocation();
3654             Decl = VolatileField;
3655           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3656             DiagKind = 1;
3657             Loc = VD->getLocation();
3658             Decl = VD;
3659           } else {
3660             DiagKind = 0;
3661             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3662               Loc = E->getExprLoc();
3663           }
3664           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3665               << handler.AccessKind << DiagKind << Decl;
3666           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3667         } else {
3668           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3669         }
3670         return handler.failed();
3671       }
3672 
3673       // If we are reading an object of class type, there may still be more
3674       // things we need to check: if there are any mutable subobjects, we
3675       // cannot perform this read. (This only happens when performing a trivial
3676       // copy or assignment.)
3677       if (ObjType->isRecordType() &&
3678           !Obj.mayAccessMutableMembers(Info, handler.AccessKind) &&
3679           diagnoseMutableFields(Info, E, handler.AccessKind, ObjType))
3680         return handler.failed();
3681     }
3682 
3683     if (I == N) {
3684       if (!handler.found(*O, ObjType))
3685         return false;
3686 
3687       // If we modified a bit-field, truncate it to the right width.
3688       if (isModification(handler.AccessKind) &&
3689           LastField && LastField->isBitField() &&
3690           !truncateBitfieldValue(Info, E, *O, LastField))
3691         return false;
3692 
3693       return true;
3694     }
3695 
3696     LastField = nullptr;
3697     if (ObjType->isArrayType()) {
3698       // Next subobject is an array element.
3699       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3700       assert(CAT && "vla in literal type?");
3701       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3702       if (CAT->getSize().ule(Index)) {
3703         // Note, it should not be possible to form a pointer with a valid
3704         // designator which points more than one past the end of the array.
3705         if (Info.getLangOpts().CPlusPlus11)
3706           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3707             << handler.AccessKind;
3708         else
3709           Info.FFDiag(E);
3710         return handler.failed();
3711       }
3712 
3713       ObjType = CAT->getElementType();
3714 
3715       if (O->getArrayInitializedElts() > Index)
3716         O = &O->getArrayInitializedElt(Index);
3717       else if (!isRead(handler.AccessKind)) {
3718         expandArray(*O, Index);
3719         O = &O->getArrayInitializedElt(Index);
3720       } else
3721         O = &O->getArrayFiller();
3722     } else if (ObjType->isAnyComplexType()) {
3723       // Next subobject is a complex number.
3724       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3725       if (Index > 1) {
3726         if (Info.getLangOpts().CPlusPlus11)
3727           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3728             << handler.AccessKind;
3729         else
3730           Info.FFDiag(E);
3731         return handler.failed();
3732       }
3733 
3734       ObjType = getSubobjectType(
3735           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3736 
3737       assert(I == N - 1 && "extracting subobject of scalar?");
3738       if (O->isComplexInt()) {
3739         return handler.found(Index ? O->getComplexIntImag()
3740                                    : O->getComplexIntReal(), ObjType);
3741       } else {
3742         assert(O->isComplexFloat());
3743         return handler.found(Index ? O->getComplexFloatImag()
3744                                    : O->getComplexFloatReal(), ObjType);
3745       }
3746     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3747       if (Field->isMutable() &&
3748           !Obj.mayAccessMutableMembers(Info, handler.AccessKind)) {
3749         Info.FFDiag(E, diag::note_constexpr_access_mutable, 1)
3750           << handler.AccessKind << Field;
3751         Info.Note(Field->getLocation(), diag::note_declared_at);
3752         return handler.failed();
3753       }
3754 
3755       // Next subobject is a class, struct or union field.
3756       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3757       if (RD->isUnion()) {
3758         const FieldDecl *UnionField = O->getUnionField();
3759         if (!UnionField ||
3760             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3761           if (I == N - 1 && handler.AccessKind == AK_Construct) {
3762             // Placement new onto an inactive union member makes it active.
3763             O->setUnion(Field, APValue());
3764           } else {
3765             // FIXME: If O->getUnionValue() is absent, report that there's no
3766             // active union member rather than reporting the prior active union
3767             // member. We'll need to fix nullptr_t to not use APValue() as its
3768             // representation first.
3769             Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3770                 << handler.AccessKind << Field << !UnionField << UnionField;
3771             return handler.failed();
3772           }
3773         }
3774         O = &O->getUnionValue();
3775       } else
3776         O = &O->getStructField(Field->getFieldIndex());
3777 
3778       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3779       LastField = Field;
3780       if (Field->getType().isVolatileQualified())
3781         VolatileField = Field;
3782     } else {
3783       // Next subobject is a base class.
3784       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3785       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3786       O = &O->getStructBase(getBaseIndex(Derived, Base));
3787 
3788       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3789     }
3790   }
3791 }
3792 
3793 namespace {
3794 struct ExtractSubobjectHandler {
3795   EvalInfo &Info;
3796   const Expr *E;
3797   APValue &Result;
3798   const AccessKinds AccessKind;
3799 
3800   typedef bool result_type;
3801   bool failed() { return false; }
3802   bool found(APValue &Subobj, QualType SubobjType) {
3803     Result = Subobj;
3804     if (AccessKind == AK_ReadObjectRepresentation)
3805       return true;
3806     return CheckFullyInitialized(Info, E->getExprLoc(), SubobjType, Result);
3807   }
3808   bool found(APSInt &Value, QualType SubobjType) {
3809     Result = APValue(Value);
3810     return true;
3811   }
3812   bool found(APFloat &Value, QualType SubobjType) {
3813     Result = APValue(Value);
3814     return true;
3815   }
3816 };
3817 } // end anonymous namespace
3818 
3819 /// Extract the designated sub-object of an rvalue.
3820 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3821                              const CompleteObject &Obj,
3822                              const SubobjectDesignator &Sub, APValue &Result,
3823                              AccessKinds AK = AK_Read) {
3824   assert(AK == AK_Read || AK == AK_ReadObjectRepresentation);
3825   ExtractSubobjectHandler Handler = {Info, E, Result, AK};
3826   return findSubobject(Info, E, Obj, Sub, Handler);
3827 }
3828 
3829 namespace {
3830 struct ModifySubobjectHandler {
3831   EvalInfo &Info;
3832   APValue &NewVal;
3833   const Expr *E;
3834 
3835   typedef bool result_type;
3836   static const AccessKinds AccessKind = AK_Assign;
3837 
3838   bool checkConst(QualType QT) {
3839     // Assigning to a const object has undefined behavior.
3840     if (QT.isConstQualified()) {
3841       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3842       return false;
3843     }
3844     return true;
3845   }
3846 
3847   bool failed() { return false; }
3848   bool found(APValue &Subobj, QualType SubobjType) {
3849     if (!checkConst(SubobjType))
3850       return false;
3851     // We've been given ownership of NewVal, so just swap it in.
3852     Subobj.swap(NewVal);
3853     return true;
3854   }
3855   bool found(APSInt &Value, QualType SubobjType) {
3856     if (!checkConst(SubobjType))
3857       return false;
3858     if (!NewVal.isInt()) {
3859       // Maybe trying to write a cast pointer value into a complex?
3860       Info.FFDiag(E);
3861       return false;
3862     }
3863     Value = NewVal.getInt();
3864     return true;
3865   }
3866   bool found(APFloat &Value, QualType SubobjType) {
3867     if (!checkConst(SubobjType))
3868       return false;
3869     Value = NewVal.getFloat();
3870     return true;
3871   }
3872 };
3873 } // end anonymous namespace
3874 
3875 const AccessKinds ModifySubobjectHandler::AccessKind;
3876 
3877 /// Update the designated sub-object of an rvalue to the given value.
3878 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3879                             const CompleteObject &Obj,
3880                             const SubobjectDesignator &Sub,
3881                             APValue &NewVal) {
3882   ModifySubobjectHandler Handler = { Info, NewVal, E };
3883   return findSubobject(Info, E, Obj, Sub, Handler);
3884 }
3885 
3886 /// Find the position where two subobject designators diverge, or equivalently
3887 /// the length of the common initial subsequence.
3888 static unsigned FindDesignatorMismatch(QualType ObjType,
3889                                        const SubobjectDesignator &A,
3890                                        const SubobjectDesignator &B,
3891                                        bool &WasArrayIndex) {
3892   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3893   for (/**/; I != N; ++I) {
3894     if (!ObjType.isNull() &&
3895         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3896       // Next subobject is an array element.
3897       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3898         WasArrayIndex = true;
3899         return I;
3900       }
3901       if (ObjType->isAnyComplexType())
3902         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3903       else
3904         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3905     } else {
3906       if (A.Entries[I].getAsBaseOrMember() !=
3907           B.Entries[I].getAsBaseOrMember()) {
3908         WasArrayIndex = false;
3909         return I;
3910       }
3911       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3912         // Next subobject is a field.
3913         ObjType = FD->getType();
3914       else
3915         // Next subobject is a base class.
3916         ObjType = QualType();
3917     }
3918   }
3919   WasArrayIndex = false;
3920   return I;
3921 }
3922 
3923 /// Determine whether the given subobject designators refer to elements of the
3924 /// same array object.
3925 static bool AreElementsOfSameArray(QualType ObjType,
3926                                    const SubobjectDesignator &A,
3927                                    const SubobjectDesignator &B) {
3928   if (A.Entries.size() != B.Entries.size())
3929     return false;
3930 
3931   bool IsArray = A.MostDerivedIsArrayElement;
3932   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3933     // A is a subobject of the array element.
3934     return false;
3935 
3936   // If A (and B) designates an array element, the last entry will be the array
3937   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3938   // of length 1' case, and the entire path must match.
3939   bool WasArrayIndex;
3940   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3941   return CommonLength >= A.Entries.size() - IsArray;
3942 }
3943 
3944 /// Find the complete object to which an LValue refers.
3945 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3946                                          AccessKinds AK, const LValue &LVal,
3947                                          QualType LValType) {
3948   if (LVal.InvalidBase) {
3949     Info.FFDiag(E);
3950     return CompleteObject();
3951   }
3952 
3953   if (!LVal.Base) {
3954     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3955     return CompleteObject();
3956   }
3957 
3958   CallStackFrame *Frame = nullptr;
3959   unsigned Depth = 0;
3960   if (LVal.getLValueCallIndex()) {
3961     std::tie(Frame, Depth) =
3962         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3963     if (!Frame) {
3964       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3965         << AK << LVal.Base.is<const ValueDecl*>();
3966       NoteLValueLocation(Info, LVal.Base);
3967       return CompleteObject();
3968     }
3969   }
3970 
3971   bool IsAccess = isAnyAccess(AK);
3972 
3973   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3974   // is not a constant expression (even if the object is non-volatile). We also
3975   // apply this rule to C++98, in order to conform to the expected 'volatile'
3976   // semantics.
3977   if (isFormalAccess(AK) && LValType.isVolatileQualified()) {
3978     if (Info.getLangOpts().CPlusPlus)
3979       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3980         << AK << LValType;
3981     else
3982       Info.FFDiag(E);
3983     return CompleteObject();
3984   }
3985 
3986   // Compute value storage location and type of base object.
3987   APValue *BaseVal = nullptr;
3988   QualType BaseType = getType(LVal.Base);
3989 
3990   if (Info.getLangOpts().CPlusPlus14 && LVal.Base == Info.EvaluatingDecl &&
3991       lifetimeStartedInEvaluation(Info, LVal.Base)) {
3992     // This is the object whose initializer we're evaluating, so its lifetime
3993     // started in the current evaluation.
3994     BaseVal = Info.EvaluatingDeclValue;
3995   } else if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl *>()) {
3996     // Allow reading from a GUID declaration.
3997     if (auto *GD = dyn_cast<MSGuidDecl>(D)) {
3998       if (isModification(AK)) {
3999         // All the remaining cases do not permit modification of the object.
4000         Info.FFDiag(E, diag::note_constexpr_modify_global);
4001         return CompleteObject();
4002       }
4003       APValue &V = GD->getAsAPValue();
4004       if (V.isAbsent()) {
4005         Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
4006             << GD->getType();
4007         return CompleteObject();
4008       }
4009       return CompleteObject(LVal.Base, &V, GD->getType());
4010     }
4011 
4012     // Allow reading from template parameter objects.
4013     if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(D)) {
4014       if (isModification(AK)) {
4015         Info.FFDiag(E, diag::note_constexpr_modify_global);
4016         return CompleteObject();
4017       }
4018       return CompleteObject(LVal.Base, const_cast<APValue *>(&TPO->getValue()),
4019                             TPO->getType());
4020     }
4021 
4022     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
4023     // In C++11, constexpr, non-volatile variables initialized with constant
4024     // expressions are constant expressions too. Inside constexpr functions,
4025     // parameters are constant expressions even if they're non-const.
4026     // In C++1y, objects local to a constant expression (those with a Frame) are
4027     // both readable and writable inside constant expressions.
4028     // In C, such things can also be folded, although they are not ICEs.
4029     const VarDecl *VD = dyn_cast<VarDecl>(D);
4030     if (VD) {
4031       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
4032         VD = VDef;
4033     }
4034     if (!VD || VD->isInvalidDecl()) {
4035       Info.FFDiag(E);
4036       return CompleteObject();
4037     }
4038 
4039     bool IsConstant = BaseType.isConstant(Info.Ctx);
4040 
4041     // Unless we're looking at a local variable or argument in a constexpr call,
4042     // the variable we're reading must be const.
4043     if (!Frame) {
4044       if (IsAccess && isa<ParmVarDecl>(VD)) {
4045         // Access of a parameter that's not associated with a frame isn't going
4046         // to work out, but we can leave it to evaluateVarDeclInit to provide a
4047         // suitable diagnostic.
4048       } else if (Info.getLangOpts().CPlusPlus14 &&
4049                  lifetimeStartedInEvaluation(Info, LVal.Base)) {
4050         // OK, we can read and modify an object if we're in the process of
4051         // evaluating its initializer, because its lifetime began in this
4052         // evaluation.
4053       } else if (isModification(AK)) {
4054         // All the remaining cases do not permit modification of the object.
4055         Info.FFDiag(E, diag::note_constexpr_modify_global);
4056         return CompleteObject();
4057       } else if (VD->isConstexpr()) {
4058         // OK, we can read this variable.
4059       } else if (BaseType->isIntegralOrEnumerationType()) {
4060         if (!IsConstant) {
4061           if (!IsAccess)
4062             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4063           if (Info.getLangOpts().CPlusPlus) {
4064             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
4065             Info.Note(VD->getLocation(), diag::note_declared_at);
4066           } else {
4067             Info.FFDiag(E);
4068           }
4069           return CompleteObject();
4070         }
4071       } else if (!IsAccess) {
4072         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4073       } else if (IsConstant && Info.checkingPotentialConstantExpression() &&
4074                  BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
4075         // This variable might end up being constexpr. Don't diagnose it yet.
4076       } else if (IsConstant) {
4077         // Keep evaluating to see what we can do. In particular, we support
4078         // folding of const floating-point types, in order to make static const
4079         // data members of such types (supported as an extension) more useful.
4080         if (Info.getLangOpts().CPlusPlus) {
4081           Info.CCEDiag(E, Info.getLangOpts().CPlusPlus11
4082                               ? diag::note_constexpr_ltor_non_constexpr
4083                               : diag::note_constexpr_ltor_non_integral, 1)
4084               << VD << BaseType;
4085           Info.Note(VD->getLocation(), diag::note_declared_at);
4086         } else {
4087           Info.CCEDiag(E);
4088         }
4089       } else {
4090         // Never allow reading a non-const value.
4091         if (Info.getLangOpts().CPlusPlus) {
4092           Info.FFDiag(E, Info.getLangOpts().CPlusPlus11
4093                              ? diag::note_constexpr_ltor_non_constexpr
4094                              : diag::note_constexpr_ltor_non_integral, 1)
4095               << VD << BaseType;
4096           Info.Note(VD->getLocation(), diag::note_declared_at);
4097         } else {
4098           Info.FFDiag(E);
4099         }
4100         return CompleteObject();
4101       }
4102     }
4103 
4104     if (!evaluateVarDeclInit(Info, E, VD, Frame, LVal.getLValueVersion(), BaseVal))
4105       return CompleteObject();
4106   } else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
4107     Optional<DynAlloc*> Alloc = Info.lookupDynamicAlloc(DA);
4108     if (!Alloc) {
4109       Info.FFDiag(E, diag::note_constexpr_access_deleted_object) << AK;
4110       return CompleteObject();
4111     }
4112     return CompleteObject(LVal.Base, &(*Alloc)->Value,
4113                           LVal.Base.getDynamicAllocType());
4114   } else {
4115     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4116 
4117     if (!Frame) {
4118       if (const MaterializeTemporaryExpr *MTE =
4119               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
4120         assert(MTE->getStorageDuration() == SD_Static &&
4121                "should have a frame for a non-global materialized temporary");
4122 
4123         // C++20 [expr.const]p4: [DR2126]
4124         //   An object or reference is usable in constant expressions if it is
4125         //   - a temporary object of non-volatile const-qualified literal type
4126         //     whose lifetime is extended to that of a variable that is usable
4127         //     in constant expressions
4128         //
4129         // C++20 [expr.const]p5:
4130         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
4131         //   - a non-volatile glvalue that refers to an object that is usable
4132         //     in constant expressions, or
4133         //   - a non-volatile glvalue of literal type that refers to a
4134         //     non-volatile object whose lifetime began within the evaluation
4135         //     of E;
4136         //
4137         // C++11 misses the 'began within the evaluation of e' check and
4138         // instead allows all temporaries, including things like:
4139         //   int &&r = 1;
4140         //   int x = ++r;
4141         //   constexpr int k = r;
4142         // Therefore we use the C++14-onwards rules in C++11 too.
4143         //
4144         // Note that temporaries whose lifetimes began while evaluating a
4145         // variable's constructor are not usable while evaluating the
4146         // corresponding destructor, not even if they're of const-qualified
4147         // types.
4148         if (!MTE->isUsableInConstantExpressions(Info.Ctx) &&
4149             !lifetimeStartedInEvaluation(Info, LVal.Base)) {
4150           if (!IsAccess)
4151             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4152           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
4153           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
4154           return CompleteObject();
4155         }
4156 
4157         BaseVal = MTE->getOrCreateValue(false);
4158         assert(BaseVal && "got reference to unevaluated temporary");
4159       } else {
4160         if (!IsAccess)
4161           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
4162         APValue Val;
4163         LVal.moveInto(Val);
4164         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
4165             << AK
4166             << Val.getAsString(Info.Ctx,
4167                                Info.Ctx.getLValueReferenceType(LValType));
4168         NoteLValueLocation(Info, LVal.Base);
4169         return CompleteObject();
4170       }
4171     } else {
4172       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
4173       assert(BaseVal && "missing value for temporary");
4174     }
4175   }
4176 
4177   // In C++14, we can't safely access any mutable state when we might be
4178   // evaluating after an unmodeled side effect. Parameters are modeled as state
4179   // in the caller, but aren't visible once the call returns, so they can be
4180   // modified in a speculatively-evaluated call.
4181   //
4182   // FIXME: Not all local state is mutable. Allow local constant subobjects
4183   // to be read here (but take care with 'mutable' fields).
4184   unsigned VisibleDepth = Depth;
4185   if (llvm::isa_and_nonnull<ParmVarDecl>(
4186           LVal.Base.dyn_cast<const ValueDecl *>()))
4187     ++VisibleDepth;
4188   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
4189        Info.EvalStatus.HasSideEffects) ||
4190       (isModification(AK) && VisibleDepth < Info.SpeculativeEvaluationDepth))
4191     return CompleteObject();
4192 
4193   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
4194 }
4195 
4196 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
4197 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
4198 /// glvalue referred to by an entity of reference type.
4199 ///
4200 /// \param Info - Information about the ongoing evaluation.
4201 /// \param Conv - The expression for which we are performing the conversion.
4202 ///               Used for diagnostics.
4203 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
4204 ///               case of a non-class type).
4205 /// \param LVal - The glvalue on which we are attempting to perform this action.
4206 /// \param RVal - The produced value will be placed here.
4207 /// \param WantObjectRepresentation - If true, we're looking for the object
4208 ///               representation rather than the value, and in particular,
4209 ///               there is no requirement that the result be fully initialized.
4210 static bool
4211 handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv, QualType Type,
4212                                const LValue &LVal, APValue &RVal,
4213                                bool WantObjectRepresentation = false) {
4214   if (LVal.Designator.Invalid)
4215     return false;
4216 
4217   // Check for special cases where there is no existing APValue to look at.
4218   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
4219 
4220   AccessKinds AK =
4221       WantObjectRepresentation ? AK_ReadObjectRepresentation : AK_Read;
4222 
4223   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
4224     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
4225       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
4226       // initializer until now for such expressions. Such an expression can't be
4227       // an ICE in C, so this only matters for fold.
4228       if (Type.isVolatileQualified()) {
4229         Info.FFDiag(Conv);
4230         return false;
4231       }
4232       APValue Lit;
4233       if (!Evaluate(Lit, Info, CLE->getInitializer()))
4234         return false;
4235       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
4236       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal, AK);
4237     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
4238       // Special-case character extraction so we don't have to construct an
4239       // APValue for the whole string.
4240       assert(LVal.Designator.Entries.size() <= 1 &&
4241              "Can only read characters from string literals");
4242       if (LVal.Designator.Entries.empty()) {
4243         // Fail for now for LValue to RValue conversion of an array.
4244         // (This shouldn't show up in C/C++, but it could be triggered by a
4245         // weird EvaluateAsRValue call from a tool.)
4246         Info.FFDiag(Conv);
4247         return false;
4248       }
4249       if (LVal.Designator.isOnePastTheEnd()) {
4250         if (Info.getLangOpts().CPlusPlus11)
4251           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK;
4252         else
4253           Info.FFDiag(Conv);
4254         return false;
4255       }
4256       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
4257       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
4258       return true;
4259     }
4260   }
4261 
4262   CompleteObject Obj = findCompleteObject(Info, Conv, AK, LVal, Type);
4263   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal, AK);
4264 }
4265 
4266 /// Perform an assignment of Val to LVal. Takes ownership of Val.
4267 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
4268                              QualType LValType, APValue &Val) {
4269   if (LVal.Designator.Invalid)
4270     return false;
4271 
4272   if (!Info.getLangOpts().CPlusPlus14) {
4273     Info.FFDiag(E);
4274     return false;
4275   }
4276 
4277   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4278   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
4279 }
4280 
4281 namespace {
4282 struct CompoundAssignSubobjectHandler {
4283   EvalInfo &Info;
4284   const CompoundAssignOperator *E;
4285   QualType PromotedLHSType;
4286   BinaryOperatorKind Opcode;
4287   const APValue &RHS;
4288 
4289   static const AccessKinds AccessKind = AK_Assign;
4290 
4291   typedef bool result_type;
4292 
4293   bool checkConst(QualType QT) {
4294     // Assigning to a const object has undefined behavior.
4295     if (QT.isConstQualified()) {
4296       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4297       return false;
4298     }
4299     return true;
4300   }
4301 
4302   bool failed() { return false; }
4303   bool found(APValue &Subobj, QualType SubobjType) {
4304     switch (Subobj.getKind()) {
4305     case APValue::Int:
4306       return found(Subobj.getInt(), SubobjType);
4307     case APValue::Float:
4308       return found(Subobj.getFloat(), SubobjType);
4309     case APValue::ComplexInt:
4310     case APValue::ComplexFloat:
4311       // FIXME: Implement complex compound assignment.
4312       Info.FFDiag(E);
4313       return false;
4314     case APValue::LValue:
4315       return foundPointer(Subobj, SubobjType);
4316     case APValue::Vector:
4317       return foundVector(Subobj, SubobjType);
4318     default:
4319       // FIXME: can this happen?
4320       Info.FFDiag(E);
4321       return false;
4322     }
4323   }
4324 
4325   bool foundVector(APValue &Value, QualType SubobjType) {
4326     if (!checkConst(SubobjType))
4327       return false;
4328 
4329     if (!SubobjType->isVectorType()) {
4330       Info.FFDiag(E);
4331       return false;
4332     }
4333     return handleVectorVectorBinOp(Info, E, Opcode, Value, RHS);
4334   }
4335 
4336   bool found(APSInt &Value, QualType SubobjType) {
4337     if (!checkConst(SubobjType))
4338       return false;
4339 
4340     if (!SubobjType->isIntegerType()) {
4341       // We don't support compound assignment on integer-cast-to-pointer
4342       // values.
4343       Info.FFDiag(E);
4344       return false;
4345     }
4346 
4347     if (RHS.isInt()) {
4348       APSInt LHS =
4349           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
4350       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
4351         return false;
4352       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
4353       return true;
4354     } else if (RHS.isFloat()) {
4355       const FPOptions FPO = E->getFPFeaturesInEffect(
4356                                     Info.Ctx.getLangOpts());
4357       APFloat FValue(0.0);
4358       return HandleIntToFloatCast(Info, E, FPO, SubobjType, Value,
4359                                   PromotedLHSType, FValue) &&
4360              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
4361              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
4362                                   Value);
4363     }
4364 
4365     Info.FFDiag(E);
4366     return false;
4367   }
4368   bool found(APFloat &Value, QualType SubobjType) {
4369     return checkConst(SubobjType) &&
4370            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
4371                                   Value) &&
4372            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
4373            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
4374   }
4375   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4376     if (!checkConst(SubobjType))
4377       return false;
4378 
4379     QualType PointeeType;
4380     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4381       PointeeType = PT->getPointeeType();
4382 
4383     if (PointeeType.isNull() || !RHS.isInt() ||
4384         (Opcode != BO_Add && Opcode != BO_Sub)) {
4385       Info.FFDiag(E);
4386       return false;
4387     }
4388 
4389     APSInt Offset = RHS.getInt();
4390     if (Opcode == BO_Sub)
4391       negateAsSigned(Offset);
4392 
4393     LValue LVal;
4394     LVal.setFrom(Info.Ctx, Subobj);
4395     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
4396       return false;
4397     LVal.moveInto(Subobj);
4398     return true;
4399   }
4400 };
4401 } // end anonymous namespace
4402 
4403 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
4404 
4405 /// Perform a compound assignment of LVal <op>= RVal.
4406 static bool handleCompoundAssignment(EvalInfo &Info,
4407                                      const CompoundAssignOperator *E,
4408                                      const LValue &LVal, QualType LValType,
4409                                      QualType PromotedLValType,
4410                                      BinaryOperatorKind Opcode,
4411                                      const APValue &RVal) {
4412   if (LVal.Designator.Invalid)
4413     return false;
4414 
4415   if (!Info.getLangOpts().CPlusPlus14) {
4416     Info.FFDiag(E);
4417     return false;
4418   }
4419 
4420   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
4421   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
4422                                              RVal };
4423   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4424 }
4425 
4426 namespace {
4427 struct IncDecSubobjectHandler {
4428   EvalInfo &Info;
4429   const UnaryOperator *E;
4430   AccessKinds AccessKind;
4431   APValue *Old;
4432 
4433   typedef bool result_type;
4434 
4435   bool checkConst(QualType QT) {
4436     // Assigning to a const object has undefined behavior.
4437     if (QT.isConstQualified()) {
4438       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
4439       return false;
4440     }
4441     return true;
4442   }
4443 
4444   bool failed() { return false; }
4445   bool found(APValue &Subobj, QualType SubobjType) {
4446     // Stash the old value. Also clear Old, so we don't clobber it later
4447     // if we're post-incrementing a complex.
4448     if (Old) {
4449       *Old = Subobj;
4450       Old = nullptr;
4451     }
4452 
4453     switch (Subobj.getKind()) {
4454     case APValue::Int:
4455       return found(Subobj.getInt(), SubobjType);
4456     case APValue::Float:
4457       return found(Subobj.getFloat(), SubobjType);
4458     case APValue::ComplexInt:
4459       return found(Subobj.getComplexIntReal(),
4460                    SubobjType->castAs<ComplexType>()->getElementType()
4461                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4462     case APValue::ComplexFloat:
4463       return found(Subobj.getComplexFloatReal(),
4464                    SubobjType->castAs<ComplexType>()->getElementType()
4465                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
4466     case APValue::LValue:
4467       return foundPointer(Subobj, SubobjType);
4468     default:
4469       // FIXME: can this happen?
4470       Info.FFDiag(E);
4471       return false;
4472     }
4473   }
4474   bool found(APSInt &Value, QualType SubobjType) {
4475     if (!checkConst(SubobjType))
4476       return false;
4477 
4478     if (!SubobjType->isIntegerType()) {
4479       // We don't support increment / decrement on integer-cast-to-pointer
4480       // values.
4481       Info.FFDiag(E);
4482       return false;
4483     }
4484 
4485     if (Old) *Old = APValue(Value);
4486 
4487     // bool arithmetic promotes to int, and the conversion back to bool
4488     // doesn't reduce mod 2^n, so special-case it.
4489     if (SubobjType->isBooleanType()) {
4490       if (AccessKind == AK_Increment)
4491         Value = 1;
4492       else
4493         Value = !Value;
4494       return true;
4495     }
4496 
4497     bool WasNegative = Value.isNegative();
4498     if (AccessKind == AK_Increment) {
4499       ++Value;
4500 
4501       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
4502         APSInt ActualValue(Value, /*IsUnsigned*/true);
4503         return HandleOverflow(Info, E, ActualValue, SubobjType);
4504       }
4505     } else {
4506       --Value;
4507 
4508       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
4509         unsigned BitWidth = Value.getBitWidth();
4510         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
4511         ActualValue.setBit(BitWidth);
4512         return HandleOverflow(Info, E, ActualValue, SubobjType);
4513       }
4514     }
4515     return true;
4516   }
4517   bool found(APFloat &Value, QualType SubobjType) {
4518     if (!checkConst(SubobjType))
4519       return false;
4520 
4521     if (Old) *Old = APValue(Value);
4522 
4523     APFloat One(Value.getSemantics(), 1);
4524     if (AccessKind == AK_Increment)
4525       Value.add(One, APFloat::rmNearestTiesToEven);
4526     else
4527       Value.subtract(One, APFloat::rmNearestTiesToEven);
4528     return true;
4529   }
4530   bool foundPointer(APValue &Subobj, QualType SubobjType) {
4531     if (!checkConst(SubobjType))
4532       return false;
4533 
4534     QualType PointeeType;
4535     if (const PointerType *PT = SubobjType->getAs<PointerType>())
4536       PointeeType = PT->getPointeeType();
4537     else {
4538       Info.FFDiag(E);
4539       return false;
4540     }
4541 
4542     LValue LVal;
4543     LVal.setFrom(Info.Ctx, Subobj);
4544     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
4545                                      AccessKind == AK_Increment ? 1 : -1))
4546       return false;
4547     LVal.moveInto(Subobj);
4548     return true;
4549   }
4550 };
4551 } // end anonymous namespace
4552 
4553 /// Perform an increment or decrement on LVal.
4554 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
4555                          QualType LValType, bool IsIncrement, APValue *Old) {
4556   if (LVal.Designator.Invalid)
4557     return false;
4558 
4559   if (!Info.getLangOpts().CPlusPlus14) {
4560     Info.FFDiag(E);
4561     return false;
4562   }
4563 
4564   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
4565   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
4566   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
4567   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
4568 }
4569 
4570 /// Build an lvalue for the object argument of a member function call.
4571 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
4572                                    LValue &This) {
4573   if (Object->getType()->isPointerType() && Object->isPRValue())
4574     return EvaluatePointer(Object, This, Info);
4575 
4576   if (Object->isGLValue())
4577     return EvaluateLValue(Object, This, Info);
4578 
4579   if (Object->getType()->isLiteralType(Info.Ctx))
4580     return EvaluateTemporary(Object, This, Info);
4581 
4582   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
4583   return false;
4584 }
4585 
4586 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
4587 /// lvalue referring to the result.
4588 ///
4589 /// \param Info - Information about the ongoing evaluation.
4590 /// \param LV - An lvalue referring to the base of the member pointer.
4591 /// \param RHS - The member pointer expression.
4592 /// \param IncludeMember - Specifies whether the member itself is included in
4593 ///        the resulting LValue subobject designator. This is not possible when
4594 ///        creating a bound member function.
4595 /// \return The field or method declaration to which the member pointer refers,
4596 ///         or 0 if evaluation fails.
4597 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4598                                                   QualType LVType,
4599                                                   LValue &LV,
4600                                                   const Expr *RHS,
4601                                                   bool IncludeMember = true) {
4602   MemberPtr MemPtr;
4603   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
4604     return nullptr;
4605 
4606   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
4607   // member value, the behavior is undefined.
4608   if (!MemPtr.getDecl()) {
4609     // FIXME: Specific diagnostic.
4610     Info.FFDiag(RHS);
4611     return nullptr;
4612   }
4613 
4614   if (MemPtr.isDerivedMember()) {
4615     // This is a member of some derived class. Truncate LV appropriately.
4616     // The end of the derived-to-base path for the base object must match the
4617     // derived-to-base path for the member pointer.
4618     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
4619         LV.Designator.Entries.size()) {
4620       Info.FFDiag(RHS);
4621       return nullptr;
4622     }
4623     unsigned PathLengthToMember =
4624         LV.Designator.Entries.size() - MemPtr.Path.size();
4625     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
4626       const CXXRecordDecl *LVDecl = getAsBaseClass(
4627           LV.Designator.Entries[PathLengthToMember + I]);
4628       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
4629       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
4630         Info.FFDiag(RHS);
4631         return nullptr;
4632       }
4633     }
4634 
4635     // Truncate the lvalue to the appropriate derived class.
4636     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
4637                             PathLengthToMember))
4638       return nullptr;
4639   } else if (!MemPtr.Path.empty()) {
4640     // Extend the LValue path with the member pointer's path.
4641     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
4642                                   MemPtr.Path.size() + IncludeMember);
4643 
4644     // Walk down to the appropriate base class.
4645     if (const PointerType *PT = LVType->getAs<PointerType>())
4646       LVType = PT->getPointeeType();
4647     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
4648     assert(RD && "member pointer access on non-class-type expression");
4649     // The first class in the path is that of the lvalue.
4650     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
4651       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
4652       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
4653         return nullptr;
4654       RD = Base;
4655     }
4656     // Finally cast to the class containing the member.
4657     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
4658                                 MemPtr.getContainingRecord()))
4659       return nullptr;
4660   }
4661 
4662   // Add the member. Note that we cannot build bound member functions here.
4663   if (IncludeMember) {
4664     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
4665       if (!HandleLValueMember(Info, RHS, LV, FD))
4666         return nullptr;
4667     } else if (const IndirectFieldDecl *IFD =
4668                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
4669       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
4670         return nullptr;
4671     } else {
4672       llvm_unreachable("can't construct reference to bound member function");
4673     }
4674   }
4675 
4676   return MemPtr.getDecl();
4677 }
4678 
4679 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
4680                                                   const BinaryOperator *BO,
4681                                                   LValue &LV,
4682                                                   bool IncludeMember = true) {
4683   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
4684 
4685   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
4686     if (Info.noteFailure()) {
4687       MemberPtr MemPtr;
4688       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
4689     }
4690     return nullptr;
4691   }
4692 
4693   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
4694                                    BO->getRHS(), IncludeMember);
4695 }
4696 
4697 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
4698 /// the provided lvalue, which currently refers to the base object.
4699 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
4700                                     LValue &Result) {
4701   SubobjectDesignator &D = Result.Designator;
4702   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
4703     return false;
4704 
4705   QualType TargetQT = E->getType();
4706   if (const PointerType *PT = TargetQT->getAs<PointerType>())
4707     TargetQT = PT->getPointeeType();
4708 
4709   // Check this cast lands within the final derived-to-base subobject path.
4710   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
4711     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4712       << D.MostDerivedType << TargetQT;
4713     return false;
4714   }
4715 
4716   // Check the type of the final cast. We don't need to check the path,
4717   // since a cast can only be formed if the path is unique.
4718   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
4719   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
4720   const CXXRecordDecl *FinalType;
4721   if (NewEntriesSize == D.MostDerivedPathLength)
4722     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
4723   else
4724     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
4725   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
4726     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
4727       << D.MostDerivedType << TargetQT;
4728     return false;
4729   }
4730 
4731   // Truncate the lvalue to the appropriate derived class.
4732   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4733 }
4734 
4735 /// Get the value to use for a default-initialized object of type T.
4736 /// Return false if it encounters something invalid.
4737 static bool getDefaultInitValue(QualType T, APValue &Result) {
4738   bool Success = true;
4739   if (auto *RD = T->getAsCXXRecordDecl()) {
4740     if (RD->isInvalidDecl()) {
4741       Result = APValue();
4742       return false;
4743     }
4744     if (RD->isUnion()) {
4745       Result = APValue((const FieldDecl *)nullptr);
4746       return true;
4747     }
4748     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4749                      std::distance(RD->field_begin(), RD->field_end()));
4750 
4751     unsigned Index = 0;
4752     for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4753                                                   End = RD->bases_end();
4754          I != End; ++I, ++Index)
4755       Success &= getDefaultInitValue(I->getType(), Result.getStructBase(Index));
4756 
4757     for (const auto *I : RD->fields()) {
4758       if (I->isUnnamedBitfield())
4759         continue;
4760       Success &= getDefaultInitValue(I->getType(),
4761                                      Result.getStructField(I->getFieldIndex()));
4762     }
4763     return Success;
4764   }
4765 
4766   if (auto *AT =
4767           dyn_cast_or_null<ConstantArrayType>(T->getAsArrayTypeUnsafe())) {
4768     Result = APValue(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4769     if (Result.hasArrayFiller())
4770       Success &=
4771           getDefaultInitValue(AT->getElementType(), Result.getArrayFiller());
4772 
4773     return Success;
4774   }
4775 
4776   Result = APValue::IndeterminateValue();
4777   return true;
4778 }
4779 
4780 namespace {
4781 enum EvalStmtResult {
4782   /// Evaluation failed.
4783   ESR_Failed,
4784   /// Hit a 'return' statement.
4785   ESR_Returned,
4786   /// Evaluation succeeded.
4787   ESR_Succeeded,
4788   /// Hit a 'continue' statement.
4789   ESR_Continue,
4790   /// Hit a 'break' statement.
4791   ESR_Break,
4792   /// Still scanning for 'case' or 'default' statement.
4793   ESR_CaseNotFound
4794 };
4795 }
4796 
4797 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4798   // We don't need to evaluate the initializer for a static local.
4799   if (!VD->hasLocalStorage())
4800     return true;
4801 
4802   LValue Result;
4803   APValue &Val = Info.CurrentCall->createTemporary(VD, VD->getType(),
4804                                                    ScopeKind::Block, Result);
4805 
4806   const Expr *InitE = VD->getInit();
4807   if (!InitE) {
4808     if (VD->getType()->isDependentType())
4809       return Info.noteSideEffect();
4810     return getDefaultInitValue(VD->getType(), Val);
4811   }
4812   if (InitE->isValueDependent())
4813     return false;
4814 
4815   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4816     // Wipe out any partially-computed value, to allow tracking that this
4817     // evaluation failed.
4818     Val = APValue();
4819     return false;
4820   }
4821 
4822   return true;
4823 }
4824 
4825 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4826   bool OK = true;
4827 
4828   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4829     OK &= EvaluateVarDecl(Info, VD);
4830 
4831   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4832     for (auto *BD : DD->bindings())
4833       if (auto *VD = BD->getHoldingVar())
4834         OK &= EvaluateDecl(Info, VD);
4835 
4836   return OK;
4837 }
4838 
4839 static bool EvaluateDependentExpr(const Expr *E, EvalInfo &Info) {
4840   assert(E->isValueDependent());
4841   if (Info.noteSideEffect())
4842     return true;
4843   assert(E->containsErrors() && "valid value-dependent expression should never "
4844                                 "reach invalid code path.");
4845   return false;
4846 }
4847 
4848 /// Evaluate a condition (either a variable declaration or an expression).
4849 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4850                          const Expr *Cond, bool &Result) {
4851   if (Cond->isValueDependent())
4852     return false;
4853   FullExpressionRAII Scope(Info);
4854   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4855     return false;
4856   if (!EvaluateAsBooleanCondition(Cond, Result, Info))
4857     return false;
4858   return Scope.destroy();
4859 }
4860 
4861 namespace {
4862 /// A location where the result (returned value) of evaluating a
4863 /// statement should be stored.
4864 struct StmtResult {
4865   /// The APValue that should be filled in with the returned value.
4866   APValue &Value;
4867   /// The location containing the result, if any (used to support RVO).
4868   const LValue *Slot;
4869 };
4870 
4871 struct TempVersionRAII {
4872   CallStackFrame &Frame;
4873 
4874   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4875     Frame.pushTempVersion();
4876   }
4877 
4878   ~TempVersionRAII() {
4879     Frame.popTempVersion();
4880   }
4881 };
4882 
4883 }
4884 
4885 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4886                                    const Stmt *S,
4887                                    const SwitchCase *SC = nullptr);
4888 
4889 /// Evaluate the body of a loop, and translate the result as appropriate.
4890 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4891                                        const Stmt *Body,
4892                                        const SwitchCase *Case = nullptr) {
4893   BlockScopeRAII Scope(Info);
4894 
4895   EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case);
4896   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4897     ESR = ESR_Failed;
4898 
4899   switch (ESR) {
4900   case ESR_Break:
4901     return ESR_Succeeded;
4902   case ESR_Succeeded:
4903   case ESR_Continue:
4904     return ESR_Continue;
4905   case ESR_Failed:
4906   case ESR_Returned:
4907   case ESR_CaseNotFound:
4908     return ESR;
4909   }
4910   llvm_unreachable("Invalid EvalStmtResult!");
4911 }
4912 
4913 /// Evaluate a switch statement.
4914 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4915                                      const SwitchStmt *SS) {
4916   BlockScopeRAII Scope(Info);
4917 
4918   // Evaluate the switch condition.
4919   APSInt Value;
4920   {
4921     if (const Stmt *Init = SS->getInit()) {
4922       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4923       if (ESR != ESR_Succeeded) {
4924         if (ESR != ESR_Failed && !Scope.destroy())
4925           ESR = ESR_Failed;
4926         return ESR;
4927       }
4928     }
4929 
4930     FullExpressionRAII CondScope(Info);
4931     if (SS->getConditionVariable() &&
4932         !EvaluateDecl(Info, SS->getConditionVariable()))
4933       return ESR_Failed;
4934     if (!EvaluateInteger(SS->getCond(), Value, Info))
4935       return ESR_Failed;
4936     if (!CondScope.destroy())
4937       return ESR_Failed;
4938   }
4939 
4940   // Find the switch case corresponding to the value of the condition.
4941   // FIXME: Cache this lookup.
4942   const SwitchCase *Found = nullptr;
4943   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4944        SC = SC->getNextSwitchCase()) {
4945     if (isa<DefaultStmt>(SC)) {
4946       Found = SC;
4947       continue;
4948     }
4949 
4950     const CaseStmt *CS = cast<CaseStmt>(SC);
4951     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4952     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4953                               : LHS;
4954     if (LHS <= Value && Value <= RHS) {
4955       Found = SC;
4956       break;
4957     }
4958   }
4959 
4960   if (!Found)
4961     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
4962 
4963   // Search the switch body for the switch case and evaluate it from there.
4964   EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found);
4965   if (ESR != ESR_Failed && ESR != ESR_CaseNotFound && !Scope.destroy())
4966     return ESR_Failed;
4967 
4968   switch (ESR) {
4969   case ESR_Break:
4970     return ESR_Succeeded;
4971   case ESR_Succeeded:
4972   case ESR_Continue:
4973   case ESR_Failed:
4974   case ESR_Returned:
4975     return ESR;
4976   case ESR_CaseNotFound:
4977     // This can only happen if the switch case is nested within a statement
4978     // expression. We have no intention of supporting that.
4979     Info.FFDiag(Found->getBeginLoc(),
4980                 diag::note_constexpr_stmt_expr_unsupported);
4981     return ESR_Failed;
4982   }
4983   llvm_unreachable("Invalid EvalStmtResult!");
4984 }
4985 
4986 // Evaluate a statement.
4987 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4988                                    const Stmt *S, const SwitchCase *Case) {
4989   if (!Info.nextStep(S))
4990     return ESR_Failed;
4991 
4992   // If we're hunting down a 'case' or 'default' label, recurse through
4993   // substatements until we hit the label.
4994   if (Case) {
4995     switch (S->getStmtClass()) {
4996     case Stmt::CompoundStmtClass:
4997       // FIXME: Precompute which substatement of a compound statement we
4998       // would jump to, and go straight there rather than performing a
4999       // linear scan each time.
5000     case Stmt::LabelStmtClass:
5001     case Stmt::AttributedStmtClass:
5002     case Stmt::DoStmtClass:
5003       break;
5004 
5005     case Stmt::CaseStmtClass:
5006     case Stmt::DefaultStmtClass:
5007       if (Case == S)
5008         Case = nullptr;
5009       break;
5010 
5011     case Stmt::IfStmtClass: {
5012       // FIXME: Precompute which side of an 'if' we would jump to, and go
5013       // straight there rather than scanning both sides.
5014       const IfStmt *IS = cast<IfStmt>(S);
5015 
5016       // Wrap the evaluation in a block scope, in case it's a DeclStmt
5017       // preceded by our switch label.
5018       BlockScopeRAII Scope(Info);
5019 
5020       // Step into the init statement in case it brings an (uninitialized)
5021       // variable into scope.
5022       if (const Stmt *Init = IS->getInit()) {
5023         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5024         if (ESR != ESR_CaseNotFound) {
5025           assert(ESR != ESR_Succeeded);
5026           return ESR;
5027         }
5028       }
5029 
5030       // Condition variable must be initialized if it exists.
5031       // FIXME: We can skip evaluating the body if there's a condition
5032       // variable, as there can't be any case labels within it.
5033       // (The same is true for 'for' statements.)
5034 
5035       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
5036       if (ESR == ESR_Failed)
5037         return ESR;
5038       if (ESR != ESR_CaseNotFound)
5039         return Scope.destroy() ? ESR : ESR_Failed;
5040       if (!IS->getElse())
5041         return ESR_CaseNotFound;
5042 
5043       ESR = EvaluateStmt(Result, Info, IS->getElse(), Case);
5044       if (ESR == ESR_Failed)
5045         return ESR;
5046       if (ESR != ESR_CaseNotFound)
5047         return Scope.destroy() ? ESR : ESR_Failed;
5048       return ESR_CaseNotFound;
5049     }
5050 
5051     case Stmt::WhileStmtClass: {
5052       EvalStmtResult ESR =
5053           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
5054       if (ESR != ESR_Continue)
5055         return ESR;
5056       break;
5057     }
5058 
5059     case Stmt::ForStmtClass: {
5060       const ForStmt *FS = cast<ForStmt>(S);
5061       BlockScopeRAII Scope(Info);
5062 
5063       // Step into the init statement in case it brings an (uninitialized)
5064       // variable into scope.
5065       if (const Stmt *Init = FS->getInit()) {
5066         EvalStmtResult ESR = EvaluateStmt(Result, Info, Init, Case);
5067         if (ESR != ESR_CaseNotFound) {
5068           assert(ESR != ESR_Succeeded);
5069           return ESR;
5070         }
5071       }
5072 
5073       EvalStmtResult ESR =
5074           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
5075       if (ESR != ESR_Continue)
5076         return ESR;
5077       if (const auto *Inc = FS->getInc()) {
5078         if (Inc->isValueDependent()) {
5079           if (!EvaluateDependentExpr(Inc, Info))
5080             return ESR_Failed;
5081         } else {
5082           FullExpressionRAII IncScope(Info);
5083           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5084             return ESR_Failed;
5085         }
5086       }
5087       break;
5088     }
5089 
5090     case Stmt::DeclStmtClass: {
5091       // Start the lifetime of any uninitialized variables we encounter. They
5092       // might be used by the selected branch of the switch.
5093       const DeclStmt *DS = cast<DeclStmt>(S);
5094       for (const auto *D : DS->decls()) {
5095         if (const auto *VD = dyn_cast<VarDecl>(D)) {
5096           if (VD->hasLocalStorage() && !VD->getInit())
5097             if (!EvaluateVarDecl(Info, VD))
5098               return ESR_Failed;
5099           // FIXME: If the variable has initialization that can't be jumped
5100           // over, bail out of any immediately-surrounding compound-statement
5101           // too. There can't be any case labels here.
5102         }
5103       }
5104       return ESR_CaseNotFound;
5105     }
5106 
5107     default:
5108       return ESR_CaseNotFound;
5109     }
5110   }
5111 
5112   switch (S->getStmtClass()) {
5113   default:
5114     if (const Expr *E = dyn_cast<Expr>(S)) {
5115       if (E->isValueDependent()) {
5116         if (!EvaluateDependentExpr(E, Info))
5117           return ESR_Failed;
5118       } else {
5119         // Don't bother evaluating beyond an expression-statement which couldn't
5120         // be evaluated.
5121         // FIXME: Do we need the FullExpressionRAII object here?
5122         // VisitExprWithCleanups should create one when necessary.
5123         FullExpressionRAII Scope(Info);
5124         if (!EvaluateIgnoredValue(Info, E) || !Scope.destroy())
5125           return ESR_Failed;
5126       }
5127       return ESR_Succeeded;
5128     }
5129 
5130     Info.FFDiag(S->getBeginLoc());
5131     return ESR_Failed;
5132 
5133   case Stmt::NullStmtClass:
5134     return ESR_Succeeded;
5135 
5136   case Stmt::DeclStmtClass: {
5137     const DeclStmt *DS = cast<DeclStmt>(S);
5138     for (const auto *D : DS->decls()) {
5139       // Each declaration initialization is its own full-expression.
5140       FullExpressionRAII Scope(Info);
5141       if (!EvaluateDecl(Info, D) && !Info.noteFailure())
5142         return ESR_Failed;
5143       if (!Scope.destroy())
5144         return ESR_Failed;
5145     }
5146     return ESR_Succeeded;
5147   }
5148 
5149   case Stmt::ReturnStmtClass: {
5150     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
5151     FullExpressionRAII Scope(Info);
5152     if (RetExpr && RetExpr->isValueDependent()) {
5153       EvaluateDependentExpr(RetExpr, Info);
5154       // We know we returned, but we don't know what the value is.
5155       return ESR_Failed;
5156     }
5157     if (RetExpr &&
5158         !(Result.Slot
5159               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
5160               : Evaluate(Result.Value, Info, RetExpr)))
5161       return ESR_Failed;
5162     return Scope.destroy() ? ESR_Returned : ESR_Failed;
5163   }
5164 
5165   case Stmt::CompoundStmtClass: {
5166     BlockScopeRAII Scope(Info);
5167 
5168     const CompoundStmt *CS = cast<CompoundStmt>(S);
5169     for (const auto *BI : CS->body()) {
5170       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
5171       if (ESR == ESR_Succeeded)
5172         Case = nullptr;
5173       else if (ESR != ESR_CaseNotFound) {
5174         if (ESR != ESR_Failed && !Scope.destroy())
5175           return ESR_Failed;
5176         return ESR;
5177       }
5178     }
5179     if (Case)
5180       return ESR_CaseNotFound;
5181     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5182   }
5183 
5184   case Stmt::IfStmtClass: {
5185     const IfStmt *IS = cast<IfStmt>(S);
5186 
5187     // Evaluate the condition, as either a var decl or as an expression.
5188     BlockScopeRAII Scope(Info);
5189     if (const Stmt *Init = IS->getInit()) {
5190       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
5191       if (ESR != ESR_Succeeded) {
5192         if (ESR != ESR_Failed && !Scope.destroy())
5193           return ESR_Failed;
5194         return ESR;
5195       }
5196     }
5197     bool Cond;
5198     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
5199       return ESR_Failed;
5200 
5201     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
5202       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
5203       if (ESR != ESR_Succeeded) {
5204         if (ESR != ESR_Failed && !Scope.destroy())
5205           return ESR_Failed;
5206         return ESR;
5207       }
5208     }
5209     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5210   }
5211 
5212   case Stmt::WhileStmtClass: {
5213     const WhileStmt *WS = cast<WhileStmt>(S);
5214     while (true) {
5215       BlockScopeRAII Scope(Info);
5216       bool Continue;
5217       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
5218                         Continue))
5219         return ESR_Failed;
5220       if (!Continue)
5221         break;
5222 
5223       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
5224       if (ESR != ESR_Continue) {
5225         if (ESR != ESR_Failed && !Scope.destroy())
5226           return ESR_Failed;
5227         return ESR;
5228       }
5229       if (!Scope.destroy())
5230         return ESR_Failed;
5231     }
5232     return ESR_Succeeded;
5233   }
5234 
5235   case Stmt::DoStmtClass: {
5236     const DoStmt *DS = cast<DoStmt>(S);
5237     bool Continue;
5238     do {
5239       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
5240       if (ESR != ESR_Continue)
5241         return ESR;
5242       Case = nullptr;
5243 
5244       if (DS->getCond()->isValueDependent()) {
5245         EvaluateDependentExpr(DS->getCond(), Info);
5246         // Bailout as we don't know whether to keep going or terminate the loop.
5247         return ESR_Failed;
5248       }
5249       FullExpressionRAII CondScope(Info);
5250       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info) ||
5251           !CondScope.destroy())
5252         return ESR_Failed;
5253     } while (Continue);
5254     return ESR_Succeeded;
5255   }
5256 
5257   case Stmt::ForStmtClass: {
5258     const ForStmt *FS = cast<ForStmt>(S);
5259     BlockScopeRAII ForScope(Info);
5260     if (FS->getInit()) {
5261       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5262       if (ESR != ESR_Succeeded) {
5263         if (ESR != ESR_Failed && !ForScope.destroy())
5264           return ESR_Failed;
5265         return ESR;
5266       }
5267     }
5268     while (true) {
5269       BlockScopeRAII IterScope(Info);
5270       bool Continue = true;
5271       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
5272                                          FS->getCond(), Continue))
5273         return ESR_Failed;
5274       if (!Continue)
5275         break;
5276 
5277       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5278       if (ESR != ESR_Continue) {
5279         if (ESR != ESR_Failed && (!IterScope.destroy() || !ForScope.destroy()))
5280           return ESR_Failed;
5281         return ESR;
5282       }
5283 
5284       if (const auto *Inc = FS->getInc()) {
5285         if (Inc->isValueDependent()) {
5286           if (!EvaluateDependentExpr(Inc, Info))
5287             return ESR_Failed;
5288         } else {
5289           FullExpressionRAII IncScope(Info);
5290           if (!EvaluateIgnoredValue(Info, Inc) || !IncScope.destroy())
5291             return ESR_Failed;
5292         }
5293       }
5294 
5295       if (!IterScope.destroy())
5296         return ESR_Failed;
5297     }
5298     return ForScope.destroy() ? ESR_Succeeded : ESR_Failed;
5299   }
5300 
5301   case Stmt::CXXForRangeStmtClass: {
5302     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
5303     BlockScopeRAII Scope(Info);
5304 
5305     // Evaluate the init-statement if present.
5306     if (FS->getInit()) {
5307       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
5308       if (ESR != ESR_Succeeded) {
5309         if (ESR != ESR_Failed && !Scope.destroy())
5310           return ESR_Failed;
5311         return ESR;
5312       }
5313     }
5314 
5315     // Initialize the __range variable.
5316     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
5317     if (ESR != ESR_Succeeded) {
5318       if (ESR != ESR_Failed && !Scope.destroy())
5319         return ESR_Failed;
5320       return ESR;
5321     }
5322 
5323     // Create the __begin and __end iterators.
5324     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
5325     if (ESR != ESR_Succeeded) {
5326       if (ESR != ESR_Failed && !Scope.destroy())
5327         return ESR_Failed;
5328       return ESR;
5329     }
5330     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
5331     if (ESR != ESR_Succeeded) {
5332       if (ESR != ESR_Failed && !Scope.destroy())
5333         return ESR_Failed;
5334       return ESR;
5335     }
5336 
5337     while (true) {
5338       // Condition: __begin != __end.
5339       {
5340         if (FS->getCond()->isValueDependent()) {
5341           EvaluateDependentExpr(FS->getCond(), Info);
5342           // We don't know whether to keep going or terminate the loop.
5343           return ESR_Failed;
5344         }
5345         bool Continue = true;
5346         FullExpressionRAII CondExpr(Info);
5347         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
5348           return ESR_Failed;
5349         if (!Continue)
5350           break;
5351       }
5352 
5353       // User's variable declaration, initialized by *__begin.
5354       BlockScopeRAII InnerScope(Info);
5355       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
5356       if (ESR != ESR_Succeeded) {
5357         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5358           return ESR_Failed;
5359         return ESR;
5360       }
5361 
5362       // Loop body.
5363       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
5364       if (ESR != ESR_Continue) {
5365         if (ESR != ESR_Failed && (!InnerScope.destroy() || !Scope.destroy()))
5366           return ESR_Failed;
5367         return ESR;
5368       }
5369       if (FS->getInc()->isValueDependent()) {
5370         if (!EvaluateDependentExpr(FS->getInc(), Info))
5371           return ESR_Failed;
5372       } else {
5373         // Increment: ++__begin
5374         if (!EvaluateIgnoredValue(Info, FS->getInc()))
5375           return ESR_Failed;
5376       }
5377 
5378       if (!InnerScope.destroy())
5379         return ESR_Failed;
5380     }
5381 
5382     return Scope.destroy() ? ESR_Succeeded : ESR_Failed;
5383   }
5384 
5385   case Stmt::SwitchStmtClass:
5386     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
5387 
5388   case Stmt::ContinueStmtClass:
5389     return ESR_Continue;
5390 
5391   case Stmt::BreakStmtClass:
5392     return ESR_Break;
5393 
5394   case Stmt::LabelStmtClass:
5395     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
5396 
5397   case Stmt::AttributedStmtClass:
5398     // As a general principle, C++11 attributes can be ignored without
5399     // any semantic impact.
5400     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
5401                         Case);
5402 
5403   case Stmt::CaseStmtClass:
5404   case Stmt::DefaultStmtClass:
5405     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
5406   case Stmt::CXXTryStmtClass:
5407     // Evaluate try blocks by evaluating all sub statements.
5408     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
5409   }
5410 }
5411 
5412 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
5413 /// default constructor. If so, we'll fold it whether or not it's marked as
5414 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
5415 /// so we need special handling.
5416 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
5417                                            const CXXConstructorDecl *CD,
5418                                            bool IsValueInitialization) {
5419   if (!CD->isTrivial() || !CD->isDefaultConstructor())
5420     return false;
5421 
5422   // Value-initialization does not call a trivial default constructor, so such a
5423   // call is a core constant expression whether or not the constructor is
5424   // constexpr.
5425   if (!CD->isConstexpr() && !IsValueInitialization) {
5426     if (Info.getLangOpts().CPlusPlus11) {
5427       // FIXME: If DiagDecl is an implicitly-declared special member function,
5428       // we should be much more explicit about why it's not constexpr.
5429       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
5430         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
5431       Info.Note(CD->getLocation(), diag::note_declared_at);
5432     } else {
5433       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
5434     }
5435   }
5436   return true;
5437 }
5438 
5439 /// CheckConstexprFunction - Check that a function can be called in a constant
5440 /// expression.
5441 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
5442                                    const FunctionDecl *Declaration,
5443                                    const FunctionDecl *Definition,
5444                                    const Stmt *Body) {
5445   // Potential constant expressions can contain calls to declared, but not yet
5446   // defined, constexpr functions.
5447   if (Info.checkingPotentialConstantExpression() && !Definition &&
5448       Declaration->isConstexpr())
5449     return false;
5450 
5451   // Bail out if the function declaration itself is invalid.  We will
5452   // have produced a relevant diagnostic while parsing it, so just
5453   // note the problematic sub-expression.
5454   if (Declaration->isInvalidDecl()) {
5455     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5456     return false;
5457   }
5458 
5459   // DR1872: An instantiated virtual constexpr function can't be called in a
5460   // constant expression (prior to C++20). We can still constant-fold such a
5461   // call.
5462   if (!Info.Ctx.getLangOpts().CPlusPlus20 && isa<CXXMethodDecl>(Declaration) &&
5463       cast<CXXMethodDecl>(Declaration)->isVirtual())
5464     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
5465 
5466   if (Definition && Definition->isInvalidDecl()) {
5467     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5468     return false;
5469   }
5470 
5471   // Can we evaluate this function call?
5472   if (Definition && Definition->isConstexpr() && Body)
5473     return true;
5474 
5475   if (Info.getLangOpts().CPlusPlus11) {
5476     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
5477 
5478     // If this function is not constexpr because it is an inherited
5479     // non-constexpr constructor, diagnose that directly.
5480     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
5481     if (CD && CD->isInheritingConstructor()) {
5482       auto *Inherited = CD->getInheritedConstructor().getConstructor();
5483       if (!Inherited->isConstexpr())
5484         DiagDecl = CD = Inherited;
5485     }
5486 
5487     // FIXME: If DiagDecl is an implicitly-declared special member function
5488     // or an inheriting constructor, we should be much more explicit about why
5489     // it's not constexpr.
5490     if (CD && CD->isInheritingConstructor())
5491       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
5492         << CD->getInheritedConstructor().getConstructor()->getParent();
5493     else
5494       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
5495         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
5496     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
5497   } else {
5498     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
5499   }
5500   return false;
5501 }
5502 
5503 namespace {
5504 struct CheckDynamicTypeHandler {
5505   AccessKinds AccessKind;
5506   typedef bool result_type;
5507   bool failed() { return false; }
5508   bool found(APValue &Subobj, QualType SubobjType) { return true; }
5509   bool found(APSInt &Value, QualType SubobjType) { return true; }
5510   bool found(APFloat &Value, QualType SubobjType) { return true; }
5511 };
5512 } // end anonymous namespace
5513 
5514 /// Check that we can access the notional vptr of an object / determine its
5515 /// dynamic type.
5516 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
5517                              AccessKinds AK, bool Polymorphic) {
5518   if (This.Designator.Invalid)
5519     return false;
5520 
5521   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
5522 
5523   if (!Obj)
5524     return false;
5525 
5526   if (!Obj.Value) {
5527     // The object is not usable in constant expressions, so we can't inspect
5528     // its value to see if it's in-lifetime or what the active union members
5529     // are. We can still check for a one-past-the-end lvalue.
5530     if (This.Designator.isOnePastTheEnd() ||
5531         This.Designator.isMostDerivedAnUnsizedArray()) {
5532       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
5533                          ? diag::note_constexpr_access_past_end
5534                          : diag::note_constexpr_access_unsized_array)
5535           << AK;
5536       return false;
5537     } else if (Polymorphic) {
5538       // Conservatively refuse to perform a polymorphic operation if we would
5539       // not be able to read a notional 'vptr' value.
5540       APValue Val;
5541       This.moveInto(Val);
5542       QualType StarThisType =
5543           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
5544       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
5545           << AK << Val.getAsString(Info.Ctx, StarThisType);
5546       return false;
5547     }
5548     return true;
5549   }
5550 
5551   CheckDynamicTypeHandler Handler{AK};
5552   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
5553 }
5554 
5555 /// Check that the pointee of the 'this' pointer in a member function call is
5556 /// either within its lifetime or in its period of construction or destruction.
5557 static bool
5558 checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
5559                                      const LValue &This,
5560                                      const CXXMethodDecl *NamedMember) {
5561   return checkDynamicType(
5562       Info, E, This,
5563       isa<CXXDestructorDecl>(NamedMember) ? AK_Destroy : AK_MemberCall, false);
5564 }
5565 
5566 struct DynamicType {
5567   /// The dynamic class type of the object.
5568   const CXXRecordDecl *Type;
5569   /// The corresponding path length in the lvalue.
5570   unsigned PathLength;
5571 };
5572 
5573 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
5574                                              unsigned PathLength) {
5575   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
5576       Designator.Entries.size() && "invalid path length");
5577   return (PathLength == Designator.MostDerivedPathLength)
5578              ? Designator.MostDerivedType->getAsCXXRecordDecl()
5579              : getAsBaseClass(Designator.Entries[PathLength - 1]);
5580 }
5581 
5582 /// Determine the dynamic type of an object.
5583 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
5584                                                 LValue &This, AccessKinds AK) {
5585   // If we don't have an lvalue denoting an object of class type, there is no
5586   // meaningful dynamic type. (We consider objects of non-class type to have no
5587   // dynamic type.)
5588   if (!checkDynamicType(Info, E, This, AK, true))
5589     return None;
5590 
5591   // Refuse to compute a dynamic type in the presence of virtual bases. This
5592   // shouldn't happen other than in constant-folding situations, since literal
5593   // types can't have virtual bases.
5594   //
5595   // Note that consumers of DynamicType assume that the type has no virtual
5596   // bases, and will need modifications if this restriction is relaxed.
5597   const CXXRecordDecl *Class =
5598       This.Designator.MostDerivedType->getAsCXXRecordDecl();
5599   if (!Class || Class->getNumVBases()) {
5600     Info.FFDiag(E);
5601     return None;
5602   }
5603 
5604   // FIXME: For very deep class hierarchies, it might be beneficial to use a
5605   // binary search here instead. But the overwhelmingly common case is that
5606   // we're not in the middle of a constructor, so it probably doesn't matter
5607   // in practice.
5608   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
5609   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
5610        PathLength <= Path.size(); ++PathLength) {
5611     switch (Info.isEvaluatingCtorDtor(This.getLValueBase(),
5612                                       Path.slice(0, PathLength))) {
5613     case ConstructionPhase::Bases:
5614     case ConstructionPhase::DestroyingBases:
5615       // We're constructing or destroying a base class. This is not the dynamic
5616       // type.
5617       break;
5618 
5619     case ConstructionPhase::None:
5620     case ConstructionPhase::AfterBases:
5621     case ConstructionPhase::AfterFields:
5622     case ConstructionPhase::Destroying:
5623       // We've finished constructing the base classes and not yet started
5624       // destroying them again, so this is the dynamic type.
5625       return DynamicType{getBaseClassType(This.Designator, PathLength),
5626                          PathLength};
5627     }
5628   }
5629 
5630   // CWG issue 1517: we're constructing a base class of the object described by
5631   // 'This', so that object has not yet begun its period of construction and
5632   // any polymorphic operation on it results in undefined behavior.
5633   Info.FFDiag(E);
5634   return None;
5635 }
5636 
5637 /// Perform virtual dispatch.
5638 static const CXXMethodDecl *HandleVirtualDispatch(
5639     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
5640     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
5641   Optional<DynamicType> DynType = ComputeDynamicType(
5642       Info, E, This,
5643       isa<CXXDestructorDecl>(Found) ? AK_Destroy : AK_MemberCall);
5644   if (!DynType)
5645     return nullptr;
5646 
5647   // Find the final overrider. It must be declared in one of the classes on the
5648   // path from the dynamic type to the static type.
5649   // FIXME: If we ever allow literal types to have virtual base classes, that
5650   // won't be true.
5651   const CXXMethodDecl *Callee = Found;
5652   unsigned PathLength = DynType->PathLength;
5653   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
5654     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
5655     const CXXMethodDecl *Overrider =
5656         Found->getCorrespondingMethodDeclaredInClass(Class, false);
5657     if (Overrider) {
5658       Callee = Overrider;
5659       break;
5660     }
5661   }
5662 
5663   // C++2a [class.abstract]p6:
5664   //   the effect of making a virtual call to a pure virtual function [...] is
5665   //   undefined
5666   if (Callee->isPure()) {
5667     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
5668     Info.Note(Callee->getLocation(), diag::note_declared_at);
5669     return nullptr;
5670   }
5671 
5672   // If necessary, walk the rest of the path to determine the sequence of
5673   // covariant adjustment steps to apply.
5674   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
5675                                        Found->getReturnType())) {
5676     CovariantAdjustmentPath.push_back(Callee->getReturnType());
5677     for (unsigned CovariantPathLength = PathLength + 1;
5678          CovariantPathLength != This.Designator.Entries.size();
5679          ++CovariantPathLength) {
5680       const CXXRecordDecl *NextClass =
5681           getBaseClassType(This.Designator, CovariantPathLength);
5682       const CXXMethodDecl *Next =
5683           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
5684       if (Next && !Info.Ctx.hasSameUnqualifiedType(
5685                       Next->getReturnType(), CovariantAdjustmentPath.back()))
5686         CovariantAdjustmentPath.push_back(Next->getReturnType());
5687     }
5688     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
5689                                          CovariantAdjustmentPath.back()))
5690       CovariantAdjustmentPath.push_back(Found->getReturnType());
5691   }
5692 
5693   // Perform 'this' adjustment.
5694   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
5695     return nullptr;
5696 
5697   return Callee;
5698 }
5699 
5700 /// Perform the adjustment from a value returned by a virtual function to
5701 /// a value of the statically expected type, which may be a pointer or
5702 /// reference to a base class of the returned type.
5703 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
5704                                             APValue &Result,
5705                                             ArrayRef<QualType> Path) {
5706   assert(Result.isLValue() &&
5707          "unexpected kind of APValue for covariant return");
5708   if (Result.isNullPointer())
5709     return true;
5710 
5711   LValue LVal;
5712   LVal.setFrom(Info.Ctx, Result);
5713 
5714   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
5715   for (unsigned I = 1; I != Path.size(); ++I) {
5716     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
5717     assert(OldClass && NewClass && "unexpected kind of covariant return");
5718     if (OldClass != NewClass &&
5719         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
5720       return false;
5721     OldClass = NewClass;
5722   }
5723 
5724   LVal.moveInto(Result);
5725   return true;
5726 }
5727 
5728 /// Determine whether \p Base, which is known to be a direct base class of
5729 /// \p Derived, is a public base class.
5730 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
5731                               const CXXRecordDecl *Base) {
5732   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
5733     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
5734     if (BaseClass && declaresSameEntity(BaseClass, Base))
5735       return BaseSpec.getAccessSpecifier() == AS_public;
5736   }
5737   llvm_unreachable("Base is not a direct base of Derived");
5738 }
5739 
5740 /// Apply the given dynamic cast operation on the provided lvalue.
5741 ///
5742 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
5743 /// to find a suitable target subobject.
5744 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
5745                               LValue &Ptr) {
5746   // We can't do anything with a non-symbolic pointer value.
5747   SubobjectDesignator &D = Ptr.Designator;
5748   if (D.Invalid)
5749     return false;
5750 
5751   // C++ [expr.dynamic.cast]p6:
5752   //   If v is a null pointer value, the result is a null pointer value.
5753   if (Ptr.isNullPointer() && !E->isGLValue())
5754     return true;
5755 
5756   // For all the other cases, we need the pointer to point to an object within
5757   // its lifetime / period of construction / destruction, and we need to know
5758   // its dynamic type.
5759   Optional<DynamicType> DynType =
5760       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
5761   if (!DynType)
5762     return false;
5763 
5764   // C++ [expr.dynamic.cast]p7:
5765   //   If T is "pointer to cv void", then the result is a pointer to the most
5766   //   derived object
5767   if (E->getType()->isVoidPointerType())
5768     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
5769 
5770   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
5771   assert(C && "dynamic_cast target is not void pointer nor class");
5772   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
5773 
5774   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
5775     // C++ [expr.dynamic.cast]p9:
5776     if (!E->isGLValue()) {
5777       //   The value of a failed cast to pointer type is the null pointer value
5778       //   of the required result type.
5779       Ptr.setNull(Info.Ctx, E->getType());
5780       return true;
5781     }
5782 
5783     //   A failed cast to reference type throws [...] std::bad_cast.
5784     unsigned DiagKind;
5785     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
5786                    DynType->Type->isDerivedFrom(C)))
5787       DiagKind = 0;
5788     else if (!Paths || Paths->begin() == Paths->end())
5789       DiagKind = 1;
5790     else if (Paths->isAmbiguous(CQT))
5791       DiagKind = 2;
5792     else {
5793       assert(Paths->front().Access != AS_public && "why did the cast fail?");
5794       DiagKind = 3;
5795     }
5796     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
5797         << DiagKind << Ptr.Designator.getType(Info.Ctx)
5798         << Info.Ctx.getRecordType(DynType->Type)
5799         << E->getType().getUnqualifiedType();
5800     return false;
5801   };
5802 
5803   // Runtime check, phase 1:
5804   //   Walk from the base subobject towards the derived object looking for the
5805   //   target type.
5806   for (int PathLength = Ptr.Designator.Entries.size();
5807        PathLength >= (int)DynType->PathLength; --PathLength) {
5808     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
5809     if (declaresSameEntity(Class, C))
5810       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
5811     // We can only walk across public inheritance edges.
5812     if (PathLength > (int)DynType->PathLength &&
5813         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
5814                            Class))
5815       return RuntimeCheckFailed(nullptr);
5816   }
5817 
5818   // Runtime check, phase 2:
5819   //   Search the dynamic type for an unambiguous public base of type C.
5820   CXXBasePaths Paths(/*FindAmbiguities=*/true,
5821                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
5822   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
5823       Paths.front().Access == AS_public) {
5824     // Downcast to the dynamic type...
5825     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
5826       return false;
5827     // ... then upcast to the chosen base class subobject.
5828     for (CXXBasePathElement &Elem : Paths.front())
5829       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
5830         return false;
5831     return true;
5832   }
5833 
5834   // Otherwise, the runtime check fails.
5835   return RuntimeCheckFailed(&Paths);
5836 }
5837 
5838 namespace {
5839 struct StartLifetimeOfUnionMemberHandler {
5840   EvalInfo &Info;
5841   const Expr *LHSExpr;
5842   const FieldDecl *Field;
5843   bool DuringInit;
5844   bool Failed = false;
5845   static const AccessKinds AccessKind = AK_Assign;
5846 
5847   typedef bool result_type;
5848   bool failed() { return Failed; }
5849   bool found(APValue &Subobj, QualType SubobjType) {
5850     // We are supposed to perform no initialization but begin the lifetime of
5851     // the object. We interpret that as meaning to do what default
5852     // initialization of the object would do if all constructors involved were
5853     // trivial:
5854     //  * All base, non-variant member, and array element subobjects' lifetimes
5855     //    begin
5856     //  * No variant members' lifetimes begin
5857     //  * All scalar subobjects whose lifetimes begin have indeterminate values
5858     assert(SubobjType->isUnionType());
5859     if (declaresSameEntity(Subobj.getUnionField(), Field)) {
5860       // This union member is already active. If it's also in-lifetime, there's
5861       // nothing to do.
5862       if (Subobj.getUnionValue().hasValue())
5863         return true;
5864     } else if (DuringInit) {
5865       // We're currently in the process of initializing a different union
5866       // member.  If we carried on, that initialization would attempt to
5867       // store to an inactive union member, resulting in undefined behavior.
5868       Info.FFDiag(LHSExpr,
5869                   diag::note_constexpr_union_member_change_during_init);
5870       return false;
5871     }
5872     APValue Result;
5873     Failed = !getDefaultInitValue(Field->getType(), Result);
5874     Subobj.setUnion(Field, Result);
5875     return true;
5876   }
5877   bool found(APSInt &Value, QualType SubobjType) {
5878     llvm_unreachable("wrong value kind for union object");
5879   }
5880   bool found(APFloat &Value, QualType SubobjType) {
5881     llvm_unreachable("wrong value kind for union object");
5882   }
5883 };
5884 } // end anonymous namespace
5885 
5886 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
5887 
5888 /// Handle a builtin simple-assignment or a call to a trivial assignment
5889 /// operator whose left-hand side might involve a union member access. If it
5890 /// does, implicitly start the lifetime of any accessed union elements per
5891 /// C++20 [class.union]5.
5892 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
5893                                           const LValue &LHS) {
5894   if (LHS.InvalidBase || LHS.Designator.Invalid)
5895     return false;
5896 
5897   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
5898   // C++ [class.union]p5:
5899   //   define the set S(E) of subexpressions of E as follows:
5900   unsigned PathLength = LHS.Designator.Entries.size();
5901   for (const Expr *E = LHSExpr; E != nullptr;) {
5902     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
5903     if (auto *ME = dyn_cast<MemberExpr>(E)) {
5904       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
5905       // Note that we can't implicitly start the lifetime of a reference,
5906       // so we don't need to proceed any further if we reach one.
5907       if (!FD || FD->getType()->isReferenceType())
5908         break;
5909 
5910       //    ... and also contains A.B if B names a union member ...
5911       if (FD->getParent()->isUnion()) {
5912         //    ... of a non-class, non-array type, or of a class type with a
5913         //    trivial default constructor that is not deleted, or an array of
5914         //    such types.
5915         auto *RD =
5916             FD->getType()->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
5917         if (!RD || RD->hasTrivialDefaultConstructor())
5918           UnionPathLengths.push_back({PathLength - 1, FD});
5919       }
5920 
5921       E = ME->getBase();
5922       --PathLength;
5923       assert(declaresSameEntity(FD,
5924                                 LHS.Designator.Entries[PathLength]
5925                                     .getAsBaseOrMember().getPointer()));
5926 
5927       //   -- If E is of the form A[B] and is interpreted as a built-in array
5928       //      subscripting operator, S(E) is [S(the array operand, if any)].
5929     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5930       // Step over an ArrayToPointerDecay implicit cast.
5931       auto *Base = ASE->getBase()->IgnoreImplicit();
5932       if (!Base->getType()->isArrayType())
5933         break;
5934 
5935       E = Base;
5936       --PathLength;
5937 
5938     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5939       // Step over a derived-to-base conversion.
5940       E = ICE->getSubExpr();
5941       if (ICE->getCastKind() == CK_NoOp)
5942         continue;
5943       if (ICE->getCastKind() != CK_DerivedToBase &&
5944           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5945         break;
5946       // Walk path backwards as we walk up from the base to the derived class.
5947       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5948         --PathLength;
5949         (void)Elt;
5950         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5951                                   LHS.Designator.Entries[PathLength]
5952                                       .getAsBaseOrMember().getPointer()));
5953       }
5954 
5955     //   -- Otherwise, S(E) is empty.
5956     } else {
5957       break;
5958     }
5959   }
5960 
5961   // Common case: no unions' lifetimes are started.
5962   if (UnionPathLengths.empty())
5963     return true;
5964 
5965   //   if modification of X [would access an inactive union member], an object
5966   //   of the type of X is implicitly created
5967   CompleteObject Obj =
5968       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5969   if (!Obj)
5970     return false;
5971   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5972            llvm::reverse(UnionPathLengths)) {
5973     // Form a designator for the union object.
5974     SubobjectDesignator D = LHS.Designator;
5975     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5976 
5977     bool DuringInit = Info.isEvaluatingCtorDtor(LHS.Base, D.Entries) ==
5978                       ConstructionPhase::AfterBases;
5979     StartLifetimeOfUnionMemberHandler StartLifetime{
5980         Info, LHSExpr, LengthAndField.second, DuringInit};
5981     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5982       return false;
5983   }
5984 
5985   return true;
5986 }
5987 
5988 static bool EvaluateCallArg(const ParmVarDecl *PVD, const Expr *Arg,
5989                             CallRef Call, EvalInfo &Info,
5990                             bool NonNull = false) {
5991   LValue LV;
5992   // Create the parameter slot and register its destruction. For a vararg
5993   // argument, create a temporary.
5994   // FIXME: For calling conventions that destroy parameters in the callee,
5995   // should we consider performing destruction when the function returns
5996   // instead?
5997   APValue &V = PVD ? Info.CurrentCall->createParam(Call, PVD, LV)
5998                    : Info.CurrentCall->createTemporary(Arg, Arg->getType(),
5999                                                        ScopeKind::Call, LV);
6000   if (!EvaluateInPlace(V, Info, LV, Arg))
6001     return false;
6002 
6003   // Passing a null pointer to an __attribute__((nonnull)) parameter results in
6004   // undefined behavior, so is non-constant.
6005   if (NonNull && V.isLValue() && V.isNullPointer()) {
6006     Info.CCEDiag(Arg, diag::note_non_null_attribute_failed);
6007     return false;
6008   }
6009 
6010   return true;
6011 }
6012 
6013 /// Evaluate the arguments to a function call.
6014 static bool EvaluateArgs(ArrayRef<const Expr *> Args, CallRef Call,
6015                          EvalInfo &Info, const FunctionDecl *Callee,
6016                          bool RightToLeft = false) {
6017   bool Success = true;
6018   llvm::SmallBitVector ForbiddenNullArgs;
6019   if (Callee->hasAttr<NonNullAttr>()) {
6020     ForbiddenNullArgs.resize(Args.size());
6021     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
6022       if (!Attr->args_size()) {
6023         ForbiddenNullArgs.set();
6024         break;
6025       } else
6026         for (auto Idx : Attr->args()) {
6027           unsigned ASTIdx = Idx.getASTIndex();
6028           if (ASTIdx >= Args.size())
6029             continue;
6030           ForbiddenNullArgs[ASTIdx] = 1;
6031         }
6032     }
6033   }
6034   for (unsigned I = 0; I < Args.size(); I++) {
6035     unsigned Idx = RightToLeft ? Args.size() - I - 1 : I;
6036     const ParmVarDecl *PVD =
6037         Idx < Callee->getNumParams() ? Callee->getParamDecl(Idx) : nullptr;
6038     bool NonNull = !ForbiddenNullArgs.empty() && ForbiddenNullArgs[Idx];
6039     if (!EvaluateCallArg(PVD, Args[Idx], Call, Info, NonNull)) {
6040       // If we're checking for a potential constant expression, evaluate all
6041       // initializers even if some of them fail.
6042       if (!Info.noteFailure())
6043         return false;
6044       Success = false;
6045     }
6046   }
6047   return Success;
6048 }
6049 
6050 /// Perform a trivial copy from Param, which is the parameter of a copy or move
6051 /// constructor or assignment operator.
6052 static bool handleTrivialCopy(EvalInfo &Info, const ParmVarDecl *Param,
6053                               const Expr *E, APValue &Result,
6054                               bool CopyObjectRepresentation) {
6055   // Find the reference argument.
6056   CallStackFrame *Frame = Info.CurrentCall;
6057   APValue *RefValue = Info.getParamSlot(Frame->Arguments, Param);
6058   if (!RefValue) {
6059     Info.FFDiag(E);
6060     return false;
6061   }
6062 
6063   // Copy out the contents of the RHS object.
6064   LValue RefLValue;
6065   RefLValue.setFrom(Info.Ctx, *RefValue);
6066   return handleLValueToRValueConversion(
6067       Info, E, Param->getType().getNonReferenceType(), RefLValue, Result,
6068       CopyObjectRepresentation);
6069 }
6070 
6071 /// Evaluate a function call.
6072 static bool HandleFunctionCall(SourceLocation CallLoc,
6073                                const FunctionDecl *Callee, const LValue *This,
6074                                ArrayRef<const Expr *> Args, CallRef Call,
6075                                const Stmt *Body, EvalInfo &Info,
6076                                APValue &Result, const LValue *ResultSlot) {
6077   if (!Info.CheckCallLimit(CallLoc))
6078     return false;
6079 
6080   CallStackFrame Frame(Info, CallLoc, Callee, This, Call);
6081 
6082   // For a trivial copy or move assignment, perform an APValue copy. This is
6083   // essential for unions, where the operations performed by the assignment
6084   // operator cannot be represented as statements.
6085   //
6086   // Skip this for non-union classes with no fields; in that case, the defaulted
6087   // copy/move does not actually read the object.
6088   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
6089   if (MD && MD->isDefaulted() &&
6090       (MD->getParent()->isUnion() ||
6091        (MD->isTrivial() &&
6092         isReadByLvalueToRvalueConversion(MD->getParent())))) {
6093     assert(This &&
6094            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
6095     APValue RHSValue;
6096     if (!handleTrivialCopy(Info, MD->getParamDecl(0), Args[0], RHSValue,
6097                            MD->getParent()->isUnion()))
6098       return false;
6099     if (Info.getLangOpts().CPlusPlus20 && MD->isTrivial() &&
6100         !HandleUnionActiveMemberChange(Info, Args[0], *This))
6101       return false;
6102     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
6103                           RHSValue))
6104       return false;
6105     This->moveInto(Result);
6106     return true;
6107   } else if (MD && isLambdaCallOperator(MD)) {
6108     // We're in a lambda; determine the lambda capture field maps unless we're
6109     // just constexpr checking a lambda's call operator. constexpr checking is
6110     // done before the captures have been added to the closure object (unless
6111     // we're inferring constexpr-ness), so we don't have access to them in this
6112     // case. But since we don't need the captures to constexpr check, we can
6113     // just ignore them.
6114     if (!Info.checkingPotentialConstantExpression())
6115       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
6116                                         Frame.LambdaThisCaptureField);
6117   }
6118 
6119   StmtResult Ret = {Result, ResultSlot};
6120   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
6121   if (ESR == ESR_Succeeded) {
6122     if (Callee->getReturnType()->isVoidType())
6123       return true;
6124     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
6125   }
6126   return ESR == ESR_Returned;
6127 }
6128 
6129 /// Evaluate a constructor call.
6130 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6131                                   CallRef Call,
6132                                   const CXXConstructorDecl *Definition,
6133                                   EvalInfo &Info, APValue &Result) {
6134   SourceLocation CallLoc = E->getExprLoc();
6135   if (!Info.CheckCallLimit(CallLoc))
6136     return false;
6137 
6138   const CXXRecordDecl *RD = Definition->getParent();
6139   if (RD->getNumVBases()) {
6140     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6141     return false;
6142   }
6143 
6144   EvalInfo::EvaluatingConstructorRAII EvalObj(
6145       Info,
6146       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
6147       RD->getNumBases());
6148   CallStackFrame Frame(Info, CallLoc, Definition, &This, Call);
6149 
6150   // FIXME: Creating an APValue just to hold a nonexistent return value is
6151   // wasteful.
6152   APValue RetVal;
6153   StmtResult Ret = {RetVal, nullptr};
6154 
6155   // If it's a delegating constructor, delegate.
6156   if (Definition->isDelegatingConstructor()) {
6157     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
6158     if ((*I)->getInit()->isValueDependent()) {
6159       if (!EvaluateDependentExpr((*I)->getInit(), Info))
6160         return false;
6161     } else {
6162       FullExpressionRAII InitScope(Info);
6163       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()) ||
6164           !InitScope.destroy())
6165         return false;
6166     }
6167     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
6168   }
6169 
6170   // For a trivial copy or move constructor, perform an APValue copy. This is
6171   // essential for unions (or classes with anonymous union members), where the
6172   // operations performed by the constructor cannot be represented by
6173   // ctor-initializers.
6174   //
6175   // Skip this for empty non-union classes; we should not perform an
6176   // lvalue-to-rvalue conversion on them because their copy constructor does not
6177   // actually read them.
6178   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
6179       (Definition->getParent()->isUnion() ||
6180        (Definition->isTrivial() &&
6181         isReadByLvalueToRvalueConversion(Definition->getParent())))) {
6182     return handleTrivialCopy(Info, Definition->getParamDecl(0), E, Result,
6183                              Definition->getParent()->isUnion());
6184   }
6185 
6186   // Reserve space for the struct members.
6187   if (!Result.hasValue()) {
6188     if (!RD->isUnion())
6189       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
6190                        std::distance(RD->field_begin(), RD->field_end()));
6191     else
6192       // A union starts with no active member.
6193       Result = APValue((const FieldDecl*)nullptr);
6194   }
6195 
6196   if (RD->isInvalidDecl()) return false;
6197   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6198 
6199   // A scope for temporaries lifetime-extended by reference members.
6200   BlockScopeRAII LifetimeExtendedScope(Info);
6201 
6202   bool Success = true;
6203   unsigned BasesSeen = 0;
6204 #ifndef NDEBUG
6205   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
6206 #endif
6207   CXXRecordDecl::field_iterator FieldIt = RD->field_begin();
6208   auto SkipToField = [&](FieldDecl *FD, bool Indirect) {
6209     // We might be initializing the same field again if this is an indirect
6210     // field initialization.
6211     if (FieldIt == RD->field_end() ||
6212         FieldIt->getFieldIndex() > FD->getFieldIndex()) {
6213       assert(Indirect && "fields out of order?");
6214       return;
6215     }
6216 
6217     // Default-initialize any fields with no explicit initializer.
6218     for (; !declaresSameEntity(*FieldIt, FD); ++FieldIt) {
6219       assert(FieldIt != RD->field_end() && "missing field?");
6220       if (!FieldIt->isUnnamedBitfield())
6221         Success &= getDefaultInitValue(
6222             FieldIt->getType(),
6223             Result.getStructField(FieldIt->getFieldIndex()));
6224     }
6225     ++FieldIt;
6226   };
6227   for (const auto *I : Definition->inits()) {
6228     LValue Subobject = This;
6229     LValue SubobjectParent = This;
6230     APValue *Value = &Result;
6231 
6232     // Determine the subobject to initialize.
6233     FieldDecl *FD = nullptr;
6234     if (I->isBaseInitializer()) {
6235       QualType BaseType(I->getBaseClass(), 0);
6236 #ifndef NDEBUG
6237       // Non-virtual base classes are initialized in the order in the class
6238       // definition. We have already checked for virtual base classes.
6239       assert(!BaseIt->isVirtual() && "virtual base for literal type");
6240       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
6241              "base class initializers not in expected order");
6242       ++BaseIt;
6243 #endif
6244       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
6245                                   BaseType->getAsCXXRecordDecl(), &Layout))
6246         return false;
6247       Value = &Result.getStructBase(BasesSeen++);
6248     } else if ((FD = I->getMember())) {
6249       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
6250         return false;
6251       if (RD->isUnion()) {
6252         Result = APValue(FD);
6253         Value = &Result.getUnionValue();
6254       } else {
6255         SkipToField(FD, false);
6256         Value = &Result.getStructField(FD->getFieldIndex());
6257       }
6258     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
6259       // Walk the indirect field decl's chain to find the object to initialize,
6260       // and make sure we've initialized every step along it.
6261       auto IndirectFieldChain = IFD->chain();
6262       for (auto *C : IndirectFieldChain) {
6263         FD = cast<FieldDecl>(C);
6264         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
6265         // Switch the union field if it differs. This happens if we had
6266         // preceding zero-initialization, and we're now initializing a union
6267         // subobject other than the first.
6268         // FIXME: In this case, the values of the other subobjects are
6269         // specified, since zero-initialization sets all padding bits to zero.
6270         if (!Value->hasValue() ||
6271             (Value->isUnion() && Value->getUnionField() != FD)) {
6272           if (CD->isUnion())
6273             *Value = APValue(FD);
6274           else
6275             // FIXME: This immediately starts the lifetime of all members of
6276             // an anonymous struct. It would be preferable to strictly start
6277             // member lifetime in initialization order.
6278             Success &= getDefaultInitValue(Info.Ctx.getRecordType(CD), *Value);
6279         }
6280         // Store Subobject as its parent before updating it for the last element
6281         // in the chain.
6282         if (C == IndirectFieldChain.back())
6283           SubobjectParent = Subobject;
6284         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
6285           return false;
6286         if (CD->isUnion())
6287           Value = &Value->getUnionValue();
6288         else {
6289           if (C == IndirectFieldChain.front() && !RD->isUnion())
6290             SkipToField(FD, true);
6291           Value = &Value->getStructField(FD->getFieldIndex());
6292         }
6293       }
6294     } else {
6295       llvm_unreachable("unknown base initializer kind");
6296     }
6297 
6298     // Need to override This for implicit field initializers as in this case
6299     // This refers to innermost anonymous struct/union containing initializer,
6300     // not to currently constructed class.
6301     const Expr *Init = I->getInit();
6302     if (Init->isValueDependent()) {
6303       if (!EvaluateDependentExpr(Init, Info))
6304         return false;
6305     } else {
6306       ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
6307                                     isa<CXXDefaultInitExpr>(Init));
6308       FullExpressionRAII InitScope(Info);
6309       if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
6310           (FD && FD->isBitField() &&
6311            !truncateBitfieldValue(Info, Init, *Value, FD))) {
6312         // If we're checking for a potential constant expression, evaluate all
6313         // initializers even if some of them fail.
6314         if (!Info.noteFailure())
6315           return false;
6316         Success = false;
6317       }
6318     }
6319 
6320     // This is the point at which the dynamic type of the object becomes this
6321     // class type.
6322     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
6323       EvalObj.finishedConstructingBases();
6324   }
6325 
6326   // Default-initialize any remaining fields.
6327   if (!RD->isUnion()) {
6328     for (; FieldIt != RD->field_end(); ++FieldIt) {
6329       if (!FieldIt->isUnnamedBitfield())
6330         Success &= getDefaultInitValue(
6331             FieldIt->getType(),
6332             Result.getStructField(FieldIt->getFieldIndex()));
6333     }
6334   }
6335 
6336   EvalObj.finishedConstructingFields();
6337 
6338   return Success &&
6339          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed &&
6340          LifetimeExtendedScope.destroy();
6341 }
6342 
6343 static bool HandleConstructorCall(const Expr *E, const LValue &This,
6344                                   ArrayRef<const Expr*> Args,
6345                                   const CXXConstructorDecl *Definition,
6346                                   EvalInfo &Info, APValue &Result) {
6347   CallScopeRAII CallScope(Info);
6348   CallRef Call = Info.CurrentCall->createCall(Definition);
6349   if (!EvaluateArgs(Args, Call, Info, Definition))
6350     return false;
6351 
6352   return HandleConstructorCall(E, This, Call, Definition, Info, Result) &&
6353          CallScope.destroy();
6354 }
6355 
6356 static bool HandleDestructionImpl(EvalInfo &Info, SourceLocation CallLoc,
6357                                   const LValue &This, APValue &Value,
6358                                   QualType T) {
6359   // Objects can only be destroyed while they're within their lifetimes.
6360   // FIXME: We have no representation for whether an object of type nullptr_t
6361   // is in its lifetime; it usually doesn't matter. Perhaps we should model it
6362   // as indeterminate instead?
6363   if (Value.isAbsent() && !T->isNullPtrType()) {
6364     APValue Printable;
6365     This.moveInto(Printable);
6366     Info.FFDiag(CallLoc, diag::note_constexpr_destroy_out_of_lifetime)
6367       << Printable.getAsString(Info.Ctx, Info.Ctx.getLValueReferenceType(T));
6368     return false;
6369   }
6370 
6371   // Invent an expression for location purposes.
6372   // FIXME: We shouldn't need to do this.
6373   OpaqueValueExpr LocE(CallLoc, Info.Ctx.IntTy, VK_PRValue);
6374 
6375   // For arrays, destroy elements right-to-left.
6376   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(T)) {
6377     uint64_t Size = CAT->getSize().getZExtValue();
6378     QualType ElemT = CAT->getElementType();
6379 
6380     LValue ElemLV = This;
6381     ElemLV.addArray(Info, &LocE, CAT);
6382     if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, Size))
6383       return false;
6384 
6385     // Ensure that we have actual array elements available to destroy; the
6386     // destructors might mutate the value, so we can't run them on the array
6387     // filler.
6388     if (Size && Size > Value.getArrayInitializedElts())
6389       expandArray(Value, Value.getArraySize() - 1);
6390 
6391     for (; Size != 0; --Size) {
6392       APValue &Elem = Value.getArrayInitializedElt(Size - 1);
6393       if (!HandleLValueArrayAdjustment(Info, &LocE, ElemLV, ElemT, -1) ||
6394           !HandleDestructionImpl(Info, CallLoc, ElemLV, Elem, ElemT))
6395         return false;
6396     }
6397 
6398     // End the lifetime of this array now.
6399     Value = APValue();
6400     return true;
6401   }
6402 
6403   const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
6404   if (!RD) {
6405     if (T.isDestructedType()) {
6406       Info.FFDiag(CallLoc, diag::note_constexpr_unsupported_destruction) << T;
6407       return false;
6408     }
6409 
6410     Value = APValue();
6411     return true;
6412   }
6413 
6414   if (RD->getNumVBases()) {
6415     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
6416     return false;
6417   }
6418 
6419   const CXXDestructorDecl *DD = RD->getDestructor();
6420   if (!DD && !RD->hasTrivialDestructor()) {
6421     Info.FFDiag(CallLoc);
6422     return false;
6423   }
6424 
6425   if (!DD || DD->isTrivial() ||
6426       (RD->isAnonymousStructOrUnion() && RD->isUnion())) {
6427     // A trivial destructor just ends the lifetime of the object. Check for
6428     // this case before checking for a body, because we might not bother
6429     // building a body for a trivial destructor. Note that it doesn't matter
6430     // whether the destructor is constexpr in this case; all trivial
6431     // destructors are constexpr.
6432     //
6433     // If an anonymous union would be destroyed, some enclosing destructor must
6434     // have been explicitly defined, and the anonymous union destruction should
6435     // have no effect.
6436     Value = APValue();
6437     return true;
6438   }
6439 
6440   if (!Info.CheckCallLimit(CallLoc))
6441     return false;
6442 
6443   const FunctionDecl *Definition = nullptr;
6444   const Stmt *Body = DD->getBody(Definition);
6445 
6446   if (!CheckConstexprFunction(Info, CallLoc, DD, Definition, Body))
6447     return false;
6448 
6449   CallStackFrame Frame(Info, CallLoc, Definition, &This, CallRef());
6450 
6451   // We're now in the period of destruction of this object.
6452   unsigned BasesLeft = RD->getNumBases();
6453   EvalInfo::EvaluatingDestructorRAII EvalObj(
6454       Info,
6455       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries});
6456   if (!EvalObj.DidInsert) {
6457     // C++2a [class.dtor]p19:
6458     //   the behavior is undefined if the destructor is invoked for an object
6459     //   whose lifetime has ended
6460     // (Note that formally the lifetime ends when the period of destruction
6461     // begins, even though certain uses of the object remain valid until the
6462     // period of destruction ends.)
6463     Info.FFDiag(CallLoc, diag::note_constexpr_double_destroy);
6464     return false;
6465   }
6466 
6467   // FIXME: Creating an APValue just to hold a nonexistent return value is
6468   // wasteful.
6469   APValue RetVal;
6470   StmtResult Ret = {RetVal, nullptr};
6471   if (EvaluateStmt(Ret, Info, Definition->getBody()) == ESR_Failed)
6472     return false;
6473 
6474   // A union destructor does not implicitly destroy its members.
6475   if (RD->isUnion())
6476     return true;
6477 
6478   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6479 
6480   // We don't have a good way to iterate fields in reverse, so collect all the
6481   // fields first and then walk them backwards.
6482   SmallVector<FieldDecl*, 16> Fields(RD->field_begin(), RD->field_end());
6483   for (const FieldDecl *FD : llvm::reverse(Fields)) {
6484     if (FD->isUnnamedBitfield())
6485       continue;
6486 
6487     LValue Subobject = This;
6488     if (!HandleLValueMember(Info, &LocE, Subobject, FD, &Layout))
6489       return false;
6490 
6491     APValue *SubobjectValue = &Value.getStructField(FD->getFieldIndex());
6492     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6493                                FD->getType()))
6494       return false;
6495   }
6496 
6497   if (BasesLeft != 0)
6498     EvalObj.startedDestroyingBases();
6499 
6500   // Destroy base classes in reverse order.
6501   for (const CXXBaseSpecifier &Base : llvm::reverse(RD->bases())) {
6502     --BasesLeft;
6503 
6504     QualType BaseType = Base.getType();
6505     LValue Subobject = This;
6506     if (!HandleLValueDirectBase(Info, &LocE, Subobject, RD,
6507                                 BaseType->getAsCXXRecordDecl(), &Layout))
6508       return false;
6509 
6510     APValue *SubobjectValue = &Value.getStructBase(BasesLeft);
6511     if (!HandleDestructionImpl(Info, CallLoc, Subobject, *SubobjectValue,
6512                                BaseType))
6513       return false;
6514   }
6515   assert(BasesLeft == 0 && "NumBases was wrong?");
6516 
6517   // The period of destruction ends now. The object is gone.
6518   Value = APValue();
6519   return true;
6520 }
6521 
6522 namespace {
6523 struct DestroyObjectHandler {
6524   EvalInfo &Info;
6525   const Expr *E;
6526   const LValue &This;
6527   const AccessKinds AccessKind;
6528 
6529   typedef bool result_type;
6530   bool failed() { return false; }
6531   bool found(APValue &Subobj, QualType SubobjType) {
6532     return HandleDestructionImpl(Info, E->getExprLoc(), This, Subobj,
6533                                  SubobjType);
6534   }
6535   bool found(APSInt &Value, QualType SubobjType) {
6536     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6537     return false;
6538   }
6539   bool found(APFloat &Value, QualType SubobjType) {
6540     Info.FFDiag(E, diag::note_constexpr_destroy_complex_elem);
6541     return false;
6542   }
6543 };
6544 }
6545 
6546 /// Perform a destructor or pseudo-destructor call on the given object, which
6547 /// might in general not be a complete object.
6548 static bool HandleDestruction(EvalInfo &Info, const Expr *E,
6549                               const LValue &This, QualType ThisType) {
6550   CompleteObject Obj = findCompleteObject(Info, E, AK_Destroy, This, ThisType);
6551   DestroyObjectHandler Handler = {Info, E, This, AK_Destroy};
6552   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
6553 }
6554 
6555 /// Destroy and end the lifetime of the given complete object.
6556 static bool HandleDestruction(EvalInfo &Info, SourceLocation Loc,
6557                               APValue::LValueBase LVBase, APValue &Value,
6558                               QualType T) {
6559   // If we've had an unmodeled side-effect, we can't rely on mutable state
6560   // (such as the object we're about to destroy) being correct.
6561   if (Info.EvalStatus.HasSideEffects)
6562     return false;
6563 
6564   LValue LV;
6565   LV.set({LVBase});
6566   return HandleDestructionImpl(Info, Loc, LV, Value, T);
6567 }
6568 
6569 /// Perform a call to 'perator new' or to `__builtin_operator_new'.
6570 static bool HandleOperatorNewCall(EvalInfo &Info, const CallExpr *E,
6571                                   LValue &Result) {
6572   if (Info.checkingPotentialConstantExpression() ||
6573       Info.SpeculativeEvaluationDepth)
6574     return false;
6575 
6576   // This is permitted only within a call to std::allocator<T>::allocate.
6577   auto Caller = Info.getStdAllocatorCaller("allocate");
6578   if (!Caller) {
6579     Info.FFDiag(E->getExprLoc(), Info.getLangOpts().CPlusPlus20
6580                                      ? diag::note_constexpr_new_untyped
6581                                      : diag::note_constexpr_new);
6582     return false;
6583   }
6584 
6585   QualType ElemType = Caller.ElemType;
6586   if (ElemType->isIncompleteType() || ElemType->isFunctionType()) {
6587     Info.FFDiag(E->getExprLoc(),
6588                 diag::note_constexpr_new_not_complete_object_type)
6589         << (ElemType->isIncompleteType() ? 0 : 1) << ElemType;
6590     return false;
6591   }
6592 
6593   APSInt ByteSize;
6594   if (!EvaluateInteger(E->getArg(0), ByteSize, Info))
6595     return false;
6596   bool IsNothrow = false;
6597   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I) {
6598     EvaluateIgnoredValue(Info, E->getArg(I));
6599     IsNothrow |= E->getType()->isNothrowT();
6600   }
6601 
6602   CharUnits ElemSize;
6603   if (!HandleSizeof(Info, E->getExprLoc(), ElemType, ElemSize))
6604     return false;
6605   APInt Size, Remainder;
6606   APInt ElemSizeAP(ByteSize.getBitWidth(), ElemSize.getQuantity());
6607   APInt::udivrem(ByteSize, ElemSizeAP, Size, Remainder);
6608   if (Remainder != 0) {
6609     // This likely indicates a bug in the implementation of 'std::allocator'.
6610     Info.FFDiag(E->getExprLoc(), diag::note_constexpr_operator_new_bad_size)
6611         << ByteSize << APSInt(ElemSizeAP, true) << ElemType;
6612     return false;
6613   }
6614 
6615   if (ByteSize.getActiveBits() > ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
6616     if (IsNothrow) {
6617       Result.setNull(Info.Ctx, E->getType());
6618       return true;
6619     }
6620 
6621     Info.FFDiag(E, diag::note_constexpr_new_too_large) << APSInt(Size, true);
6622     return false;
6623   }
6624 
6625   QualType AllocType = Info.Ctx.getConstantArrayType(ElemType, Size, nullptr,
6626                                                      ArrayType::Normal, 0);
6627   APValue *Val = Info.createHeapAlloc(E, AllocType, Result);
6628   *Val = APValue(APValue::UninitArray(), 0, Size.getZExtValue());
6629   Result.addArray(Info, E, cast<ConstantArrayType>(AllocType));
6630   return true;
6631 }
6632 
6633 static bool hasVirtualDestructor(QualType T) {
6634   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6635     if (CXXDestructorDecl *DD = RD->getDestructor())
6636       return DD->isVirtual();
6637   return false;
6638 }
6639 
6640 static const FunctionDecl *getVirtualOperatorDelete(QualType T) {
6641   if (CXXRecordDecl *RD = T->getAsCXXRecordDecl())
6642     if (CXXDestructorDecl *DD = RD->getDestructor())
6643       return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
6644   return nullptr;
6645 }
6646 
6647 /// Check that the given object is a suitable pointer to a heap allocation that
6648 /// still exists and is of the right kind for the purpose of a deletion.
6649 ///
6650 /// On success, returns the heap allocation to deallocate. On failure, produces
6651 /// a diagnostic and returns None.
6652 static Optional<DynAlloc *> CheckDeleteKind(EvalInfo &Info, const Expr *E,
6653                                             const LValue &Pointer,
6654                                             DynAlloc::Kind DeallocKind) {
6655   auto PointerAsString = [&] {
6656     return Pointer.toString(Info.Ctx, Info.Ctx.VoidPtrTy);
6657   };
6658 
6659   DynamicAllocLValue DA = Pointer.Base.dyn_cast<DynamicAllocLValue>();
6660   if (!DA) {
6661     Info.FFDiag(E, diag::note_constexpr_delete_not_heap_alloc)
6662         << PointerAsString();
6663     if (Pointer.Base)
6664       NoteLValueLocation(Info, Pointer.Base);
6665     return None;
6666   }
6667 
6668   Optional<DynAlloc *> Alloc = Info.lookupDynamicAlloc(DA);
6669   if (!Alloc) {
6670     Info.FFDiag(E, diag::note_constexpr_double_delete);
6671     return None;
6672   }
6673 
6674   QualType AllocType = Pointer.Base.getDynamicAllocType();
6675   if (DeallocKind != (*Alloc)->getKind()) {
6676     Info.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
6677         << DeallocKind << (*Alloc)->getKind() << AllocType;
6678     NoteLValueLocation(Info, Pointer.Base);
6679     return None;
6680   }
6681 
6682   bool Subobject = false;
6683   if (DeallocKind == DynAlloc::New) {
6684     Subobject = Pointer.Designator.MostDerivedPathLength != 0 ||
6685                 Pointer.Designator.isOnePastTheEnd();
6686   } else {
6687     Subobject = Pointer.Designator.Entries.size() != 1 ||
6688                 Pointer.Designator.Entries[0].getAsArrayIndex() != 0;
6689   }
6690   if (Subobject) {
6691     Info.FFDiag(E, diag::note_constexpr_delete_subobject)
6692         << PointerAsString() << Pointer.Designator.isOnePastTheEnd();
6693     return None;
6694   }
6695 
6696   return Alloc;
6697 }
6698 
6699 // Perform a call to 'operator delete' or '__builtin_operator_delete'.
6700 bool HandleOperatorDeleteCall(EvalInfo &Info, const CallExpr *E) {
6701   if (Info.checkingPotentialConstantExpression() ||
6702       Info.SpeculativeEvaluationDepth)
6703     return false;
6704 
6705   // This is permitted only within a call to std::allocator<T>::deallocate.
6706   if (!Info.getStdAllocatorCaller("deallocate")) {
6707     Info.FFDiag(E->getExprLoc());
6708     return true;
6709   }
6710 
6711   LValue Pointer;
6712   if (!EvaluatePointer(E->getArg(0), Pointer, Info))
6713     return false;
6714   for (unsigned I = 1, N = E->getNumArgs(); I != N; ++I)
6715     EvaluateIgnoredValue(Info, E->getArg(I));
6716 
6717   if (Pointer.Designator.Invalid)
6718     return false;
6719 
6720   // Deleting a null pointer would have no effect, but it's not permitted by
6721   // std::allocator<T>::deallocate's contract.
6722   if (Pointer.isNullPointer()) {
6723     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_deallocate_null);
6724     return true;
6725   }
6726 
6727   if (!CheckDeleteKind(Info, E, Pointer, DynAlloc::StdAllocator))
6728     return false;
6729 
6730   Info.HeapAllocs.erase(Pointer.Base.get<DynamicAllocLValue>());
6731   return true;
6732 }
6733 
6734 //===----------------------------------------------------------------------===//
6735 // Generic Evaluation
6736 //===----------------------------------------------------------------------===//
6737 namespace {
6738 
6739 class BitCastBuffer {
6740   // FIXME: We're going to need bit-level granularity when we support
6741   // bit-fields.
6742   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
6743   // we don't support a host or target where that is the case. Still, we should
6744   // use a more generic type in case we ever do.
6745   SmallVector<Optional<unsigned char>, 32> Bytes;
6746 
6747   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
6748                 "Need at least 8 bit unsigned char");
6749 
6750   bool TargetIsLittleEndian;
6751 
6752 public:
6753   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
6754       : Bytes(Width.getQuantity()),
6755         TargetIsLittleEndian(TargetIsLittleEndian) {}
6756 
6757   LLVM_NODISCARD
6758   bool readObject(CharUnits Offset, CharUnits Width,
6759                   SmallVectorImpl<unsigned char> &Output) const {
6760     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
6761       // If a byte of an integer is uninitialized, then the whole integer is
6762       // uninitialized.
6763       if (!Bytes[I.getQuantity()])
6764         return false;
6765       Output.push_back(*Bytes[I.getQuantity()]);
6766     }
6767     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6768       std::reverse(Output.begin(), Output.end());
6769     return true;
6770   }
6771 
6772   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
6773     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
6774       std::reverse(Input.begin(), Input.end());
6775 
6776     size_t Index = 0;
6777     for (unsigned char Byte : Input) {
6778       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
6779       Bytes[Offset.getQuantity() + Index] = Byte;
6780       ++Index;
6781     }
6782   }
6783 
6784   size_t size() { return Bytes.size(); }
6785 };
6786 
6787 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
6788 /// target would represent the value at runtime.
6789 class APValueToBufferConverter {
6790   EvalInfo &Info;
6791   BitCastBuffer Buffer;
6792   const CastExpr *BCE;
6793 
6794   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
6795                            const CastExpr *BCE)
6796       : Info(Info),
6797         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
6798         BCE(BCE) {}
6799 
6800   bool visit(const APValue &Val, QualType Ty) {
6801     return visit(Val, Ty, CharUnits::fromQuantity(0));
6802   }
6803 
6804   // Write out Val with type Ty into Buffer starting at Offset.
6805   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
6806     assert((size_t)Offset.getQuantity() <= Buffer.size());
6807 
6808     // As a special case, nullptr_t has an indeterminate value.
6809     if (Ty->isNullPtrType())
6810       return true;
6811 
6812     // Dig through Src to find the byte at SrcOffset.
6813     switch (Val.getKind()) {
6814     case APValue::Indeterminate:
6815     case APValue::None:
6816       return true;
6817 
6818     case APValue::Int:
6819       return visitInt(Val.getInt(), Ty, Offset);
6820     case APValue::Float:
6821       return visitFloat(Val.getFloat(), Ty, Offset);
6822     case APValue::Array:
6823       return visitArray(Val, Ty, Offset);
6824     case APValue::Struct:
6825       return visitRecord(Val, Ty, Offset);
6826 
6827     case APValue::ComplexInt:
6828     case APValue::ComplexFloat:
6829     case APValue::Vector:
6830     case APValue::FixedPoint:
6831       // FIXME: We should support these.
6832 
6833     case APValue::Union:
6834     case APValue::MemberPointer:
6835     case APValue::AddrLabelDiff: {
6836       Info.FFDiag(BCE->getBeginLoc(),
6837                   diag::note_constexpr_bit_cast_unsupported_type)
6838           << Ty;
6839       return false;
6840     }
6841 
6842     case APValue::LValue:
6843       llvm_unreachable("LValue subobject in bit_cast?");
6844     }
6845     llvm_unreachable("Unhandled APValue::ValueKind");
6846   }
6847 
6848   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
6849     const RecordDecl *RD = Ty->getAsRecordDecl();
6850     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6851 
6852     // Visit the base classes.
6853     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
6854       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
6855         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
6856         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
6857 
6858         if (!visitRecord(Val.getStructBase(I), BS.getType(),
6859                          Layout.getBaseClassOffset(BaseDecl) + Offset))
6860           return false;
6861       }
6862     }
6863 
6864     // Visit the fields.
6865     unsigned FieldIdx = 0;
6866     for (FieldDecl *FD : RD->fields()) {
6867       if (FD->isBitField()) {
6868         Info.FFDiag(BCE->getBeginLoc(),
6869                     diag::note_constexpr_bit_cast_unsupported_bitfield);
6870         return false;
6871       }
6872 
6873       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
6874 
6875       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
6876              "only bit-fields can have sub-char alignment");
6877       CharUnits FieldOffset =
6878           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
6879       QualType FieldTy = FD->getType();
6880       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
6881         return false;
6882       ++FieldIdx;
6883     }
6884 
6885     return true;
6886   }
6887 
6888   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
6889     const auto *CAT =
6890         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
6891     if (!CAT)
6892       return false;
6893 
6894     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
6895     unsigned NumInitializedElts = Val.getArrayInitializedElts();
6896     unsigned ArraySize = Val.getArraySize();
6897     // First, initialize the initialized elements.
6898     for (unsigned I = 0; I != NumInitializedElts; ++I) {
6899       const APValue &SubObj = Val.getArrayInitializedElt(I);
6900       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
6901         return false;
6902     }
6903 
6904     // Next, initialize the rest of the array using the filler.
6905     if (Val.hasArrayFiller()) {
6906       const APValue &Filler = Val.getArrayFiller();
6907       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
6908         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
6909           return false;
6910       }
6911     }
6912 
6913     return true;
6914   }
6915 
6916   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
6917     APSInt AdjustedVal = Val;
6918     unsigned Width = AdjustedVal.getBitWidth();
6919     if (Ty->isBooleanType()) {
6920       Width = Info.Ctx.getTypeSize(Ty);
6921       AdjustedVal = AdjustedVal.extend(Width);
6922     }
6923 
6924     SmallVector<unsigned char, 8> Bytes(Width / 8);
6925     llvm::StoreIntToMemory(AdjustedVal, &*Bytes.begin(), Width / 8);
6926     Buffer.writeObject(Offset, Bytes);
6927     return true;
6928   }
6929 
6930   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
6931     APSInt AsInt(Val.bitcastToAPInt());
6932     return visitInt(AsInt, Ty, Offset);
6933   }
6934 
6935 public:
6936   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
6937                                          const CastExpr *BCE) {
6938     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
6939     APValueToBufferConverter Converter(Info, DstSize, BCE);
6940     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
6941       return None;
6942     return Converter.Buffer;
6943   }
6944 };
6945 
6946 /// Write an BitCastBuffer into an APValue.
6947 class BufferToAPValueConverter {
6948   EvalInfo &Info;
6949   const BitCastBuffer &Buffer;
6950   const CastExpr *BCE;
6951 
6952   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
6953                            const CastExpr *BCE)
6954       : Info(Info), Buffer(Buffer), BCE(BCE) {}
6955 
6956   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
6957   // with an invalid type, so anything left is a deficiency on our part (FIXME).
6958   // Ideally this will be unreachable.
6959   llvm::NoneType unsupportedType(QualType Ty) {
6960     Info.FFDiag(BCE->getBeginLoc(),
6961                 diag::note_constexpr_bit_cast_unsupported_type)
6962         << Ty;
6963     return None;
6964   }
6965 
6966   llvm::NoneType unrepresentableValue(QualType Ty, const APSInt &Val) {
6967     Info.FFDiag(BCE->getBeginLoc(),
6968                 diag::note_constexpr_bit_cast_unrepresentable_value)
6969         << Ty << toString(Val, /*Radix=*/10);
6970     return None;
6971   }
6972 
6973   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
6974                           const EnumType *EnumSugar = nullptr) {
6975     if (T->isNullPtrType()) {
6976       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
6977       return APValue((Expr *)nullptr,
6978                      /*Offset=*/CharUnits::fromQuantity(NullValue),
6979                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
6980     }
6981 
6982     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
6983 
6984     // Work around floating point types that contain unused padding bytes. This
6985     // is really just `long double` on x86, which is the only fundamental type
6986     // with padding bytes.
6987     if (T->isRealFloatingType()) {
6988       const llvm::fltSemantics &Semantics =
6989           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
6990       unsigned NumBits = llvm::APFloatBase::getSizeInBits(Semantics);
6991       assert(NumBits % 8 == 0);
6992       CharUnits NumBytes = CharUnits::fromQuantity(NumBits / 8);
6993       if (NumBytes != SizeOf)
6994         SizeOf = NumBytes;
6995     }
6996 
6997     SmallVector<uint8_t, 8> Bytes;
6998     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
6999       // If this is std::byte or unsigned char, then its okay to store an
7000       // indeterminate value.
7001       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
7002       bool IsUChar =
7003           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
7004                          T->isSpecificBuiltinType(BuiltinType::Char_U));
7005       if (!IsStdByte && !IsUChar) {
7006         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
7007         Info.FFDiag(BCE->getExprLoc(),
7008                     diag::note_constexpr_bit_cast_indet_dest)
7009             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
7010         return None;
7011       }
7012 
7013       return APValue::IndeterminateValue();
7014     }
7015 
7016     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
7017     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
7018 
7019     if (T->isIntegralOrEnumerationType()) {
7020       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
7021 
7022       unsigned IntWidth = Info.Ctx.getIntWidth(QualType(T, 0));
7023       if (IntWidth != Val.getBitWidth()) {
7024         APSInt Truncated = Val.trunc(IntWidth);
7025         if (Truncated.extend(Val.getBitWidth()) != Val)
7026           return unrepresentableValue(QualType(T, 0), Val);
7027         Val = Truncated;
7028       }
7029 
7030       return APValue(Val);
7031     }
7032 
7033     if (T->isRealFloatingType()) {
7034       const llvm::fltSemantics &Semantics =
7035           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
7036       return APValue(APFloat(Semantics, Val));
7037     }
7038 
7039     return unsupportedType(QualType(T, 0));
7040   }
7041 
7042   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
7043     const RecordDecl *RD = RTy->getAsRecordDecl();
7044     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7045 
7046     unsigned NumBases = 0;
7047     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
7048       NumBases = CXXRD->getNumBases();
7049 
7050     APValue ResultVal(APValue::UninitStruct(), NumBases,
7051                       std::distance(RD->field_begin(), RD->field_end()));
7052 
7053     // Visit the base classes.
7054     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
7055       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
7056         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
7057         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
7058         if (BaseDecl->isEmpty() ||
7059             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
7060           continue;
7061 
7062         Optional<APValue> SubObj = visitType(
7063             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
7064         if (!SubObj)
7065           return None;
7066         ResultVal.getStructBase(I) = *SubObj;
7067       }
7068     }
7069 
7070     // Visit the fields.
7071     unsigned FieldIdx = 0;
7072     for (FieldDecl *FD : RD->fields()) {
7073       // FIXME: We don't currently support bit-fields. A lot of the logic for
7074       // this is in CodeGen, so we need to factor it around.
7075       if (FD->isBitField()) {
7076         Info.FFDiag(BCE->getBeginLoc(),
7077                     diag::note_constexpr_bit_cast_unsupported_bitfield);
7078         return None;
7079       }
7080 
7081       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
7082       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
7083 
7084       CharUnits FieldOffset =
7085           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
7086           Offset;
7087       QualType FieldTy = FD->getType();
7088       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
7089       if (!SubObj)
7090         return None;
7091       ResultVal.getStructField(FieldIdx) = *SubObj;
7092       ++FieldIdx;
7093     }
7094 
7095     return ResultVal;
7096   }
7097 
7098   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
7099     QualType RepresentationType = Ty->getDecl()->getIntegerType();
7100     assert(!RepresentationType.isNull() &&
7101            "enum forward decl should be caught by Sema");
7102     const auto *AsBuiltin =
7103         RepresentationType.getCanonicalType()->castAs<BuiltinType>();
7104     // Recurse into the underlying type. Treat std::byte transparently as
7105     // unsigned char.
7106     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
7107   }
7108 
7109   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
7110     size_t Size = Ty->getSize().getLimitedValue();
7111     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
7112 
7113     APValue ArrayValue(APValue::UninitArray(), Size, Size);
7114     for (size_t I = 0; I != Size; ++I) {
7115       Optional<APValue> ElementValue =
7116           visitType(Ty->getElementType(), Offset + I * ElementWidth);
7117       if (!ElementValue)
7118         return None;
7119       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
7120     }
7121 
7122     return ArrayValue;
7123   }
7124 
7125   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
7126     return unsupportedType(QualType(Ty, 0));
7127   }
7128 
7129   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
7130     QualType Can = Ty.getCanonicalType();
7131 
7132     switch (Can->getTypeClass()) {
7133 #define TYPE(Class, Base)                                                      \
7134   case Type::Class:                                                            \
7135     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
7136 #define ABSTRACT_TYPE(Class, Base)
7137 #define NON_CANONICAL_TYPE(Class, Base)                                        \
7138   case Type::Class:                                                            \
7139     llvm_unreachable("non-canonical type should be impossible!");
7140 #define DEPENDENT_TYPE(Class, Base)                                            \
7141   case Type::Class:                                                            \
7142     llvm_unreachable(                                                          \
7143         "dependent types aren't supported in the constant evaluator!");
7144 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
7145   case Type::Class:                                                            \
7146     llvm_unreachable("either dependent or not canonical!");
7147 #include "clang/AST/TypeNodes.inc"
7148     }
7149     llvm_unreachable("Unhandled Type::TypeClass");
7150   }
7151 
7152 public:
7153   // Pull out a full value of type DstType.
7154   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
7155                                    const CastExpr *BCE) {
7156     BufferToAPValueConverter Converter(Info, Buffer, BCE);
7157     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
7158   }
7159 };
7160 
7161 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
7162                                                  QualType Ty, EvalInfo *Info,
7163                                                  const ASTContext &Ctx,
7164                                                  bool CheckingDest) {
7165   Ty = Ty.getCanonicalType();
7166 
7167   auto diag = [&](int Reason) {
7168     if (Info)
7169       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
7170           << CheckingDest << (Reason == 4) << Reason;
7171     return false;
7172   };
7173   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
7174     if (Info)
7175       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
7176           << NoteTy << Construct << Ty;
7177     return false;
7178   };
7179 
7180   if (Ty->isUnionType())
7181     return diag(0);
7182   if (Ty->isPointerType())
7183     return diag(1);
7184   if (Ty->isMemberPointerType())
7185     return diag(2);
7186   if (Ty.isVolatileQualified())
7187     return diag(3);
7188 
7189   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
7190     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
7191       for (CXXBaseSpecifier &BS : CXXRD->bases())
7192         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
7193                                                   CheckingDest))
7194           return note(1, BS.getType(), BS.getBeginLoc());
7195     }
7196     for (FieldDecl *FD : Record->fields()) {
7197       if (FD->getType()->isReferenceType())
7198         return diag(4);
7199       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
7200                                                 CheckingDest))
7201         return note(0, FD->getType(), FD->getBeginLoc());
7202     }
7203   }
7204 
7205   if (Ty->isArrayType() &&
7206       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
7207                                             Info, Ctx, CheckingDest))
7208     return false;
7209 
7210   return true;
7211 }
7212 
7213 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
7214                                              const ASTContext &Ctx,
7215                                              const CastExpr *BCE) {
7216   bool DestOK = checkBitCastConstexprEligibilityType(
7217       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
7218   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
7219                                 BCE->getBeginLoc(),
7220                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
7221   return SourceOK;
7222 }
7223 
7224 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
7225                                         APValue &SourceValue,
7226                                         const CastExpr *BCE) {
7227   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
7228          "no host or target supports non 8-bit chars");
7229   assert(SourceValue.isLValue() &&
7230          "LValueToRValueBitcast requires an lvalue operand!");
7231 
7232   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
7233     return false;
7234 
7235   LValue SourceLValue;
7236   APValue SourceRValue;
7237   SourceLValue.setFrom(Info.Ctx, SourceValue);
7238   if (!handleLValueToRValueConversion(
7239           Info, BCE, BCE->getSubExpr()->getType().withConst(), SourceLValue,
7240           SourceRValue, /*WantObjectRepresentation=*/true))
7241     return false;
7242 
7243   // Read out SourceValue into a char buffer.
7244   Optional<BitCastBuffer> Buffer =
7245       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
7246   if (!Buffer)
7247     return false;
7248 
7249   // Write out the buffer into a new APValue.
7250   Optional<APValue> MaybeDestValue =
7251       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
7252   if (!MaybeDestValue)
7253     return false;
7254 
7255   DestValue = std::move(*MaybeDestValue);
7256   return true;
7257 }
7258 
7259 template <class Derived>
7260 class ExprEvaluatorBase
7261   : public ConstStmtVisitor<Derived, bool> {
7262 private:
7263   Derived &getDerived() { return static_cast<Derived&>(*this); }
7264   bool DerivedSuccess(const APValue &V, const Expr *E) {
7265     return getDerived().Success(V, E);
7266   }
7267   bool DerivedZeroInitialization(const Expr *E) {
7268     return getDerived().ZeroInitialization(E);
7269   }
7270 
7271   // Check whether a conditional operator with a non-constant condition is a
7272   // potential constant expression. If neither arm is a potential constant
7273   // expression, then the conditional operator is not either.
7274   template<typename ConditionalOperator>
7275   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
7276     assert(Info.checkingPotentialConstantExpression());
7277 
7278     // Speculatively evaluate both arms.
7279     SmallVector<PartialDiagnosticAt, 8> Diag;
7280     {
7281       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7282       StmtVisitorTy::Visit(E->getFalseExpr());
7283       if (Diag.empty())
7284         return;
7285     }
7286 
7287     {
7288       SpeculativeEvaluationRAII Speculate(Info, &Diag);
7289       Diag.clear();
7290       StmtVisitorTy::Visit(E->getTrueExpr());
7291       if (Diag.empty())
7292         return;
7293     }
7294 
7295     Error(E, diag::note_constexpr_conditional_never_const);
7296   }
7297 
7298 
7299   template<typename ConditionalOperator>
7300   bool HandleConditionalOperator(const ConditionalOperator *E) {
7301     bool BoolResult;
7302     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
7303       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
7304         CheckPotentialConstantConditional(E);
7305         return false;
7306       }
7307       if (Info.noteFailure()) {
7308         StmtVisitorTy::Visit(E->getTrueExpr());
7309         StmtVisitorTy::Visit(E->getFalseExpr());
7310       }
7311       return false;
7312     }
7313 
7314     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
7315     return StmtVisitorTy::Visit(EvalExpr);
7316   }
7317 
7318 protected:
7319   EvalInfo &Info;
7320   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
7321   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
7322 
7323   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7324     return Info.CCEDiag(E, D);
7325   }
7326 
7327   bool ZeroInitialization(const Expr *E) { return Error(E); }
7328 
7329 public:
7330   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
7331 
7332   EvalInfo &getEvalInfo() { return Info; }
7333 
7334   /// Report an evaluation error. This should only be called when an error is
7335   /// first discovered. When propagating an error, just return false.
7336   bool Error(const Expr *E, diag::kind D) {
7337     Info.FFDiag(E, D);
7338     return false;
7339   }
7340   bool Error(const Expr *E) {
7341     return Error(E, diag::note_invalid_subexpr_in_const_expr);
7342   }
7343 
7344   bool VisitStmt(const Stmt *) {
7345     llvm_unreachable("Expression evaluator should not be called on stmts");
7346   }
7347   bool VisitExpr(const Expr *E) {
7348     return Error(E);
7349   }
7350 
7351   bool VisitConstantExpr(const ConstantExpr *E) {
7352     if (E->hasAPValueResult())
7353       return DerivedSuccess(E->getAPValueResult(), E);
7354 
7355     return StmtVisitorTy::Visit(E->getSubExpr());
7356   }
7357 
7358   bool VisitParenExpr(const ParenExpr *E)
7359     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7360   bool VisitUnaryExtension(const UnaryOperator *E)
7361     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7362   bool VisitUnaryPlus(const UnaryOperator *E)
7363     { return StmtVisitorTy::Visit(E->getSubExpr()); }
7364   bool VisitChooseExpr(const ChooseExpr *E)
7365     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
7366   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
7367     { return StmtVisitorTy::Visit(E->getResultExpr()); }
7368   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
7369     { return StmtVisitorTy::Visit(E->getReplacement()); }
7370   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
7371     TempVersionRAII RAII(*Info.CurrentCall);
7372     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7373     return StmtVisitorTy::Visit(E->getExpr());
7374   }
7375   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
7376     TempVersionRAII RAII(*Info.CurrentCall);
7377     // The initializer may not have been parsed yet, or might be erroneous.
7378     if (!E->getExpr())
7379       return Error(E);
7380     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
7381     return StmtVisitorTy::Visit(E->getExpr());
7382   }
7383 
7384   bool VisitExprWithCleanups(const ExprWithCleanups *E) {
7385     FullExpressionRAII Scope(Info);
7386     return StmtVisitorTy::Visit(E->getSubExpr()) && Scope.destroy();
7387   }
7388 
7389   // Temporaries are registered when created, so we don't care about
7390   // CXXBindTemporaryExpr.
7391   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
7392     return StmtVisitorTy::Visit(E->getSubExpr());
7393   }
7394 
7395   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
7396     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
7397     return static_cast<Derived*>(this)->VisitCastExpr(E);
7398   }
7399   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
7400     if (!Info.Ctx.getLangOpts().CPlusPlus20)
7401       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
7402     return static_cast<Derived*>(this)->VisitCastExpr(E);
7403   }
7404   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
7405     return static_cast<Derived*>(this)->VisitCastExpr(E);
7406   }
7407 
7408   bool VisitBinaryOperator(const BinaryOperator *E) {
7409     switch (E->getOpcode()) {
7410     default:
7411       return Error(E);
7412 
7413     case BO_Comma:
7414       VisitIgnoredValue(E->getLHS());
7415       return StmtVisitorTy::Visit(E->getRHS());
7416 
7417     case BO_PtrMemD:
7418     case BO_PtrMemI: {
7419       LValue Obj;
7420       if (!HandleMemberPointerAccess(Info, E, Obj))
7421         return false;
7422       APValue Result;
7423       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
7424         return false;
7425       return DerivedSuccess(Result, E);
7426     }
7427     }
7428   }
7429 
7430   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E) {
7431     return StmtVisitorTy::Visit(E->getSemanticForm());
7432   }
7433 
7434   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
7435     // Evaluate and cache the common expression. We treat it as a temporary,
7436     // even though it's not quite the same thing.
7437     LValue CommonLV;
7438     if (!Evaluate(Info.CurrentCall->createTemporary(
7439                       E->getOpaqueValue(),
7440                       getStorageType(Info.Ctx, E->getOpaqueValue()),
7441                       ScopeKind::FullExpression, CommonLV),
7442                   Info, E->getCommon()))
7443       return false;
7444 
7445     return HandleConditionalOperator(E);
7446   }
7447 
7448   bool VisitConditionalOperator(const ConditionalOperator *E) {
7449     bool IsBcpCall = false;
7450     // If the condition (ignoring parens) is a __builtin_constant_p call,
7451     // the result is a constant expression if it can be folded without
7452     // side-effects. This is an important GNU extension. See GCC PR38377
7453     // for discussion.
7454     if (const CallExpr *CallCE =
7455           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
7456       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
7457         IsBcpCall = true;
7458 
7459     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
7460     // constant expression; we can't check whether it's potentially foldable.
7461     // FIXME: We should instead treat __builtin_constant_p as non-constant if
7462     // it would return 'false' in this mode.
7463     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
7464       return false;
7465 
7466     FoldConstant Fold(Info, IsBcpCall);
7467     if (!HandleConditionalOperator(E)) {
7468       Fold.keepDiagnostics();
7469       return false;
7470     }
7471 
7472     return true;
7473   }
7474 
7475   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
7476     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
7477       return DerivedSuccess(*Value, E);
7478 
7479     const Expr *Source = E->getSourceExpr();
7480     if (!Source)
7481       return Error(E);
7482     if (Source == E) { // sanity checking.
7483       assert(0 && "OpaqueValueExpr recursively refers to itself");
7484       return Error(E);
7485     }
7486     return StmtVisitorTy::Visit(Source);
7487   }
7488 
7489   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
7490     for (const Expr *SemE : E->semantics()) {
7491       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
7492         // FIXME: We can't handle the case where an OpaqueValueExpr is also the
7493         // result expression: there could be two different LValues that would
7494         // refer to the same object in that case, and we can't model that.
7495         if (SemE == E->getResultExpr())
7496           return Error(E);
7497 
7498         // Unique OVEs get evaluated if and when we encounter them when
7499         // emitting the rest of the semantic form, rather than eagerly.
7500         if (OVE->isUnique())
7501           continue;
7502 
7503         LValue LV;
7504         if (!Evaluate(Info.CurrentCall->createTemporary(
7505                           OVE, getStorageType(Info.Ctx, OVE),
7506                           ScopeKind::FullExpression, LV),
7507                       Info, OVE->getSourceExpr()))
7508           return false;
7509       } else if (SemE == E->getResultExpr()) {
7510         if (!StmtVisitorTy::Visit(SemE))
7511           return false;
7512       } else {
7513         if (!EvaluateIgnoredValue(Info, SemE))
7514           return false;
7515       }
7516     }
7517     return true;
7518   }
7519 
7520   bool VisitCallExpr(const CallExpr *E) {
7521     APValue Result;
7522     if (!handleCallExpr(E, Result, nullptr))
7523       return false;
7524     return DerivedSuccess(Result, E);
7525   }
7526 
7527   bool handleCallExpr(const CallExpr *E, APValue &Result,
7528                      const LValue *ResultSlot) {
7529     CallScopeRAII CallScope(Info);
7530 
7531     const Expr *Callee = E->getCallee()->IgnoreParens();
7532     QualType CalleeType = Callee->getType();
7533 
7534     const FunctionDecl *FD = nullptr;
7535     LValue *This = nullptr, ThisVal;
7536     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
7537     bool HasQualifier = false;
7538 
7539     CallRef Call;
7540 
7541     // Extract function decl and 'this' pointer from the callee.
7542     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
7543       const CXXMethodDecl *Member = nullptr;
7544       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
7545         // Explicit bound member calls, such as x.f() or p->g();
7546         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
7547           return false;
7548         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
7549         if (!Member)
7550           return Error(Callee);
7551         This = &ThisVal;
7552         HasQualifier = ME->hasQualifier();
7553       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
7554         // Indirect bound member calls ('.*' or '->*').
7555         const ValueDecl *D =
7556             HandleMemberPointerAccess(Info, BE, ThisVal, false);
7557         if (!D)
7558           return false;
7559         Member = dyn_cast<CXXMethodDecl>(D);
7560         if (!Member)
7561           return Error(Callee);
7562         This = &ThisVal;
7563       } else if (const auto *PDE = dyn_cast<CXXPseudoDestructorExpr>(Callee)) {
7564         if (!Info.getLangOpts().CPlusPlus20)
7565           Info.CCEDiag(PDE, diag::note_constexpr_pseudo_destructor);
7566         return EvaluateObjectArgument(Info, PDE->getBase(), ThisVal) &&
7567                HandleDestruction(Info, PDE, ThisVal, PDE->getDestroyedType());
7568       } else
7569         return Error(Callee);
7570       FD = Member;
7571     } else if (CalleeType->isFunctionPointerType()) {
7572       LValue CalleeLV;
7573       if (!EvaluatePointer(Callee, CalleeLV, Info))
7574         return false;
7575 
7576       if (!CalleeLV.getLValueOffset().isZero())
7577         return Error(Callee);
7578       FD = dyn_cast_or_null<FunctionDecl>(
7579           CalleeLV.getLValueBase().dyn_cast<const ValueDecl *>());
7580       if (!FD)
7581         return Error(Callee);
7582       // Don't call function pointers which have been cast to some other type.
7583       // Per DR (no number yet), the caller and callee can differ in noexcept.
7584       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
7585         CalleeType->getPointeeType(), FD->getType())) {
7586         return Error(E);
7587       }
7588 
7589       // For an (overloaded) assignment expression, evaluate the RHS before the
7590       // LHS.
7591       auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
7592       if (OCE && OCE->isAssignmentOp()) {
7593         assert(Args.size() == 2 && "wrong number of arguments in assignment");
7594         Call = Info.CurrentCall->createCall(FD);
7595         if (!EvaluateArgs(isa<CXXMethodDecl>(FD) ? Args.slice(1) : Args, Call,
7596                           Info, FD, /*RightToLeft=*/true))
7597           return false;
7598       }
7599 
7600       // Overloaded operator calls to member functions are represented as normal
7601       // calls with '*this' as the first argument.
7602       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
7603       if (MD && !MD->isStatic()) {
7604         // FIXME: When selecting an implicit conversion for an overloaded
7605         // operator delete, we sometimes try to evaluate calls to conversion
7606         // operators without a 'this' parameter!
7607         if (Args.empty())
7608           return Error(E);
7609 
7610         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
7611           return false;
7612         This = &ThisVal;
7613         Args = Args.slice(1);
7614       } else if (MD && MD->isLambdaStaticInvoker()) {
7615         // Map the static invoker for the lambda back to the call operator.
7616         // Conveniently, we don't have to slice out the 'this' argument (as is
7617         // being done for the non-static case), since a static member function
7618         // doesn't have an implicit argument passed in.
7619         const CXXRecordDecl *ClosureClass = MD->getParent();
7620         assert(
7621             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
7622             "Number of captures must be zero for conversion to function-ptr");
7623 
7624         const CXXMethodDecl *LambdaCallOp =
7625             ClosureClass->getLambdaCallOperator();
7626 
7627         // Set 'FD', the function that will be called below, to the call
7628         // operator.  If the closure object represents a generic lambda, find
7629         // the corresponding specialization of the call operator.
7630 
7631         if (ClosureClass->isGenericLambda()) {
7632           assert(MD->isFunctionTemplateSpecialization() &&
7633                  "A generic lambda's static-invoker function must be a "
7634                  "template specialization");
7635           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
7636           FunctionTemplateDecl *CallOpTemplate =
7637               LambdaCallOp->getDescribedFunctionTemplate();
7638           void *InsertPos = nullptr;
7639           FunctionDecl *CorrespondingCallOpSpecialization =
7640               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7641           assert(CorrespondingCallOpSpecialization &&
7642                  "We must always have a function call operator specialization "
7643                  "that corresponds to our static invoker specialization");
7644           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
7645         } else
7646           FD = LambdaCallOp;
7647       } else if (FD->isReplaceableGlobalAllocationFunction()) {
7648         if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||
7649             FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
7650           LValue Ptr;
7651           if (!HandleOperatorNewCall(Info, E, Ptr))
7652             return false;
7653           Ptr.moveInto(Result);
7654           return CallScope.destroy();
7655         } else {
7656           return HandleOperatorDeleteCall(Info, E) && CallScope.destroy();
7657         }
7658       }
7659     } else
7660       return Error(E);
7661 
7662     // Evaluate the arguments now if we've not already done so.
7663     if (!Call) {
7664       Call = Info.CurrentCall->createCall(FD);
7665       if (!EvaluateArgs(Args, Call, Info, FD))
7666         return false;
7667     }
7668 
7669     SmallVector<QualType, 4> CovariantAdjustmentPath;
7670     if (This) {
7671       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
7672       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
7673         // Perform virtual dispatch, if necessary.
7674         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
7675                                    CovariantAdjustmentPath);
7676         if (!FD)
7677           return false;
7678       } else {
7679         // Check that the 'this' pointer points to an object of the right type.
7680         // FIXME: If this is an assignment operator call, we may need to change
7681         // the active union member before we check this.
7682         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This, NamedMember))
7683           return false;
7684       }
7685     }
7686 
7687     // Destructor calls are different enough that they have their own codepath.
7688     if (auto *DD = dyn_cast<CXXDestructorDecl>(FD)) {
7689       assert(This && "no 'this' pointer for destructor call");
7690       return HandleDestruction(Info, E, *This,
7691                                Info.Ctx.getRecordType(DD->getParent())) &&
7692              CallScope.destroy();
7693     }
7694 
7695     const FunctionDecl *Definition = nullptr;
7696     Stmt *Body = FD->getBody(Definition);
7697 
7698     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
7699         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Call,
7700                             Body, Info, Result, ResultSlot))
7701       return false;
7702 
7703     if (!CovariantAdjustmentPath.empty() &&
7704         !HandleCovariantReturnAdjustment(Info, E, Result,
7705                                          CovariantAdjustmentPath))
7706       return false;
7707 
7708     return CallScope.destroy();
7709   }
7710 
7711   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
7712     return StmtVisitorTy::Visit(E->getInitializer());
7713   }
7714   bool VisitInitListExpr(const InitListExpr *E) {
7715     if (E->getNumInits() == 0)
7716       return DerivedZeroInitialization(E);
7717     if (E->getNumInits() == 1)
7718       return StmtVisitorTy::Visit(E->getInit(0));
7719     return Error(E);
7720   }
7721   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
7722     return DerivedZeroInitialization(E);
7723   }
7724   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
7725     return DerivedZeroInitialization(E);
7726   }
7727   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
7728     return DerivedZeroInitialization(E);
7729   }
7730 
7731   /// A member expression where the object is a prvalue is itself a prvalue.
7732   bool VisitMemberExpr(const MemberExpr *E) {
7733     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
7734            "missing temporary materialization conversion");
7735     assert(!E->isArrow() && "missing call to bound member function?");
7736 
7737     APValue Val;
7738     if (!Evaluate(Val, Info, E->getBase()))
7739       return false;
7740 
7741     QualType BaseTy = E->getBase()->getType();
7742 
7743     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
7744     if (!FD) return Error(E);
7745     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
7746     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7747            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7748 
7749     // Note: there is no lvalue base here. But this case should only ever
7750     // happen in C or in C++98, where we cannot be evaluating a constexpr
7751     // constructor, which is the only case the base matters.
7752     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
7753     SubobjectDesignator Designator(BaseTy);
7754     Designator.addDeclUnchecked(FD);
7755 
7756     APValue Result;
7757     return extractSubobject(Info, E, Obj, Designator, Result) &&
7758            DerivedSuccess(Result, E);
7759   }
7760 
7761   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E) {
7762     APValue Val;
7763     if (!Evaluate(Val, Info, E->getBase()))
7764       return false;
7765 
7766     if (Val.isVector()) {
7767       SmallVector<uint32_t, 4> Indices;
7768       E->getEncodedElementAccess(Indices);
7769       if (Indices.size() == 1) {
7770         // Return scalar.
7771         return DerivedSuccess(Val.getVectorElt(Indices[0]), E);
7772       } else {
7773         // Construct new APValue vector.
7774         SmallVector<APValue, 4> Elts;
7775         for (unsigned I = 0; I < Indices.size(); ++I) {
7776           Elts.push_back(Val.getVectorElt(Indices[I]));
7777         }
7778         APValue VecResult(Elts.data(), Indices.size());
7779         return DerivedSuccess(VecResult, E);
7780       }
7781     }
7782 
7783     return false;
7784   }
7785 
7786   bool VisitCastExpr(const CastExpr *E) {
7787     switch (E->getCastKind()) {
7788     default:
7789       break;
7790 
7791     case CK_AtomicToNonAtomic: {
7792       APValue AtomicVal;
7793       // This does not need to be done in place even for class/array types:
7794       // atomic-to-non-atomic conversion implies copying the object
7795       // representation.
7796       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
7797         return false;
7798       return DerivedSuccess(AtomicVal, E);
7799     }
7800 
7801     case CK_NoOp:
7802     case CK_UserDefinedConversion:
7803       return StmtVisitorTy::Visit(E->getSubExpr());
7804 
7805     case CK_LValueToRValue: {
7806       LValue LVal;
7807       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
7808         return false;
7809       APValue RVal;
7810       // Note, we use the subexpression's type in order to retain cv-qualifiers.
7811       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7812                                           LVal, RVal))
7813         return false;
7814       return DerivedSuccess(RVal, E);
7815     }
7816     case CK_LValueToRValueBitCast: {
7817       APValue DestValue, SourceValue;
7818       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
7819         return false;
7820       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
7821         return false;
7822       return DerivedSuccess(DestValue, E);
7823     }
7824 
7825     case CK_AddressSpaceConversion: {
7826       APValue Value;
7827       if (!Evaluate(Value, Info, E->getSubExpr()))
7828         return false;
7829       return DerivedSuccess(Value, E);
7830     }
7831     }
7832 
7833     return Error(E);
7834   }
7835 
7836   bool VisitUnaryPostInc(const UnaryOperator *UO) {
7837     return VisitUnaryPostIncDec(UO);
7838   }
7839   bool VisitUnaryPostDec(const UnaryOperator *UO) {
7840     return VisitUnaryPostIncDec(UO);
7841   }
7842   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
7843     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
7844       return Error(UO);
7845 
7846     LValue LVal;
7847     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
7848       return false;
7849     APValue RVal;
7850     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
7851                       UO->isIncrementOp(), &RVal))
7852       return false;
7853     return DerivedSuccess(RVal, UO);
7854   }
7855 
7856   bool VisitStmtExpr(const StmtExpr *E) {
7857     // We will have checked the full-expressions inside the statement expression
7858     // when they were completed, and don't need to check them again now.
7859     llvm::SaveAndRestore<bool> NotCheckingForUB(
7860         Info.CheckingForUndefinedBehavior, false);
7861 
7862     const CompoundStmt *CS = E->getSubStmt();
7863     if (CS->body_empty())
7864       return true;
7865 
7866     BlockScopeRAII Scope(Info);
7867     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
7868                                            BE = CS->body_end();
7869          /**/; ++BI) {
7870       if (BI + 1 == BE) {
7871         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
7872         if (!FinalExpr) {
7873           Info.FFDiag((*BI)->getBeginLoc(),
7874                       diag::note_constexpr_stmt_expr_unsupported);
7875           return false;
7876         }
7877         return this->Visit(FinalExpr) && Scope.destroy();
7878       }
7879 
7880       APValue ReturnValue;
7881       StmtResult Result = { ReturnValue, nullptr };
7882       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
7883       if (ESR != ESR_Succeeded) {
7884         // FIXME: If the statement-expression terminated due to 'return',
7885         // 'break', or 'continue', it would be nice to propagate that to
7886         // the outer statement evaluation rather than bailing out.
7887         if (ESR != ESR_Failed)
7888           Info.FFDiag((*BI)->getBeginLoc(),
7889                       diag::note_constexpr_stmt_expr_unsupported);
7890         return false;
7891       }
7892     }
7893 
7894     llvm_unreachable("Return from function from the loop above.");
7895   }
7896 
7897   /// Visit a value which is evaluated, but whose value is ignored.
7898   void VisitIgnoredValue(const Expr *E) {
7899     EvaluateIgnoredValue(Info, E);
7900   }
7901 
7902   /// Potentially visit a MemberExpr's base expression.
7903   void VisitIgnoredBaseExpression(const Expr *E) {
7904     // While MSVC doesn't evaluate the base expression, it does diagnose the
7905     // presence of side-effecting behavior.
7906     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
7907       return;
7908     VisitIgnoredValue(E);
7909   }
7910 };
7911 
7912 } // namespace
7913 
7914 //===----------------------------------------------------------------------===//
7915 // Common base class for lvalue and temporary evaluation.
7916 //===----------------------------------------------------------------------===//
7917 namespace {
7918 template<class Derived>
7919 class LValueExprEvaluatorBase
7920   : public ExprEvaluatorBase<Derived> {
7921 protected:
7922   LValue &Result;
7923   bool InvalidBaseOK;
7924   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
7925   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
7926 
7927   bool Success(APValue::LValueBase B) {
7928     Result.set(B);
7929     return true;
7930   }
7931 
7932   bool evaluatePointer(const Expr *E, LValue &Result) {
7933     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
7934   }
7935 
7936 public:
7937   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
7938       : ExprEvaluatorBaseTy(Info), Result(Result),
7939         InvalidBaseOK(InvalidBaseOK) {}
7940 
7941   bool Success(const APValue &V, const Expr *E) {
7942     Result.setFrom(this->Info.Ctx, V);
7943     return true;
7944   }
7945 
7946   bool VisitMemberExpr(const MemberExpr *E) {
7947     // Handle non-static data members.
7948     QualType BaseTy;
7949     bool EvalOK;
7950     if (E->isArrow()) {
7951       EvalOK = evaluatePointer(E->getBase(), Result);
7952       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
7953     } else if (E->getBase()->isPRValue()) {
7954       assert(E->getBase()->getType()->isRecordType());
7955       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
7956       BaseTy = E->getBase()->getType();
7957     } else {
7958       EvalOK = this->Visit(E->getBase());
7959       BaseTy = E->getBase()->getType();
7960     }
7961     if (!EvalOK) {
7962       if (!InvalidBaseOK)
7963         return false;
7964       Result.setInvalid(E);
7965       return true;
7966     }
7967 
7968     const ValueDecl *MD = E->getMemberDecl();
7969     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
7970       assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
7971              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
7972       (void)BaseTy;
7973       if (!HandleLValueMember(this->Info, E, Result, FD))
7974         return false;
7975     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
7976       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
7977         return false;
7978     } else
7979       return this->Error(E);
7980 
7981     if (MD->getType()->isReferenceType()) {
7982       APValue RefValue;
7983       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
7984                                           RefValue))
7985         return false;
7986       return Success(RefValue, E);
7987     }
7988     return true;
7989   }
7990 
7991   bool VisitBinaryOperator(const BinaryOperator *E) {
7992     switch (E->getOpcode()) {
7993     default:
7994       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7995 
7996     case BO_PtrMemD:
7997     case BO_PtrMemI:
7998       return HandleMemberPointerAccess(this->Info, E, Result);
7999     }
8000   }
8001 
8002   bool VisitCastExpr(const CastExpr *E) {
8003     switch (E->getCastKind()) {
8004     default:
8005       return ExprEvaluatorBaseTy::VisitCastExpr(E);
8006 
8007     case CK_DerivedToBase:
8008     case CK_UncheckedDerivedToBase:
8009       if (!this->Visit(E->getSubExpr()))
8010         return false;
8011 
8012       // Now figure out the necessary offset to add to the base LV to get from
8013       // the derived class to the base class.
8014       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
8015                                   Result);
8016     }
8017   }
8018 };
8019 }
8020 
8021 //===----------------------------------------------------------------------===//
8022 // LValue Evaluation
8023 //
8024 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
8025 // function designators (in C), decl references to void objects (in C), and
8026 // temporaries (if building with -Wno-address-of-temporary).
8027 //
8028 // LValue evaluation produces values comprising a base expression of one of the
8029 // following types:
8030 // - Declarations
8031 //  * VarDecl
8032 //  * FunctionDecl
8033 // - Literals
8034 //  * CompoundLiteralExpr in C (and in global scope in C++)
8035 //  * StringLiteral
8036 //  * PredefinedExpr
8037 //  * ObjCStringLiteralExpr
8038 //  * ObjCEncodeExpr
8039 //  * AddrLabelExpr
8040 //  * BlockExpr
8041 //  * CallExpr for a MakeStringConstant builtin
8042 // - typeid(T) expressions, as TypeInfoLValues
8043 // - Locals and temporaries
8044 //  * MaterializeTemporaryExpr
8045 //  * Any Expr, with a CallIndex indicating the function in which the temporary
8046 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
8047 //    from the AST (FIXME).
8048 //  * A MaterializeTemporaryExpr that has static storage duration, with no
8049 //    CallIndex, for a lifetime-extended temporary.
8050 //  * The ConstantExpr that is currently being evaluated during evaluation of an
8051 //    immediate invocation.
8052 // plus an offset in bytes.
8053 //===----------------------------------------------------------------------===//
8054 namespace {
8055 class LValueExprEvaluator
8056   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
8057 public:
8058   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
8059     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
8060 
8061   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
8062   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
8063 
8064   bool VisitDeclRefExpr(const DeclRefExpr *E);
8065   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
8066   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
8067   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
8068   bool VisitMemberExpr(const MemberExpr *E);
8069   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
8070   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
8071   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
8072   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
8073   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
8074   bool VisitUnaryDeref(const UnaryOperator *E);
8075   bool VisitUnaryReal(const UnaryOperator *E);
8076   bool VisitUnaryImag(const UnaryOperator *E);
8077   bool VisitUnaryPreInc(const UnaryOperator *UO) {
8078     return VisitUnaryPreIncDec(UO);
8079   }
8080   bool VisitUnaryPreDec(const UnaryOperator *UO) {
8081     return VisitUnaryPreIncDec(UO);
8082   }
8083   bool VisitBinAssign(const BinaryOperator *BO);
8084   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
8085 
8086   bool VisitCastExpr(const CastExpr *E) {
8087     switch (E->getCastKind()) {
8088     default:
8089       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8090 
8091     case CK_LValueBitCast:
8092       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8093       if (!Visit(E->getSubExpr()))
8094         return false;
8095       Result.Designator.setInvalid();
8096       return true;
8097 
8098     case CK_BaseToDerived:
8099       if (!Visit(E->getSubExpr()))
8100         return false;
8101       return HandleBaseToDerivedCast(Info, E, Result);
8102 
8103     case CK_Dynamic:
8104       if (!Visit(E->getSubExpr()))
8105         return false;
8106       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8107     }
8108   }
8109 };
8110 } // end anonymous namespace
8111 
8112 /// Evaluate an expression as an lvalue. This can be legitimately called on
8113 /// expressions which are not glvalues, in three cases:
8114 ///  * function designators in C, and
8115 ///  * "extern void" objects
8116 ///  * @selector() expressions in Objective-C
8117 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
8118                            bool InvalidBaseOK) {
8119   assert(!E->isValueDependent());
8120   assert(E->isGLValue() || E->getType()->isFunctionType() ||
8121          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
8122   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8123 }
8124 
8125 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
8126   const NamedDecl *D = E->getDecl();
8127   if (isa<FunctionDecl, MSGuidDecl, TemplateParamObjectDecl>(D))
8128     return Success(cast<ValueDecl>(D));
8129   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
8130     return VisitVarDecl(E, VD);
8131   if (const BindingDecl *BD = dyn_cast<BindingDecl>(D))
8132     return Visit(BD->getBinding());
8133   return Error(E);
8134 }
8135 
8136 
8137 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
8138 
8139   // If we are within a lambda's call operator, check whether the 'VD' referred
8140   // to within 'E' actually represents a lambda-capture that maps to a
8141   // data-member/field within the closure object, and if so, evaluate to the
8142   // field or what the field refers to.
8143   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
8144       isa<DeclRefExpr>(E) &&
8145       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
8146     // We don't always have a complete capture-map when checking or inferring if
8147     // the function call operator meets the requirements of a constexpr function
8148     // - but we don't need to evaluate the captures to determine constexprness
8149     // (dcl.constexpr C++17).
8150     if (Info.checkingPotentialConstantExpression())
8151       return false;
8152 
8153     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
8154       // Start with 'Result' referring to the complete closure object...
8155       Result = *Info.CurrentCall->This;
8156       // ... then update it to refer to the field of the closure object
8157       // that represents the capture.
8158       if (!HandleLValueMember(Info, E, Result, FD))
8159         return false;
8160       // And if the field is of reference type, update 'Result' to refer to what
8161       // the field refers to.
8162       if (FD->getType()->isReferenceType()) {
8163         APValue RVal;
8164         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
8165                                             RVal))
8166           return false;
8167         Result.setFrom(Info.Ctx, RVal);
8168       }
8169       return true;
8170     }
8171   }
8172 
8173   CallStackFrame *Frame = nullptr;
8174   unsigned Version = 0;
8175   if (VD->hasLocalStorage()) {
8176     // Only if a local variable was declared in the function currently being
8177     // evaluated, do we expect to be able to find its value in the current
8178     // frame. (Otherwise it was likely declared in an enclosing context and
8179     // could either have a valid evaluatable value (for e.g. a constexpr
8180     // variable) or be ill-formed (and trigger an appropriate evaluation
8181     // diagnostic)).
8182     CallStackFrame *CurrFrame = Info.CurrentCall;
8183     if (CurrFrame->Callee && CurrFrame->Callee->Equals(VD->getDeclContext())) {
8184       // Function parameters are stored in some caller's frame. (Usually the
8185       // immediate caller, but for an inherited constructor they may be more
8186       // distant.)
8187       if (auto *PVD = dyn_cast<ParmVarDecl>(VD)) {
8188         if (CurrFrame->Arguments) {
8189           VD = CurrFrame->Arguments.getOrigParam(PVD);
8190           Frame =
8191               Info.getCallFrameAndDepth(CurrFrame->Arguments.CallIndex).first;
8192           Version = CurrFrame->Arguments.Version;
8193         }
8194       } else {
8195         Frame = CurrFrame;
8196         Version = CurrFrame->getCurrentTemporaryVersion(VD);
8197       }
8198     }
8199   }
8200 
8201   if (!VD->getType()->isReferenceType()) {
8202     if (Frame) {
8203       Result.set({VD, Frame->Index, Version});
8204       return true;
8205     }
8206     return Success(VD);
8207   }
8208 
8209   if (!Info.getLangOpts().CPlusPlus11) {
8210     Info.CCEDiag(E, diag::note_constexpr_ltor_non_integral, 1)
8211         << VD << VD->getType();
8212     Info.Note(VD->getLocation(), diag::note_declared_at);
8213   }
8214 
8215   APValue *V;
8216   if (!evaluateVarDeclInit(Info, E, VD, Frame, Version, V))
8217     return false;
8218   if (!V->hasValue()) {
8219     // FIXME: Is it possible for V to be indeterminate here? If so, we should
8220     // adjust the diagnostic to say that.
8221     if (!Info.checkingPotentialConstantExpression())
8222       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
8223     return false;
8224   }
8225   return Success(*V, E);
8226 }
8227 
8228 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
8229     const MaterializeTemporaryExpr *E) {
8230   // Walk through the expression to find the materialized temporary itself.
8231   SmallVector<const Expr *, 2> CommaLHSs;
8232   SmallVector<SubobjectAdjustment, 2> Adjustments;
8233   const Expr *Inner =
8234       E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
8235 
8236   // If we passed any comma operators, evaluate their LHSs.
8237   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
8238     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
8239       return false;
8240 
8241   // A materialized temporary with static storage duration can appear within the
8242   // result of a constant expression evaluation, so we need to preserve its
8243   // value for use outside this evaluation.
8244   APValue *Value;
8245   if (E->getStorageDuration() == SD_Static) {
8246     // FIXME: What about SD_Thread?
8247     Value = E->getOrCreateValue(true);
8248     *Value = APValue();
8249     Result.set(E);
8250   } else {
8251     Value = &Info.CurrentCall->createTemporary(
8252         E, E->getType(),
8253         E->getStorageDuration() == SD_FullExpression ? ScopeKind::FullExpression
8254                                                      : ScopeKind::Block,
8255         Result);
8256   }
8257 
8258   QualType Type = Inner->getType();
8259 
8260   // Materialize the temporary itself.
8261   if (!EvaluateInPlace(*Value, Info, Result, Inner)) {
8262     *Value = APValue();
8263     return false;
8264   }
8265 
8266   // Adjust our lvalue to refer to the desired subobject.
8267   for (unsigned I = Adjustments.size(); I != 0; /**/) {
8268     --I;
8269     switch (Adjustments[I].Kind) {
8270     case SubobjectAdjustment::DerivedToBaseAdjustment:
8271       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
8272                                 Type, Result))
8273         return false;
8274       Type = Adjustments[I].DerivedToBase.BasePath->getType();
8275       break;
8276 
8277     case SubobjectAdjustment::FieldAdjustment:
8278       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
8279         return false;
8280       Type = Adjustments[I].Field->getType();
8281       break;
8282 
8283     case SubobjectAdjustment::MemberPointerAdjustment:
8284       if (!HandleMemberPointerAccess(this->Info, Type, Result,
8285                                      Adjustments[I].Ptr.RHS))
8286         return false;
8287       Type = Adjustments[I].Ptr.MPT->getPointeeType();
8288       break;
8289     }
8290   }
8291 
8292   return true;
8293 }
8294 
8295 bool
8296 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
8297   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
8298          "lvalue compound literal in c++?");
8299   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
8300   // only see this when folding in C, so there's no standard to follow here.
8301   return Success(E);
8302 }
8303 
8304 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
8305   TypeInfoLValue TypeInfo;
8306 
8307   if (!E->isPotentiallyEvaluated()) {
8308     if (E->isTypeOperand())
8309       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
8310     else
8311       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
8312   } else {
8313     if (!Info.Ctx.getLangOpts().CPlusPlus20) {
8314       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
8315         << E->getExprOperand()->getType()
8316         << E->getExprOperand()->getSourceRange();
8317     }
8318 
8319     if (!Visit(E->getExprOperand()))
8320       return false;
8321 
8322     Optional<DynamicType> DynType =
8323         ComputeDynamicType(Info, E, Result, AK_TypeId);
8324     if (!DynType)
8325       return false;
8326 
8327     TypeInfo =
8328         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
8329   }
8330 
8331   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
8332 }
8333 
8334 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
8335   return Success(E->getGuidDecl());
8336 }
8337 
8338 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
8339   // Handle static data members.
8340   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
8341     VisitIgnoredBaseExpression(E->getBase());
8342     return VisitVarDecl(E, VD);
8343   }
8344 
8345   // Handle static member functions.
8346   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
8347     if (MD->isStatic()) {
8348       VisitIgnoredBaseExpression(E->getBase());
8349       return Success(MD);
8350     }
8351   }
8352 
8353   // Handle non-static data members.
8354   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
8355 }
8356 
8357 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
8358   // FIXME: Deal with vectors as array subscript bases.
8359   if (E->getBase()->getType()->isVectorType())
8360     return Error(E);
8361 
8362   APSInt Index;
8363   bool Success = true;
8364 
8365   // C++17's rules require us to evaluate the LHS first, regardless of which
8366   // side is the base.
8367   for (const Expr *SubExpr : {E->getLHS(), E->getRHS()}) {
8368     if (SubExpr == E->getBase() ? !evaluatePointer(SubExpr, Result)
8369                                 : !EvaluateInteger(SubExpr, Index, Info)) {
8370       if (!Info.noteFailure())
8371         return false;
8372       Success = false;
8373     }
8374   }
8375 
8376   return Success &&
8377          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
8378 }
8379 
8380 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
8381   return evaluatePointer(E->getSubExpr(), Result);
8382 }
8383 
8384 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8385   if (!Visit(E->getSubExpr()))
8386     return false;
8387   // __real is a no-op on scalar lvalues.
8388   if (E->getSubExpr()->getType()->isAnyComplexType())
8389     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
8390   return true;
8391 }
8392 
8393 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8394   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
8395          "lvalue __imag__ on scalar?");
8396   if (!Visit(E->getSubExpr()))
8397     return false;
8398   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
8399   return true;
8400 }
8401 
8402 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
8403   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8404     return Error(UO);
8405 
8406   if (!this->Visit(UO->getSubExpr()))
8407     return false;
8408 
8409   return handleIncDec(
8410       this->Info, UO, Result, UO->getSubExpr()->getType(),
8411       UO->isIncrementOp(), nullptr);
8412 }
8413 
8414 bool LValueExprEvaluator::VisitCompoundAssignOperator(
8415     const CompoundAssignOperator *CAO) {
8416   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8417     return Error(CAO);
8418 
8419   bool Success = true;
8420 
8421   // C++17 onwards require that we evaluate the RHS first.
8422   APValue RHS;
8423   if (!Evaluate(RHS, this->Info, CAO->getRHS())) {
8424     if (!Info.noteFailure())
8425       return false;
8426     Success = false;
8427   }
8428 
8429   // The overall lvalue result is the result of evaluating the LHS.
8430   if (!this->Visit(CAO->getLHS()) || !Success)
8431     return false;
8432 
8433   return handleCompoundAssignment(
8434       this->Info, CAO,
8435       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
8436       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
8437 }
8438 
8439 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
8440   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
8441     return Error(E);
8442 
8443   bool Success = true;
8444 
8445   // C++17 onwards require that we evaluate the RHS first.
8446   APValue NewVal;
8447   if (!Evaluate(NewVal, this->Info, E->getRHS())) {
8448     if (!Info.noteFailure())
8449       return false;
8450     Success = false;
8451   }
8452 
8453   if (!this->Visit(E->getLHS()) || !Success)
8454     return false;
8455 
8456   if (Info.getLangOpts().CPlusPlus20 &&
8457       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
8458     return false;
8459 
8460   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
8461                           NewVal);
8462 }
8463 
8464 //===----------------------------------------------------------------------===//
8465 // Pointer Evaluation
8466 //===----------------------------------------------------------------------===//
8467 
8468 /// Attempts to compute the number of bytes available at the pointer
8469 /// returned by a function with the alloc_size attribute. Returns true if we
8470 /// were successful. Places an unsigned number into `Result`.
8471 ///
8472 /// This expects the given CallExpr to be a call to a function with an
8473 /// alloc_size attribute.
8474 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8475                                             const CallExpr *Call,
8476                                             llvm::APInt &Result) {
8477   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
8478 
8479   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
8480   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
8481   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
8482   if (Call->getNumArgs() <= SizeArgNo)
8483     return false;
8484 
8485   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
8486     Expr::EvalResult ExprResult;
8487     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
8488       return false;
8489     Into = ExprResult.Val.getInt();
8490     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
8491       return false;
8492     Into = Into.zextOrSelf(BitsInSizeT);
8493     return true;
8494   };
8495 
8496   APSInt SizeOfElem;
8497   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
8498     return false;
8499 
8500   if (!AllocSize->getNumElemsParam().isValid()) {
8501     Result = std::move(SizeOfElem);
8502     return true;
8503   }
8504 
8505   APSInt NumberOfElems;
8506   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
8507   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
8508     return false;
8509 
8510   bool Overflow;
8511   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
8512   if (Overflow)
8513     return false;
8514 
8515   Result = std::move(BytesAvailable);
8516   return true;
8517 }
8518 
8519 /// Convenience function. LVal's base must be a call to an alloc_size
8520 /// function.
8521 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
8522                                             const LValue &LVal,
8523                                             llvm::APInt &Result) {
8524   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8525          "Can't get the size of a non alloc_size function");
8526   const auto *Base = LVal.getLValueBase().get<const Expr *>();
8527   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
8528   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
8529 }
8530 
8531 /// Attempts to evaluate the given LValueBase as the result of a call to
8532 /// a function with the alloc_size attribute. If it was possible to do so, this
8533 /// function will return true, make Result's Base point to said function call,
8534 /// and mark Result's Base as invalid.
8535 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
8536                                       LValue &Result) {
8537   if (Base.isNull())
8538     return false;
8539 
8540   // Because we do no form of static analysis, we only support const variables.
8541   //
8542   // Additionally, we can't support parameters, nor can we support static
8543   // variables (in the latter case, use-before-assign isn't UB; in the former,
8544   // we have no clue what they'll be assigned to).
8545   const auto *VD =
8546       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
8547   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
8548     return false;
8549 
8550   const Expr *Init = VD->getAnyInitializer();
8551   if (!Init)
8552     return false;
8553 
8554   const Expr *E = Init->IgnoreParens();
8555   if (!tryUnwrapAllocSizeCall(E))
8556     return false;
8557 
8558   // Store E instead of E unwrapped so that the type of the LValue's base is
8559   // what the user wanted.
8560   Result.setInvalid(E);
8561 
8562   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
8563   Result.addUnsizedArray(Info, E, Pointee);
8564   return true;
8565 }
8566 
8567 namespace {
8568 class PointerExprEvaluator
8569   : public ExprEvaluatorBase<PointerExprEvaluator> {
8570   LValue &Result;
8571   bool InvalidBaseOK;
8572 
8573   bool Success(const Expr *E) {
8574     Result.set(E);
8575     return true;
8576   }
8577 
8578   bool evaluateLValue(const Expr *E, LValue &Result) {
8579     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
8580   }
8581 
8582   bool evaluatePointer(const Expr *E, LValue &Result) {
8583     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
8584   }
8585 
8586   bool visitNonBuiltinCallExpr(const CallExpr *E);
8587 public:
8588 
8589   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
8590       : ExprEvaluatorBaseTy(info), Result(Result),
8591         InvalidBaseOK(InvalidBaseOK) {}
8592 
8593   bool Success(const APValue &V, const Expr *E) {
8594     Result.setFrom(Info.Ctx, V);
8595     return true;
8596   }
8597   bool ZeroInitialization(const Expr *E) {
8598     Result.setNull(Info.Ctx, E->getType());
8599     return true;
8600   }
8601 
8602   bool VisitBinaryOperator(const BinaryOperator *E);
8603   bool VisitCastExpr(const CastExpr* E);
8604   bool VisitUnaryAddrOf(const UnaryOperator *E);
8605   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
8606       { return Success(E); }
8607   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
8608     if (E->isExpressibleAsConstantInitializer())
8609       return Success(E);
8610     if (Info.noteFailure())
8611       EvaluateIgnoredValue(Info, E->getSubExpr());
8612     return Error(E);
8613   }
8614   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
8615       { return Success(E); }
8616   bool VisitCallExpr(const CallExpr *E);
8617   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8618   bool VisitBlockExpr(const BlockExpr *E) {
8619     if (!E->getBlockDecl()->hasCaptures())
8620       return Success(E);
8621     return Error(E);
8622   }
8623   bool VisitCXXThisExpr(const CXXThisExpr *E) {
8624     // Can't look at 'this' when checking a potential constant expression.
8625     if (Info.checkingPotentialConstantExpression())
8626       return false;
8627     if (!Info.CurrentCall->This) {
8628       if (Info.getLangOpts().CPlusPlus11)
8629         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
8630       else
8631         Info.FFDiag(E);
8632       return false;
8633     }
8634     Result = *Info.CurrentCall->This;
8635     // If we are inside a lambda's call operator, the 'this' expression refers
8636     // to the enclosing '*this' object (either by value or reference) which is
8637     // either copied into the closure object's field that represents the '*this'
8638     // or refers to '*this'.
8639     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
8640       // Ensure we actually have captured 'this'. (an error will have
8641       // been previously reported if not).
8642       if (!Info.CurrentCall->LambdaThisCaptureField)
8643         return false;
8644 
8645       // Update 'Result' to refer to the data member/field of the closure object
8646       // that represents the '*this' capture.
8647       if (!HandleLValueMember(Info, E, Result,
8648                              Info.CurrentCall->LambdaThisCaptureField))
8649         return false;
8650       // If we captured '*this' by reference, replace the field with its referent.
8651       if (Info.CurrentCall->LambdaThisCaptureField->getType()
8652               ->isPointerType()) {
8653         APValue RVal;
8654         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
8655                                             RVal))
8656           return false;
8657 
8658         Result.setFrom(Info.Ctx, RVal);
8659       }
8660     }
8661     return true;
8662   }
8663 
8664   bool VisitCXXNewExpr(const CXXNewExpr *E);
8665 
8666   bool VisitSourceLocExpr(const SourceLocExpr *E) {
8667     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
8668     APValue LValResult = E->EvaluateInContext(
8669         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8670     Result.setFrom(Info.Ctx, LValResult);
8671     return true;
8672   }
8673 
8674   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E) {
8675     std::string ResultStr = E->ComputeName(Info.Ctx);
8676 
8677     Info.Ctx.SYCLUniqueStableNameEvaluatedValues[E] = ResultStr;
8678 
8679     QualType CharTy = Info.Ctx.CharTy.withConst();
8680     APInt Size(Info.Ctx.getTypeSize(Info.Ctx.getSizeType()),
8681                ResultStr.size() + 1);
8682     QualType ArrayTy = Info.Ctx.getConstantArrayType(CharTy, Size, nullptr,
8683                                                      ArrayType::Normal, 0);
8684 
8685     StringLiteral *SL =
8686         StringLiteral::Create(Info.Ctx, ResultStr, StringLiteral::Ascii,
8687                               /*Pascal*/ false, ArrayTy, E->getLocation());
8688 
8689     evaluateLValue(SL, Result);
8690     Result.addArray(Info, E, cast<ConstantArrayType>(ArrayTy));
8691     return true;
8692   }
8693 
8694   // FIXME: Missing: @protocol, @selector
8695 };
8696 } // end anonymous namespace
8697 
8698 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
8699                             bool InvalidBaseOK) {
8700   assert(!E->isValueDependent());
8701   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
8702   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
8703 }
8704 
8705 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8706   if (E->getOpcode() != BO_Add &&
8707       E->getOpcode() != BO_Sub)
8708     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8709 
8710   const Expr *PExp = E->getLHS();
8711   const Expr *IExp = E->getRHS();
8712   if (IExp->getType()->isPointerType())
8713     std::swap(PExp, IExp);
8714 
8715   bool EvalPtrOK = evaluatePointer(PExp, Result);
8716   if (!EvalPtrOK && !Info.noteFailure())
8717     return false;
8718 
8719   llvm::APSInt Offset;
8720   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
8721     return false;
8722 
8723   if (E->getOpcode() == BO_Sub)
8724     negateAsSigned(Offset);
8725 
8726   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
8727   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
8728 }
8729 
8730 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
8731   return evaluateLValue(E->getSubExpr(), Result);
8732 }
8733 
8734 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
8735   const Expr *SubExpr = E->getSubExpr();
8736 
8737   switch (E->getCastKind()) {
8738   default:
8739     break;
8740   case CK_BitCast:
8741   case CK_CPointerToObjCPointerCast:
8742   case CK_BlockPointerToObjCPointerCast:
8743   case CK_AnyPointerToBlockPointerCast:
8744   case CK_AddressSpaceConversion:
8745     if (!Visit(SubExpr))
8746       return false;
8747     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
8748     // permitted in constant expressions in C++11. Bitcasts from cv void* are
8749     // also static_casts, but we disallow them as a resolution to DR1312.
8750     if (!E->getType()->isVoidPointerType()) {
8751       if (!Result.InvalidBase && !Result.Designator.Invalid &&
8752           !Result.IsNullPtr &&
8753           Info.Ctx.hasSameUnqualifiedType(Result.Designator.getType(Info.Ctx),
8754                                           E->getType()->getPointeeType()) &&
8755           Info.getStdAllocatorCaller("allocate")) {
8756         // Inside a call to std::allocator::allocate and friends, we permit
8757         // casting from void* back to cv1 T* for a pointer that points to a
8758         // cv2 T.
8759       } else {
8760         Result.Designator.setInvalid();
8761         if (SubExpr->getType()->isVoidPointerType())
8762           CCEDiag(E, diag::note_constexpr_invalid_cast)
8763             << 3 << SubExpr->getType();
8764         else
8765           CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8766       }
8767     }
8768     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
8769       ZeroInitialization(E);
8770     return true;
8771 
8772   case CK_DerivedToBase:
8773   case CK_UncheckedDerivedToBase:
8774     if (!evaluatePointer(E->getSubExpr(), Result))
8775       return false;
8776     if (!Result.Base && Result.Offset.isZero())
8777       return true;
8778 
8779     // Now figure out the necessary offset to add to the base LV to get from
8780     // the derived class to the base class.
8781     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
8782                                   castAs<PointerType>()->getPointeeType(),
8783                                 Result);
8784 
8785   case CK_BaseToDerived:
8786     if (!Visit(E->getSubExpr()))
8787       return false;
8788     if (!Result.Base && Result.Offset.isZero())
8789       return true;
8790     return HandleBaseToDerivedCast(Info, E, Result);
8791 
8792   case CK_Dynamic:
8793     if (!Visit(E->getSubExpr()))
8794       return false;
8795     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
8796 
8797   case CK_NullToPointer:
8798     VisitIgnoredValue(E->getSubExpr());
8799     return ZeroInitialization(E);
8800 
8801   case CK_IntegralToPointer: {
8802     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8803 
8804     APValue Value;
8805     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
8806       break;
8807 
8808     if (Value.isInt()) {
8809       unsigned Size = Info.Ctx.getTypeSize(E->getType());
8810       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
8811       Result.Base = (Expr*)nullptr;
8812       Result.InvalidBase = false;
8813       Result.Offset = CharUnits::fromQuantity(N);
8814       Result.Designator.setInvalid();
8815       Result.IsNullPtr = false;
8816       return true;
8817     } else {
8818       // Cast is of an lvalue, no need to change value.
8819       Result.setFrom(Info.Ctx, Value);
8820       return true;
8821     }
8822   }
8823 
8824   case CK_ArrayToPointerDecay: {
8825     if (SubExpr->isGLValue()) {
8826       if (!evaluateLValue(SubExpr, Result))
8827         return false;
8828     } else {
8829       APValue &Value = Info.CurrentCall->createTemporary(
8830           SubExpr, SubExpr->getType(), ScopeKind::FullExpression, Result);
8831       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
8832         return false;
8833     }
8834     // The result is a pointer to the first element of the array.
8835     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
8836     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
8837       Result.addArray(Info, E, CAT);
8838     else
8839       Result.addUnsizedArray(Info, E, AT->getElementType());
8840     return true;
8841   }
8842 
8843   case CK_FunctionToPointerDecay:
8844     return evaluateLValue(SubExpr, Result);
8845 
8846   case CK_LValueToRValue: {
8847     LValue LVal;
8848     if (!evaluateLValue(E->getSubExpr(), LVal))
8849       return false;
8850 
8851     APValue RVal;
8852     // Note, we use the subexpression's type in order to retain cv-qualifiers.
8853     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
8854                                         LVal, RVal))
8855       return InvalidBaseOK &&
8856              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
8857     return Success(RVal, E);
8858   }
8859   }
8860 
8861   return ExprEvaluatorBaseTy::VisitCastExpr(E);
8862 }
8863 
8864 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
8865                                 UnaryExprOrTypeTrait ExprKind) {
8866   // C++ [expr.alignof]p3:
8867   //     When alignof is applied to a reference type, the result is the
8868   //     alignment of the referenced type.
8869   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
8870     T = Ref->getPointeeType();
8871 
8872   if (T.getQualifiers().hasUnaligned())
8873     return CharUnits::One();
8874 
8875   const bool AlignOfReturnsPreferred =
8876       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
8877 
8878   // __alignof is defined to return the preferred alignment.
8879   // Before 8, clang returned the preferred alignment for alignof and _Alignof
8880   // as well.
8881   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
8882     return Info.Ctx.toCharUnitsFromBits(
8883       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
8884   // alignof and _Alignof are defined to return the ABI alignment.
8885   else if (ExprKind == UETT_AlignOf)
8886     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
8887   else
8888     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
8889 }
8890 
8891 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
8892                                 UnaryExprOrTypeTrait ExprKind) {
8893   E = E->IgnoreParens();
8894 
8895   // The kinds of expressions that we have special-case logic here for
8896   // should be kept up to date with the special checks for those
8897   // expressions in Sema.
8898 
8899   // alignof decl is always accepted, even if it doesn't make sense: we default
8900   // to 1 in those cases.
8901   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
8902     return Info.Ctx.getDeclAlign(DRE->getDecl(),
8903                                  /*RefAsPointee*/true);
8904 
8905   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
8906     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
8907                                  /*RefAsPointee*/true);
8908 
8909   return GetAlignOfType(Info, E->getType(), ExprKind);
8910 }
8911 
8912 static CharUnits getBaseAlignment(EvalInfo &Info, const LValue &Value) {
8913   if (const auto *VD = Value.Base.dyn_cast<const ValueDecl *>())
8914     return Info.Ctx.getDeclAlign(VD);
8915   if (const auto *E = Value.Base.dyn_cast<const Expr *>())
8916     return GetAlignOfExpr(Info, E, UETT_AlignOf);
8917   return GetAlignOfType(Info, Value.Base.getTypeInfoType(), UETT_AlignOf);
8918 }
8919 
8920 /// Evaluate the value of the alignment argument to __builtin_align_{up,down},
8921 /// __builtin_is_aligned and __builtin_assume_aligned.
8922 static bool getAlignmentArgument(const Expr *E, QualType ForType,
8923                                  EvalInfo &Info, APSInt &Alignment) {
8924   if (!EvaluateInteger(E, Alignment, Info))
8925     return false;
8926   if (Alignment < 0 || !Alignment.isPowerOf2()) {
8927     Info.FFDiag(E, diag::note_constexpr_invalid_alignment) << Alignment;
8928     return false;
8929   }
8930   unsigned SrcWidth = Info.Ctx.getIntWidth(ForType);
8931   APSInt MaxValue(APInt::getOneBitSet(SrcWidth, SrcWidth - 1));
8932   if (APSInt::compareValues(Alignment, MaxValue) > 0) {
8933     Info.FFDiag(E, diag::note_constexpr_alignment_too_big)
8934         << MaxValue << ForType << Alignment;
8935     return false;
8936   }
8937   // Ensure both alignment and source value have the same bit width so that we
8938   // don't assert when computing the resulting value.
8939   APSInt ExtAlignment =
8940       APSInt(Alignment.zextOrTrunc(SrcWidth), /*isUnsigned=*/true);
8941   assert(APSInt::compareValues(Alignment, ExtAlignment) == 0 &&
8942          "Alignment should not be changed by ext/trunc");
8943   Alignment = ExtAlignment;
8944   assert(Alignment.getBitWidth() == SrcWidth);
8945   return true;
8946 }
8947 
8948 // To be clear: this happily visits unsupported builtins. Better name welcomed.
8949 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
8950   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
8951     return true;
8952 
8953   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
8954     return false;
8955 
8956   Result.setInvalid(E);
8957   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
8958   Result.addUnsizedArray(Info, E, PointeeTy);
8959   return true;
8960 }
8961 
8962 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
8963   if (IsStringLiteralCall(E))
8964     return Success(E);
8965 
8966   if (unsigned BuiltinOp = E->getBuiltinCallee())
8967     return VisitBuiltinCallExpr(E, BuiltinOp);
8968 
8969   return visitNonBuiltinCallExpr(E);
8970 }
8971 
8972 // Determine if T is a character type for which we guarantee that
8973 // sizeof(T) == 1.
8974 static bool isOneByteCharacterType(QualType T) {
8975   return T->isCharType() || T->isChar8Type();
8976 }
8977 
8978 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8979                                                 unsigned BuiltinOp) {
8980   switch (BuiltinOp) {
8981   case Builtin::BI__builtin_addressof:
8982     return evaluateLValue(E->getArg(0), Result);
8983   case Builtin::BI__builtin_assume_aligned: {
8984     // We need to be very careful here because: if the pointer does not have the
8985     // asserted alignment, then the behavior is undefined, and undefined
8986     // behavior is non-constant.
8987     if (!evaluatePointer(E->getArg(0), Result))
8988       return false;
8989 
8990     LValue OffsetResult(Result);
8991     APSInt Alignment;
8992     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
8993                               Alignment))
8994       return false;
8995     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
8996 
8997     if (E->getNumArgs() > 2) {
8998       APSInt Offset;
8999       if (!EvaluateInteger(E->getArg(2), Offset, Info))
9000         return false;
9001 
9002       int64_t AdditionalOffset = -Offset.getZExtValue();
9003       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
9004     }
9005 
9006     // If there is a base object, then it must have the correct alignment.
9007     if (OffsetResult.Base) {
9008       CharUnits BaseAlignment = getBaseAlignment(Info, OffsetResult);
9009 
9010       if (BaseAlignment < Align) {
9011         Result.Designator.setInvalid();
9012         // FIXME: Add support to Diagnostic for long / long long.
9013         CCEDiag(E->getArg(0),
9014                 diag::note_constexpr_baa_insufficient_alignment) << 0
9015           << (unsigned)BaseAlignment.getQuantity()
9016           << (unsigned)Align.getQuantity();
9017         return false;
9018       }
9019     }
9020 
9021     // The offset must also have the correct alignment.
9022     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
9023       Result.Designator.setInvalid();
9024 
9025       (OffsetResult.Base
9026            ? CCEDiag(E->getArg(0),
9027                      diag::note_constexpr_baa_insufficient_alignment) << 1
9028            : CCEDiag(E->getArg(0),
9029                      diag::note_constexpr_baa_value_insufficient_alignment))
9030         << (int)OffsetResult.Offset.getQuantity()
9031         << (unsigned)Align.getQuantity();
9032       return false;
9033     }
9034 
9035     return true;
9036   }
9037   case Builtin::BI__builtin_align_up:
9038   case Builtin::BI__builtin_align_down: {
9039     if (!evaluatePointer(E->getArg(0), Result))
9040       return false;
9041     APSInt Alignment;
9042     if (!getAlignmentArgument(E->getArg(1), E->getArg(0)->getType(), Info,
9043                               Alignment))
9044       return false;
9045     CharUnits BaseAlignment = getBaseAlignment(Info, Result);
9046     CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Result.Offset);
9047     // For align_up/align_down, we can return the same value if the alignment
9048     // is known to be greater or equal to the requested value.
9049     if (PtrAlign.getQuantity() >= Alignment)
9050       return true;
9051 
9052     // The alignment could be greater than the minimum at run-time, so we cannot
9053     // infer much about the resulting pointer value. One case is possible:
9054     // For `_Alignas(32) char buf[N]; __builtin_align_down(&buf[idx], 32)` we
9055     // can infer the correct index if the requested alignment is smaller than
9056     // the base alignment so we can perform the computation on the offset.
9057     if (BaseAlignment.getQuantity() >= Alignment) {
9058       assert(Alignment.getBitWidth() <= 64 &&
9059              "Cannot handle > 64-bit address-space");
9060       uint64_t Alignment64 = Alignment.getZExtValue();
9061       CharUnits NewOffset = CharUnits::fromQuantity(
9062           BuiltinOp == Builtin::BI__builtin_align_down
9063               ? llvm::alignDown(Result.Offset.getQuantity(), Alignment64)
9064               : llvm::alignTo(Result.Offset.getQuantity(), Alignment64));
9065       Result.adjustOffset(NewOffset - Result.Offset);
9066       // TODO: diagnose out-of-bounds values/only allow for arrays?
9067       return true;
9068     }
9069     // Otherwise, we cannot constant-evaluate the result.
9070     Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_adjust)
9071         << Alignment;
9072     return false;
9073   }
9074   case Builtin::BI__builtin_operator_new:
9075     return HandleOperatorNewCall(Info, E, Result);
9076   case Builtin::BI__builtin_launder:
9077     return evaluatePointer(E->getArg(0), Result);
9078   case Builtin::BIstrchr:
9079   case Builtin::BIwcschr:
9080   case Builtin::BImemchr:
9081   case Builtin::BIwmemchr:
9082     if (Info.getLangOpts().CPlusPlus11)
9083       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9084         << /*isConstexpr*/0 << /*isConstructor*/0
9085         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9086     else
9087       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9088     LLVM_FALLTHROUGH;
9089   case Builtin::BI__builtin_strchr:
9090   case Builtin::BI__builtin_wcschr:
9091   case Builtin::BI__builtin_memchr:
9092   case Builtin::BI__builtin_char_memchr:
9093   case Builtin::BI__builtin_wmemchr: {
9094     if (!Visit(E->getArg(0)))
9095       return false;
9096     APSInt Desired;
9097     if (!EvaluateInteger(E->getArg(1), Desired, Info))
9098       return false;
9099     uint64_t MaxLength = uint64_t(-1);
9100     if (BuiltinOp != Builtin::BIstrchr &&
9101         BuiltinOp != Builtin::BIwcschr &&
9102         BuiltinOp != Builtin::BI__builtin_strchr &&
9103         BuiltinOp != Builtin::BI__builtin_wcschr) {
9104       APSInt N;
9105       if (!EvaluateInteger(E->getArg(2), N, Info))
9106         return false;
9107       MaxLength = N.getExtValue();
9108     }
9109     // We cannot find the value if there are no candidates to match against.
9110     if (MaxLength == 0u)
9111       return ZeroInitialization(E);
9112     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9113         Result.Designator.Invalid)
9114       return false;
9115     QualType CharTy = Result.Designator.getType(Info.Ctx);
9116     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
9117                      BuiltinOp == Builtin::BI__builtin_memchr;
9118     assert(IsRawByte ||
9119            Info.Ctx.hasSameUnqualifiedType(
9120                CharTy, E->getArg(0)->getType()->getPointeeType()));
9121     // Pointers to const void may point to objects of incomplete type.
9122     if (IsRawByte && CharTy->isIncompleteType()) {
9123       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
9124       return false;
9125     }
9126     // Give up on byte-oriented matching against multibyte elements.
9127     // FIXME: We can compare the bytes in the correct order.
9128     if (IsRawByte && !isOneByteCharacterType(CharTy)) {
9129       Info.FFDiag(E, diag::note_constexpr_memchr_unsupported)
9130           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
9131           << CharTy;
9132       return false;
9133     }
9134     // Figure out what value we're actually looking for (after converting to
9135     // the corresponding unsigned type if necessary).
9136     uint64_t DesiredVal;
9137     bool StopAtNull = false;
9138     switch (BuiltinOp) {
9139     case Builtin::BIstrchr:
9140     case Builtin::BI__builtin_strchr:
9141       // strchr compares directly to the passed integer, and therefore
9142       // always fails if given an int that is not a char.
9143       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
9144                                                   E->getArg(1)->getType(),
9145                                                   Desired),
9146                                Desired))
9147         return ZeroInitialization(E);
9148       StopAtNull = true;
9149       LLVM_FALLTHROUGH;
9150     case Builtin::BImemchr:
9151     case Builtin::BI__builtin_memchr:
9152     case Builtin::BI__builtin_char_memchr:
9153       // memchr compares by converting both sides to unsigned char. That's also
9154       // correct for strchr if we get this far (to cope with plain char being
9155       // unsigned in the strchr case).
9156       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
9157       break;
9158 
9159     case Builtin::BIwcschr:
9160     case Builtin::BI__builtin_wcschr:
9161       StopAtNull = true;
9162       LLVM_FALLTHROUGH;
9163     case Builtin::BIwmemchr:
9164     case Builtin::BI__builtin_wmemchr:
9165       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
9166       DesiredVal = Desired.getZExtValue();
9167       break;
9168     }
9169 
9170     for (; MaxLength; --MaxLength) {
9171       APValue Char;
9172       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
9173           !Char.isInt())
9174         return false;
9175       if (Char.getInt().getZExtValue() == DesiredVal)
9176         return true;
9177       if (StopAtNull && !Char.getInt())
9178         break;
9179       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
9180         return false;
9181     }
9182     // Not found: return nullptr.
9183     return ZeroInitialization(E);
9184   }
9185 
9186   case Builtin::BImemcpy:
9187   case Builtin::BImemmove:
9188   case Builtin::BIwmemcpy:
9189   case Builtin::BIwmemmove:
9190     if (Info.getLangOpts().CPlusPlus11)
9191       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9192         << /*isConstexpr*/0 << /*isConstructor*/0
9193         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9194     else
9195       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9196     LLVM_FALLTHROUGH;
9197   case Builtin::BI__builtin_memcpy:
9198   case Builtin::BI__builtin_memmove:
9199   case Builtin::BI__builtin_wmemcpy:
9200   case Builtin::BI__builtin_wmemmove: {
9201     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
9202                  BuiltinOp == Builtin::BIwmemmove ||
9203                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
9204                  BuiltinOp == Builtin::BI__builtin_wmemmove;
9205     bool Move = BuiltinOp == Builtin::BImemmove ||
9206                 BuiltinOp == Builtin::BIwmemmove ||
9207                 BuiltinOp == Builtin::BI__builtin_memmove ||
9208                 BuiltinOp == Builtin::BI__builtin_wmemmove;
9209 
9210     // The result of mem* is the first argument.
9211     if (!Visit(E->getArg(0)))
9212       return false;
9213     LValue Dest = Result;
9214 
9215     LValue Src;
9216     if (!EvaluatePointer(E->getArg(1), Src, Info))
9217       return false;
9218 
9219     APSInt N;
9220     if (!EvaluateInteger(E->getArg(2), N, Info))
9221       return false;
9222     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
9223 
9224     // If the size is zero, we treat this as always being a valid no-op.
9225     // (Even if one of the src and dest pointers is null.)
9226     if (!N)
9227       return true;
9228 
9229     // Otherwise, if either of the operands is null, we can't proceed. Don't
9230     // try to determine the type of the copied objects, because there aren't
9231     // any.
9232     if (!Src.Base || !Dest.Base) {
9233       APValue Val;
9234       (!Src.Base ? Src : Dest).moveInto(Val);
9235       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
9236           << Move << WChar << !!Src.Base
9237           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
9238       return false;
9239     }
9240     if (Src.Designator.Invalid || Dest.Designator.Invalid)
9241       return false;
9242 
9243     // We require that Src and Dest are both pointers to arrays of
9244     // trivially-copyable type. (For the wide version, the designator will be
9245     // invalid if the designated object is not a wchar_t.)
9246     QualType T = Dest.Designator.getType(Info.Ctx);
9247     QualType SrcT = Src.Designator.getType(Info.Ctx);
9248     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
9249       // FIXME: Consider using our bit_cast implementation to support this.
9250       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
9251       return false;
9252     }
9253     if (T->isIncompleteType()) {
9254       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
9255       return false;
9256     }
9257     if (!T.isTriviallyCopyableType(Info.Ctx)) {
9258       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
9259       return false;
9260     }
9261 
9262     // Figure out how many T's we're copying.
9263     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
9264     if (!WChar) {
9265       uint64_t Remainder;
9266       llvm::APInt OrigN = N;
9267       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
9268       if (Remainder) {
9269         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9270             << Move << WChar << 0 << T << toString(OrigN, 10, /*Signed*/false)
9271             << (unsigned)TSize;
9272         return false;
9273       }
9274     }
9275 
9276     // Check that the copying will remain within the arrays, just so that we
9277     // can give a more meaningful diagnostic. This implicitly also checks that
9278     // N fits into 64 bits.
9279     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
9280     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
9281     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
9282       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
9283           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
9284           << toString(N, 10, /*Signed*/false);
9285       return false;
9286     }
9287     uint64_t NElems = N.getZExtValue();
9288     uint64_t NBytes = NElems * TSize;
9289 
9290     // Check for overlap.
9291     int Direction = 1;
9292     if (HasSameBase(Src, Dest)) {
9293       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
9294       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
9295       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
9296         // Dest is inside the source region.
9297         if (!Move) {
9298           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9299           return false;
9300         }
9301         // For memmove and friends, copy backwards.
9302         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
9303             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
9304           return false;
9305         Direction = -1;
9306       } else if (!Move && SrcOffset >= DestOffset &&
9307                  SrcOffset - DestOffset < NBytes) {
9308         // Src is inside the destination region for memcpy: invalid.
9309         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
9310         return false;
9311       }
9312     }
9313 
9314     while (true) {
9315       APValue Val;
9316       // FIXME: Set WantObjectRepresentation to true if we're copying a
9317       // char-like type?
9318       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
9319           !handleAssignment(Info, E, Dest, T, Val))
9320         return false;
9321       // Do not iterate past the last element; if we're copying backwards, that
9322       // might take us off the start of the array.
9323       if (--NElems == 0)
9324         return true;
9325       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
9326           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
9327         return false;
9328     }
9329   }
9330 
9331   default:
9332     break;
9333   }
9334 
9335   return visitNonBuiltinCallExpr(E);
9336 }
9337 
9338 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
9339                                      APValue &Result, const InitListExpr *ILE,
9340                                      QualType AllocType);
9341 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
9342                                           APValue &Result,
9343                                           const CXXConstructExpr *CCE,
9344                                           QualType AllocType);
9345 
9346 bool PointerExprEvaluator::VisitCXXNewExpr(const CXXNewExpr *E) {
9347   if (!Info.getLangOpts().CPlusPlus20)
9348     Info.CCEDiag(E, diag::note_constexpr_new);
9349 
9350   // We cannot speculatively evaluate a delete expression.
9351   if (Info.SpeculativeEvaluationDepth)
9352     return false;
9353 
9354   FunctionDecl *OperatorNew = E->getOperatorNew();
9355 
9356   bool IsNothrow = false;
9357   bool IsPlacement = false;
9358   if (OperatorNew->isReservedGlobalPlacementOperator() &&
9359       Info.CurrentCall->isStdFunction() && !E->isArray()) {
9360     // FIXME Support array placement new.
9361     assert(E->getNumPlacementArgs() == 1);
9362     if (!EvaluatePointer(E->getPlacementArg(0), Result, Info))
9363       return false;
9364     if (Result.Designator.Invalid)
9365       return false;
9366     IsPlacement = true;
9367   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction()) {
9368     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
9369         << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
9370     return false;
9371   } else if (E->getNumPlacementArgs()) {
9372     // The only new-placement list we support is of the form (std::nothrow).
9373     //
9374     // FIXME: There is no restriction on this, but it's not clear that any
9375     // other form makes any sense. We get here for cases such as:
9376     //
9377     //   new (std::align_val_t{N}) X(int)
9378     //
9379     // (which should presumably be valid only if N is a multiple of
9380     // alignof(int), and in any case can't be deallocated unless N is
9381     // alignof(X) and X has new-extended alignment).
9382     if (E->getNumPlacementArgs() != 1 ||
9383         !E->getPlacementArg(0)->getType()->isNothrowT())
9384       return Error(E, diag::note_constexpr_new_placement);
9385 
9386     LValue Nothrow;
9387     if (!EvaluateLValue(E->getPlacementArg(0), Nothrow, Info))
9388       return false;
9389     IsNothrow = true;
9390   }
9391 
9392   const Expr *Init = E->getInitializer();
9393   const InitListExpr *ResizedArrayILE = nullptr;
9394   const CXXConstructExpr *ResizedArrayCCE = nullptr;
9395   bool ValueInit = false;
9396 
9397   QualType AllocType = E->getAllocatedType();
9398   if (Optional<const Expr*> ArraySize = E->getArraySize()) {
9399     const Expr *Stripped = *ArraySize;
9400     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
9401          Stripped = ICE->getSubExpr())
9402       if (ICE->getCastKind() != CK_NoOp &&
9403           ICE->getCastKind() != CK_IntegralCast)
9404         break;
9405 
9406     llvm::APSInt ArrayBound;
9407     if (!EvaluateInteger(Stripped, ArrayBound, Info))
9408       return false;
9409 
9410     // C++ [expr.new]p9:
9411     //   The expression is erroneous if:
9412     //   -- [...] its value before converting to size_t [or] applying the
9413     //      second standard conversion sequence is less than zero
9414     if (ArrayBound.isSigned() && ArrayBound.isNegative()) {
9415       if (IsNothrow)
9416         return ZeroInitialization(E);
9417 
9418       Info.FFDiag(*ArraySize, diag::note_constexpr_new_negative)
9419           << ArrayBound << (*ArraySize)->getSourceRange();
9420       return false;
9421     }
9422 
9423     //   -- its value is such that the size of the allocated object would
9424     //      exceed the implementation-defined limit
9425     if (ConstantArrayType::getNumAddressingBits(Info.Ctx, AllocType,
9426                                                 ArrayBound) >
9427         ConstantArrayType::getMaxSizeBits(Info.Ctx)) {
9428       if (IsNothrow)
9429         return ZeroInitialization(E);
9430 
9431       Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_large)
9432         << ArrayBound << (*ArraySize)->getSourceRange();
9433       return false;
9434     }
9435 
9436     //   -- the new-initializer is a braced-init-list and the number of
9437     //      array elements for which initializers are provided [...]
9438     //      exceeds the number of elements to initialize
9439     if (!Init) {
9440       // No initialization is performed.
9441     } else if (isa<CXXScalarValueInitExpr>(Init) ||
9442                isa<ImplicitValueInitExpr>(Init)) {
9443       ValueInit = true;
9444     } else if (auto *CCE = dyn_cast<CXXConstructExpr>(Init)) {
9445       ResizedArrayCCE = CCE;
9446     } else {
9447       auto *CAT = Info.Ctx.getAsConstantArrayType(Init->getType());
9448       assert(CAT && "unexpected type for array initializer");
9449 
9450       unsigned Bits =
9451           std::max(CAT->getSize().getBitWidth(), ArrayBound.getBitWidth());
9452       llvm::APInt InitBound = CAT->getSize().zextOrSelf(Bits);
9453       llvm::APInt AllocBound = ArrayBound.zextOrSelf(Bits);
9454       if (InitBound.ugt(AllocBound)) {
9455         if (IsNothrow)
9456           return ZeroInitialization(E);
9457 
9458         Info.FFDiag(*ArraySize, diag::note_constexpr_new_too_small)
9459             << toString(AllocBound, 10, /*Signed=*/false)
9460             << toString(InitBound, 10, /*Signed=*/false)
9461             << (*ArraySize)->getSourceRange();
9462         return false;
9463       }
9464 
9465       // If the sizes differ, we must have an initializer list, and we need
9466       // special handling for this case when we initialize.
9467       if (InitBound != AllocBound)
9468         ResizedArrayILE = cast<InitListExpr>(Init);
9469     }
9470 
9471     AllocType = Info.Ctx.getConstantArrayType(AllocType, ArrayBound, nullptr,
9472                                               ArrayType::Normal, 0);
9473   } else {
9474     assert(!AllocType->isArrayType() &&
9475            "array allocation with non-array new");
9476   }
9477 
9478   APValue *Val;
9479   if (IsPlacement) {
9480     AccessKinds AK = AK_Construct;
9481     struct FindObjectHandler {
9482       EvalInfo &Info;
9483       const Expr *E;
9484       QualType AllocType;
9485       const AccessKinds AccessKind;
9486       APValue *Value;
9487 
9488       typedef bool result_type;
9489       bool failed() { return false; }
9490       bool found(APValue &Subobj, QualType SubobjType) {
9491         // FIXME: Reject the cases where [basic.life]p8 would not permit the
9492         // old name of the object to be used to name the new object.
9493         if (!Info.Ctx.hasSameUnqualifiedType(SubobjType, AllocType)) {
9494           Info.FFDiag(E, diag::note_constexpr_placement_new_wrong_type) <<
9495             SubobjType << AllocType;
9496           return false;
9497         }
9498         Value = &Subobj;
9499         return true;
9500       }
9501       bool found(APSInt &Value, QualType SubobjType) {
9502         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9503         return false;
9504       }
9505       bool found(APFloat &Value, QualType SubobjType) {
9506         Info.FFDiag(E, diag::note_constexpr_construct_complex_elem);
9507         return false;
9508       }
9509     } Handler = {Info, E, AllocType, AK, nullptr};
9510 
9511     CompleteObject Obj = findCompleteObject(Info, E, AK, Result, AllocType);
9512     if (!Obj || !findSubobject(Info, E, Obj, Result.Designator, Handler))
9513       return false;
9514 
9515     Val = Handler.Value;
9516 
9517     // [basic.life]p1:
9518     //   The lifetime of an object o of type T ends when [...] the storage
9519     //   which the object occupies is [...] reused by an object that is not
9520     //   nested within o (6.6.2).
9521     *Val = APValue();
9522   } else {
9523     // Perform the allocation and obtain a pointer to the resulting object.
9524     Val = Info.createHeapAlloc(E, AllocType, Result);
9525     if (!Val)
9526       return false;
9527   }
9528 
9529   if (ValueInit) {
9530     ImplicitValueInitExpr VIE(AllocType);
9531     if (!EvaluateInPlace(*Val, Info, Result, &VIE))
9532       return false;
9533   } else if (ResizedArrayILE) {
9534     if (!EvaluateArrayNewInitList(Info, Result, *Val, ResizedArrayILE,
9535                                   AllocType))
9536       return false;
9537   } else if (ResizedArrayCCE) {
9538     if (!EvaluateArrayNewConstructExpr(Info, Result, *Val, ResizedArrayCCE,
9539                                        AllocType))
9540       return false;
9541   } else if (Init) {
9542     if (!EvaluateInPlace(*Val, Info, Result, Init))
9543       return false;
9544   } else if (!getDefaultInitValue(AllocType, *Val)) {
9545     return false;
9546   }
9547 
9548   // Array new returns a pointer to the first element, not a pointer to the
9549   // array.
9550   if (auto *AT = AllocType->getAsArrayTypeUnsafe())
9551     Result.addArray(Info, E, cast<ConstantArrayType>(AT));
9552 
9553   return true;
9554 }
9555 //===----------------------------------------------------------------------===//
9556 // Member Pointer Evaluation
9557 //===----------------------------------------------------------------------===//
9558 
9559 namespace {
9560 class MemberPointerExprEvaluator
9561   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
9562   MemberPtr &Result;
9563 
9564   bool Success(const ValueDecl *D) {
9565     Result = MemberPtr(D);
9566     return true;
9567   }
9568 public:
9569 
9570   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
9571     : ExprEvaluatorBaseTy(Info), Result(Result) {}
9572 
9573   bool Success(const APValue &V, const Expr *E) {
9574     Result.setFrom(V);
9575     return true;
9576   }
9577   bool ZeroInitialization(const Expr *E) {
9578     return Success((const ValueDecl*)nullptr);
9579   }
9580 
9581   bool VisitCastExpr(const CastExpr *E);
9582   bool VisitUnaryAddrOf(const UnaryOperator *E);
9583 };
9584 } // end anonymous namespace
9585 
9586 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
9587                                   EvalInfo &Info) {
9588   assert(!E->isValueDependent());
9589   assert(E->isPRValue() && E->getType()->isMemberPointerType());
9590   return MemberPointerExprEvaluator(Info, Result).Visit(E);
9591 }
9592 
9593 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
9594   switch (E->getCastKind()) {
9595   default:
9596     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9597 
9598   case CK_NullToMemberPointer:
9599     VisitIgnoredValue(E->getSubExpr());
9600     return ZeroInitialization(E);
9601 
9602   case CK_BaseToDerivedMemberPointer: {
9603     if (!Visit(E->getSubExpr()))
9604       return false;
9605     if (E->path_empty())
9606       return true;
9607     // Base-to-derived member pointer casts store the path in derived-to-base
9608     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
9609     // the wrong end of the derived->base arc, so stagger the path by one class.
9610     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
9611     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
9612          PathI != PathE; ++PathI) {
9613       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9614       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
9615       if (!Result.castToDerived(Derived))
9616         return Error(E);
9617     }
9618     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
9619     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
9620       return Error(E);
9621     return true;
9622   }
9623 
9624   case CK_DerivedToBaseMemberPointer:
9625     if (!Visit(E->getSubExpr()))
9626       return false;
9627     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9628          PathE = E->path_end(); PathI != PathE; ++PathI) {
9629       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
9630       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9631       if (!Result.castToBase(Base))
9632         return Error(E);
9633     }
9634     return true;
9635   }
9636 }
9637 
9638 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
9639   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
9640   // member can be formed.
9641   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
9642 }
9643 
9644 //===----------------------------------------------------------------------===//
9645 // Record Evaluation
9646 //===----------------------------------------------------------------------===//
9647 
9648 namespace {
9649   class RecordExprEvaluator
9650   : public ExprEvaluatorBase<RecordExprEvaluator> {
9651     const LValue &This;
9652     APValue &Result;
9653   public:
9654 
9655     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
9656       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
9657 
9658     bool Success(const APValue &V, const Expr *E) {
9659       Result = V;
9660       return true;
9661     }
9662     bool ZeroInitialization(const Expr *E) {
9663       return ZeroInitialization(E, E->getType());
9664     }
9665     bool ZeroInitialization(const Expr *E, QualType T);
9666 
9667     bool VisitCallExpr(const CallExpr *E) {
9668       return handleCallExpr(E, Result, &This);
9669     }
9670     bool VisitCastExpr(const CastExpr *E);
9671     bool VisitInitListExpr(const InitListExpr *E);
9672     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
9673       return VisitCXXConstructExpr(E, E->getType());
9674     }
9675     bool VisitLambdaExpr(const LambdaExpr *E);
9676     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
9677     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
9678     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
9679     bool VisitBinCmp(const BinaryOperator *E);
9680   };
9681 }
9682 
9683 /// Perform zero-initialization on an object of non-union class type.
9684 /// C++11 [dcl.init]p5:
9685 ///  To zero-initialize an object or reference of type T means:
9686 ///    [...]
9687 ///    -- if T is a (possibly cv-qualified) non-union class type,
9688 ///       each non-static data member and each base-class subobject is
9689 ///       zero-initialized
9690 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
9691                                           const RecordDecl *RD,
9692                                           const LValue &This, APValue &Result) {
9693   assert(!RD->isUnion() && "Expected non-union class type");
9694   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
9695   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
9696                    std::distance(RD->field_begin(), RD->field_end()));
9697 
9698   if (RD->isInvalidDecl()) return false;
9699   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9700 
9701   if (CD) {
9702     unsigned Index = 0;
9703     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
9704            End = CD->bases_end(); I != End; ++I, ++Index) {
9705       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
9706       LValue Subobject = This;
9707       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
9708         return false;
9709       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
9710                                          Result.getStructBase(Index)))
9711         return false;
9712     }
9713   }
9714 
9715   for (const auto *I : RD->fields()) {
9716     // -- if T is a reference type, no initialization is performed.
9717     if (I->isUnnamedBitfield() || I->getType()->isReferenceType())
9718       continue;
9719 
9720     LValue Subobject = This;
9721     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
9722       return false;
9723 
9724     ImplicitValueInitExpr VIE(I->getType());
9725     if (!EvaluateInPlace(
9726           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
9727       return false;
9728   }
9729 
9730   return true;
9731 }
9732 
9733 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
9734   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
9735   if (RD->isInvalidDecl()) return false;
9736   if (RD->isUnion()) {
9737     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
9738     // object's first non-static named data member is zero-initialized
9739     RecordDecl::field_iterator I = RD->field_begin();
9740     while (I != RD->field_end() && (*I)->isUnnamedBitfield())
9741       ++I;
9742     if (I == RD->field_end()) {
9743       Result = APValue((const FieldDecl*)nullptr);
9744       return true;
9745     }
9746 
9747     LValue Subobject = This;
9748     if (!HandleLValueMember(Info, E, Subobject, *I))
9749       return false;
9750     Result = APValue(*I);
9751     ImplicitValueInitExpr VIE(I->getType());
9752     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
9753   }
9754 
9755   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
9756     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
9757     return false;
9758   }
9759 
9760   return HandleClassZeroInitialization(Info, E, RD, This, Result);
9761 }
9762 
9763 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
9764   switch (E->getCastKind()) {
9765   default:
9766     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9767 
9768   case CK_ConstructorConversion:
9769     return Visit(E->getSubExpr());
9770 
9771   case CK_DerivedToBase:
9772   case CK_UncheckedDerivedToBase: {
9773     APValue DerivedObject;
9774     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
9775       return false;
9776     if (!DerivedObject.isStruct())
9777       return Error(E->getSubExpr());
9778 
9779     // Derived-to-base rvalue conversion: just slice off the derived part.
9780     APValue *Value = &DerivedObject;
9781     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
9782     for (CastExpr::path_const_iterator PathI = E->path_begin(),
9783          PathE = E->path_end(); PathI != PathE; ++PathI) {
9784       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
9785       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
9786       Value = &Value->getStructBase(getBaseIndex(RD, Base));
9787       RD = Base;
9788     }
9789     Result = *Value;
9790     return true;
9791   }
9792   }
9793 }
9794 
9795 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9796   if (E->isTransparent())
9797     return Visit(E->getInit(0));
9798 
9799   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
9800   if (RD->isInvalidDecl()) return false;
9801   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
9802   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
9803 
9804   EvalInfo::EvaluatingConstructorRAII EvalObj(
9805       Info,
9806       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
9807       CXXRD && CXXRD->getNumBases());
9808 
9809   if (RD->isUnion()) {
9810     const FieldDecl *Field = E->getInitializedFieldInUnion();
9811     Result = APValue(Field);
9812     if (!Field)
9813       return true;
9814 
9815     // If the initializer list for a union does not contain any elements, the
9816     // first element of the union is value-initialized.
9817     // FIXME: The element should be initialized from an initializer list.
9818     //        Is this difference ever observable for initializer lists which
9819     //        we don't build?
9820     ImplicitValueInitExpr VIE(Field->getType());
9821     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
9822 
9823     LValue Subobject = This;
9824     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
9825       return false;
9826 
9827     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9828     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9829                                   isa<CXXDefaultInitExpr>(InitExpr));
9830 
9831     if (EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr)) {
9832       if (Field->isBitField())
9833         return truncateBitfieldValue(Info, InitExpr, Result.getUnionValue(),
9834                                      Field);
9835       return true;
9836     }
9837 
9838     return false;
9839   }
9840 
9841   if (!Result.hasValue())
9842     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
9843                      std::distance(RD->field_begin(), RD->field_end()));
9844   unsigned ElementNo = 0;
9845   bool Success = true;
9846 
9847   // Initialize base classes.
9848   if (CXXRD && CXXRD->getNumBases()) {
9849     for (const auto &Base : CXXRD->bases()) {
9850       assert(ElementNo < E->getNumInits() && "missing init for base class");
9851       const Expr *Init = E->getInit(ElementNo);
9852 
9853       LValue Subobject = This;
9854       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
9855         return false;
9856 
9857       APValue &FieldVal = Result.getStructBase(ElementNo);
9858       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
9859         if (!Info.noteFailure())
9860           return false;
9861         Success = false;
9862       }
9863       ++ElementNo;
9864     }
9865 
9866     EvalObj.finishedConstructingBases();
9867   }
9868 
9869   // Initialize members.
9870   for (const auto *Field : RD->fields()) {
9871     // Anonymous bit-fields are not considered members of the class for
9872     // purposes of aggregate initialization.
9873     if (Field->isUnnamedBitfield())
9874       continue;
9875 
9876     LValue Subobject = This;
9877 
9878     bool HaveInit = ElementNo < E->getNumInits();
9879 
9880     // FIXME: Diagnostics here should point to the end of the initializer
9881     // list, not the start.
9882     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
9883                             Subobject, Field, &Layout))
9884       return false;
9885 
9886     // Perform an implicit value-initialization for members beyond the end of
9887     // the initializer list.
9888     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
9889     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
9890 
9891     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
9892     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
9893                                   isa<CXXDefaultInitExpr>(Init));
9894 
9895     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
9896     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
9897         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
9898                                                        FieldVal, Field))) {
9899       if (!Info.noteFailure())
9900         return false;
9901       Success = false;
9902     }
9903   }
9904 
9905   EvalObj.finishedConstructingFields();
9906 
9907   return Success;
9908 }
9909 
9910 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
9911                                                 QualType T) {
9912   // Note that E's type is not necessarily the type of our class here; we might
9913   // be initializing an array element instead.
9914   const CXXConstructorDecl *FD = E->getConstructor();
9915   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
9916 
9917   bool ZeroInit = E->requiresZeroInitialization();
9918   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
9919     // If we've already performed zero-initialization, we're already done.
9920     if (Result.hasValue())
9921       return true;
9922 
9923     if (ZeroInit)
9924       return ZeroInitialization(E, T);
9925 
9926     return getDefaultInitValue(T, Result);
9927   }
9928 
9929   const FunctionDecl *Definition = nullptr;
9930   auto Body = FD->getBody(Definition);
9931 
9932   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9933     return false;
9934 
9935   // Avoid materializing a temporary for an elidable copy/move constructor.
9936   if (E->isElidable() && !ZeroInit) {
9937     // FIXME: This only handles the simplest case, where the source object
9938     //        is passed directly as the first argument to the constructor.
9939     //        This should also handle stepping though implicit casts and
9940     //        and conversion sequences which involve two steps, with a
9941     //        conversion operator followed by a converting constructor.
9942     const Expr *SrcObj = E->getArg(0);
9943     assert(SrcObj->isTemporaryObject(Info.Ctx, FD->getParent()));
9944     assert(Info.Ctx.hasSameUnqualifiedType(E->getType(), SrcObj->getType()));
9945     if (const MaterializeTemporaryExpr *ME =
9946             dyn_cast<MaterializeTemporaryExpr>(SrcObj))
9947       return Visit(ME->getSubExpr());
9948   }
9949 
9950   if (ZeroInit && !ZeroInitialization(E, T))
9951     return false;
9952 
9953   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
9954   return HandleConstructorCall(E, This, Args,
9955                                cast<CXXConstructorDecl>(Definition), Info,
9956                                Result);
9957 }
9958 
9959 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
9960     const CXXInheritedCtorInitExpr *E) {
9961   if (!Info.CurrentCall) {
9962     assert(Info.checkingPotentialConstantExpression());
9963     return false;
9964   }
9965 
9966   const CXXConstructorDecl *FD = E->getConstructor();
9967   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
9968     return false;
9969 
9970   const FunctionDecl *Definition = nullptr;
9971   auto Body = FD->getBody(Definition);
9972 
9973   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
9974     return false;
9975 
9976   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
9977                                cast<CXXConstructorDecl>(Definition), Info,
9978                                Result);
9979 }
9980 
9981 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
9982     const CXXStdInitializerListExpr *E) {
9983   const ConstantArrayType *ArrayType =
9984       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
9985 
9986   LValue Array;
9987   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
9988     return false;
9989 
9990   // Get a pointer to the first element of the array.
9991   Array.addArray(Info, E, ArrayType);
9992 
9993   auto InvalidType = [&] {
9994     Info.FFDiag(E, diag::note_constexpr_unsupported_layout)
9995       << E->getType();
9996     return false;
9997   };
9998 
9999   // FIXME: Perform the checks on the field types in SemaInit.
10000   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
10001   RecordDecl::field_iterator Field = Record->field_begin();
10002   if (Field == Record->field_end())
10003     return InvalidType();
10004 
10005   // Start pointer.
10006   if (!Field->getType()->isPointerType() ||
10007       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10008                             ArrayType->getElementType()))
10009     return InvalidType();
10010 
10011   // FIXME: What if the initializer_list type has base classes, etc?
10012   Result = APValue(APValue::UninitStruct(), 0, 2);
10013   Array.moveInto(Result.getStructField(0));
10014 
10015   if (++Field == Record->field_end())
10016     return InvalidType();
10017 
10018   if (Field->getType()->isPointerType() &&
10019       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
10020                            ArrayType->getElementType())) {
10021     // End pointer.
10022     if (!HandleLValueArrayAdjustment(Info, E, Array,
10023                                      ArrayType->getElementType(),
10024                                      ArrayType->getSize().getZExtValue()))
10025       return false;
10026     Array.moveInto(Result.getStructField(1));
10027   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
10028     // Length.
10029     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
10030   else
10031     return InvalidType();
10032 
10033   if (++Field != Record->field_end())
10034     return InvalidType();
10035 
10036   return true;
10037 }
10038 
10039 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
10040   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
10041   if (ClosureClass->isInvalidDecl())
10042     return false;
10043 
10044   const size_t NumFields =
10045       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
10046 
10047   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
10048                                             E->capture_init_end()) &&
10049          "The number of lambda capture initializers should equal the number of "
10050          "fields within the closure type");
10051 
10052   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
10053   // Iterate through all the lambda's closure object's fields and initialize
10054   // them.
10055   auto *CaptureInitIt = E->capture_init_begin();
10056   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
10057   bool Success = true;
10058   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(ClosureClass);
10059   for (const auto *Field : ClosureClass->fields()) {
10060     assert(CaptureInitIt != E->capture_init_end());
10061     // Get the initializer for this field
10062     Expr *const CurFieldInit = *CaptureInitIt++;
10063 
10064     // If there is no initializer, either this is a VLA or an error has
10065     // occurred.
10066     if (!CurFieldInit)
10067       return Error(E);
10068 
10069     LValue Subobject = This;
10070 
10071     if (!HandleLValueMember(Info, E, Subobject, Field, &Layout))
10072       return false;
10073 
10074     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
10075     if (!EvaluateInPlace(FieldVal, Info, Subobject, CurFieldInit)) {
10076       if (!Info.keepEvaluatingAfterFailure())
10077         return false;
10078       Success = false;
10079     }
10080     ++CaptureIt;
10081   }
10082   return Success;
10083 }
10084 
10085 static bool EvaluateRecord(const Expr *E, const LValue &This,
10086                            APValue &Result, EvalInfo &Info) {
10087   assert(!E->isValueDependent());
10088   assert(E->isPRValue() && E->getType()->isRecordType() &&
10089          "can't evaluate expression as a record rvalue");
10090   return RecordExprEvaluator(Info, This, Result).Visit(E);
10091 }
10092 
10093 //===----------------------------------------------------------------------===//
10094 // Temporary Evaluation
10095 //
10096 // Temporaries are represented in the AST as rvalues, but generally behave like
10097 // lvalues. The full-object of which the temporary is a subobject is implicitly
10098 // materialized so that a reference can bind to it.
10099 //===----------------------------------------------------------------------===//
10100 namespace {
10101 class TemporaryExprEvaluator
10102   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
10103 public:
10104   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
10105     LValueExprEvaluatorBaseTy(Info, Result, false) {}
10106 
10107   /// Visit an expression which constructs the value of this temporary.
10108   bool VisitConstructExpr(const Expr *E) {
10109     APValue &Value = Info.CurrentCall->createTemporary(
10110         E, E->getType(), ScopeKind::FullExpression, Result);
10111     return EvaluateInPlace(Value, Info, Result, E);
10112   }
10113 
10114   bool VisitCastExpr(const CastExpr *E) {
10115     switch (E->getCastKind()) {
10116     default:
10117       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
10118 
10119     case CK_ConstructorConversion:
10120       return VisitConstructExpr(E->getSubExpr());
10121     }
10122   }
10123   bool VisitInitListExpr(const InitListExpr *E) {
10124     return VisitConstructExpr(E);
10125   }
10126   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
10127     return VisitConstructExpr(E);
10128   }
10129   bool VisitCallExpr(const CallExpr *E) {
10130     return VisitConstructExpr(E);
10131   }
10132   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
10133     return VisitConstructExpr(E);
10134   }
10135   bool VisitLambdaExpr(const LambdaExpr *E) {
10136     return VisitConstructExpr(E);
10137   }
10138 };
10139 } // end anonymous namespace
10140 
10141 /// Evaluate an expression of record type as a temporary.
10142 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
10143   assert(!E->isValueDependent());
10144   assert(E->isPRValue() && E->getType()->isRecordType());
10145   return TemporaryExprEvaluator(Info, Result).Visit(E);
10146 }
10147 
10148 //===----------------------------------------------------------------------===//
10149 // Vector Evaluation
10150 //===----------------------------------------------------------------------===//
10151 
10152 namespace {
10153   class VectorExprEvaluator
10154   : public ExprEvaluatorBase<VectorExprEvaluator> {
10155     APValue &Result;
10156   public:
10157 
10158     VectorExprEvaluator(EvalInfo &info, APValue &Result)
10159       : ExprEvaluatorBaseTy(info), Result(Result) {}
10160 
10161     bool Success(ArrayRef<APValue> V, const Expr *E) {
10162       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
10163       // FIXME: remove this APValue copy.
10164       Result = APValue(V.data(), V.size());
10165       return true;
10166     }
10167     bool Success(const APValue &V, const Expr *E) {
10168       assert(V.isVector());
10169       Result = V;
10170       return true;
10171     }
10172     bool ZeroInitialization(const Expr *E);
10173 
10174     bool VisitUnaryReal(const UnaryOperator *E)
10175       { return Visit(E->getSubExpr()); }
10176     bool VisitCastExpr(const CastExpr* E);
10177     bool VisitInitListExpr(const InitListExpr *E);
10178     bool VisitUnaryImag(const UnaryOperator *E);
10179     bool VisitBinaryOperator(const BinaryOperator *E);
10180     // FIXME: Missing: unary -, unary ~, conditional operator (for GNU
10181     //                 conditional select), shufflevector, ExtVectorElementExpr
10182   };
10183 } // end anonymous namespace
10184 
10185 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
10186   assert(E->isPRValue() && E->getType()->isVectorType() &&
10187          "not a vector prvalue");
10188   return VectorExprEvaluator(Info, Result).Visit(E);
10189 }
10190 
10191 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
10192   const VectorType *VTy = E->getType()->castAs<VectorType>();
10193   unsigned NElts = VTy->getNumElements();
10194 
10195   const Expr *SE = E->getSubExpr();
10196   QualType SETy = SE->getType();
10197 
10198   switch (E->getCastKind()) {
10199   case CK_VectorSplat: {
10200     APValue Val = APValue();
10201     if (SETy->isIntegerType()) {
10202       APSInt IntResult;
10203       if (!EvaluateInteger(SE, IntResult, Info))
10204         return false;
10205       Val = APValue(std::move(IntResult));
10206     } else if (SETy->isRealFloatingType()) {
10207       APFloat FloatResult(0.0);
10208       if (!EvaluateFloat(SE, FloatResult, Info))
10209         return false;
10210       Val = APValue(std::move(FloatResult));
10211     } else {
10212       return Error(E);
10213     }
10214 
10215     // Splat and create vector APValue.
10216     SmallVector<APValue, 4> Elts(NElts, Val);
10217     return Success(Elts, E);
10218   }
10219   case CK_BitCast: {
10220     // Evaluate the operand into an APInt we can extract from.
10221     llvm::APInt SValInt;
10222     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
10223       return false;
10224     // Extract the elements
10225     QualType EltTy = VTy->getElementType();
10226     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
10227     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
10228     SmallVector<APValue, 4> Elts;
10229     if (EltTy->isRealFloatingType()) {
10230       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
10231       unsigned FloatEltSize = EltSize;
10232       if (&Sem == &APFloat::x87DoubleExtended())
10233         FloatEltSize = 80;
10234       for (unsigned i = 0; i < NElts; i++) {
10235         llvm::APInt Elt;
10236         if (BigEndian)
10237           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
10238         else
10239           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
10240         Elts.push_back(APValue(APFloat(Sem, Elt)));
10241       }
10242     } else if (EltTy->isIntegerType()) {
10243       for (unsigned i = 0; i < NElts; i++) {
10244         llvm::APInt Elt;
10245         if (BigEndian)
10246           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
10247         else
10248           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
10249         Elts.push_back(APValue(APSInt(Elt, !EltTy->isSignedIntegerType())));
10250       }
10251     } else {
10252       return Error(E);
10253     }
10254     return Success(Elts, E);
10255   }
10256   default:
10257     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10258   }
10259 }
10260 
10261 bool
10262 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10263   const VectorType *VT = E->getType()->castAs<VectorType>();
10264   unsigned NumInits = E->getNumInits();
10265   unsigned NumElements = VT->getNumElements();
10266 
10267   QualType EltTy = VT->getElementType();
10268   SmallVector<APValue, 4> Elements;
10269 
10270   // The number of initializers can be less than the number of
10271   // vector elements. For OpenCL, this can be due to nested vector
10272   // initialization. For GCC compatibility, missing trailing elements
10273   // should be initialized with zeroes.
10274   unsigned CountInits = 0, CountElts = 0;
10275   while (CountElts < NumElements) {
10276     // Handle nested vector initialization.
10277     if (CountInits < NumInits
10278         && E->getInit(CountInits)->getType()->isVectorType()) {
10279       APValue v;
10280       if (!EvaluateVector(E->getInit(CountInits), v, Info))
10281         return Error(E);
10282       unsigned vlen = v.getVectorLength();
10283       for (unsigned j = 0; j < vlen; j++)
10284         Elements.push_back(v.getVectorElt(j));
10285       CountElts += vlen;
10286     } else if (EltTy->isIntegerType()) {
10287       llvm::APSInt sInt(32);
10288       if (CountInits < NumInits) {
10289         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
10290           return false;
10291       } else // trailing integer zero.
10292         sInt = Info.Ctx.MakeIntValue(0, EltTy);
10293       Elements.push_back(APValue(sInt));
10294       CountElts++;
10295     } else {
10296       llvm::APFloat f(0.0);
10297       if (CountInits < NumInits) {
10298         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
10299           return false;
10300       } else // trailing float zero.
10301         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
10302       Elements.push_back(APValue(f));
10303       CountElts++;
10304     }
10305     CountInits++;
10306   }
10307   return Success(Elements, E);
10308 }
10309 
10310 bool
10311 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
10312   const auto *VT = E->getType()->castAs<VectorType>();
10313   QualType EltTy = VT->getElementType();
10314   APValue ZeroElement;
10315   if (EltTy->isIntegerType())
10316     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
10317   else
10318     ZeroElement =
10319         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
10320 
10321   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
10322   return Success(Elements, E);
10323 }
10324 
10325 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
10326   VisitIgnoredValue(E->getSubExpr());
10327   return ZeroInitialization(E);
10328 }
10329 
10330 bool VectorExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10331   BinaryOperatorKind Op = E->getOpcode();
10332   assert(Op != BO_PtrMemD && Op != BO_PtrMemI && Op != BO_Cmp &&
10333          "Operation not supported on vector types");
10334 
10335   if (Op == BO_Comma)
10336     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10337 
10338   Expr *LHS = E->getLHS();
10339   Expr *RHS = E->getRHS();
10340 
10341   assert(LHS->getType()->isVectorType() && RHS->getType()->isVectorType() &&
10342          "Must both be vector types");
10343   // Checking JUST the types are the same would be fine, except shifts don't
10344   // need to have their types be the same (since you always shift by an int).
10345   assert(LHS->getType()->castAs<VectorType>()->getNumElements() ==
10346              E->getType()->castAs<VectorType>()->getNumElements() &&
10347          RHS->getType()->castAs<VectorType>()->getNumElements() ==
10348              E->getType()->castAs<VectorType>()->getNumElements() &&
10349          "All operands must be the same size.");
10350 
10351   APValue LHSValue;
10352   APValue RHSValue;
10353   bool LHSOK = Evaluate(LHSValue, Info, LHS);
10354   if (!LHSOK && !Info.noteFailure())
10355     return false;
10356   if (!Evaluate(RHSValue, Info, RHS) || !LHSOK)
10357     return false;
10358 
10359   if (!handleVectorVectorBinOp(Info, E, Op, LHSValue, RHSValue))
10360     return false;
10361 
10362   return Success(LHSValue, E);
10363 }
10364 
10365 //===----------------------------------------------------------------------===//
10366 // Array Evaluation
10367 //===----------------------------------------------------------------------===//
10368 
10369 namespace {
10370   class ArrayExprEvaluator
10371   : public ExprEvaluatorBase<ArrayExprEvaluator> {
10372     const LValue &This;
10373     APValue &Result;
10374   public:
10375 
10376     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
10377       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10378 
10379     bool Success(const APValue &V, const Expr *E) {
10380       assert(V.isArray() && "expected array");
10381       Result = V;
10382       return true;
10383     }
10384 
10385     bool ZeroInitialization(const Expr *E) {
10386       const ConstantArrayType *CAT =
10387           Info.Ctx.getAsConstantArrayType(E->getType());
10388       if (!CAT) {
10389         if (E->getType()->isIncompleteArrayType()) {
10390           // We can be asked to zero-initialize a flexible array member; this
10391           // is represented as an ImplicitValueInitExpr of incomplete array
10392           // type. In this case, the array has zero elements.
10393           Result = APValue(APValue::UninitArray(), 0, 0);
10394           return true;
10395         }
10396         // FIXME: We could handle VLAs here.
10397         return Error(E);
10398       }
10399 
10400       Result = APValue(APValue::UninitArray(), 0,
10401                        CAT->getSize().getZExtValue());
10402       if (!Result.hasArrayFiller())
10403         return true;
10404 
10405       // Zero-initialize all elements.
10406       LValue Subobject = This;
10407       Subobject.addArray(Info, E, CAT);
10408       ImplicitValueInitExpr VIE(CAT->getElementType());
10409       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
10410     }
10411 
10412     bool VisitCallExpr(const CallExpr *E) {
10413       return handleCallExpr(E, Result, &This);
10414     }
10415     bool VisitInitListExpr(const InitListExpr *E,
10416                            QualType AllocType = QualType());
10417     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
10418     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
10419     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
10420                                const LValue &Subobject,
10421                                APValue *Value, QualType Type);
10422     bool VisitStringLiteral(const StringLiteral *E,
10423                             QualType AllocType = QualType()) {
10424       expandStringLiteral(Info, E, Result, AllocType);
10425       return true;
10426     }
10427   };
10428 } // end anonymous namespace
10429 
10430 static bool EvaluateArray(const Expr *E, const LValue &This,
10431                           APValue &Result, EvalInfo &Info) {
10432   assert(!E->isValueDependent());
10433   assert(E->isPRValue() && E->getType()->isArrayType() &&
10434          "not an array prvalue");
10435   return ArrayExprEvaluator(Info, This, Result).Visit(E);
10436 }
10437 
10438 static bool EvaluateArrayNewInitList(EvalInfo &Info, LValue &This,
10439                                      APValue &Result, const InitListExpr *ILE,
10440                                      QualType AllocType) {
10441   assert(!ILE->isValueDependent());
10442   assert(ILE->isPRValue() && ILE->getType()->isArrayType() &&
10443          "not an array prvalue");
10444   return ArrayExprEvaluator(Info, This, Result)
10445       .VisitInitListExpr(ILE, AllocType);
10446 }
10447 
10448 static bool EvaluateArrayNewConstructExpr(EvalInfo &Info, LValue &This,
10449                                           APValue &Result,
10450                                           const CXXConstructExpr *CCE,
10451                                           QualType AllocType) {
10452   assert(!CCE->isValueDependent());
10453   assert(CCE->isPRValue() && CCE->getType()->isArrayType() &&
10454          "not an array prvalue");
10455   return ArrayExprEvaluator(Info, This, Result)
10456       .VisitCXXConstructExpr(CCE, This, &Result, AllocType);
10457 }
10458 
10459 // Return true iff the given array filler may depend on the element index.
10460 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
10461   // For now, just allow non-class value-initialization and initialization
10462   // lists comprised of them.
10463   if (isa<ImplicitValueInitExpr>(FillerExpr))
10464     return false;
10465   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
10466     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
10467       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
10468         return true;
10469     }
10470     return false;
10471   }
10472   return true;
10473 }
10474 
10475 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E,
10476                                            QualType AllocType) {
10477   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(
10478       AllocType.isNull() ? E->getType() : AllocType);
10479   if (!CAT)
10480     return Error(E);
10481 
10482   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
10483   // an appropriately-typed string literal enclosed in braces.
10484   if (E->isStringLiteralInit()) {
10485     auto *SL = dyn_cast<StringLiteral>(E->getInit(0)->IgnoreParenImpCasts());
10486     // FIXME: Support ObjCEncodeExpr here once we support it in
10487     // ArrayExprEvaluator generally.
10488     if (!SL)
10489       return Error(E);
10490     return VisitStringLiteral(SL, AllocType);
10491   }
10492   // Any other transparent list init will need proper handling of the
10493   // AllocType; we can't just recurse to the inner initializer.
10494   assert(!E->isTransparent() &&
10495          "transparent array list initialization is not string literal init?");
10496 
10497   bool Success = true;
10498 
10499   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
10500          "zero-initialized array shouldn't have any initialized elts");
10501   APValue Filler;
10502   if (Result.isArray() && Result.hasArrayFiller())
10503     Filler = Result.getArrayFiller();
10504 
10505   unsigned NumEltsToInit = E->getNumInits();
10506   unsigned NumElts = CAT->getSize().getZExtValue();
10507   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
10508 
10509   // If the initializer might depend on the array index, run it for each
10510   // array element.
10511   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
10512     NumEltsToInit = NumElts;
10513 
10514   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
10515                           << NumEltsToInit << ".\n");
10516 
10517   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
10518 
10519   // If the array was previously zero-initialized, preserve the
10520   // zero-initialized values.
10521   if (Filler.hasValue()) {
10522     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
10523       Result.getArrayInitializedElt(I) = Filler;
10524     if (Result.hasArrayFiller())
10525       Result.getArrayFiller() = Filler;
10526   }
10527 
10528   LValue Subobject = This;
10529   Subobject.addArray(Info, E, CAT);
10530   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
10531     const Expr *Init =
10532         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
10533     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10534                          Info, Subobject, Init) ||
10535         !HandleLValueArrayAdjustment(Info, Init, Subobject,
10536                                      CAT->getElementType(), 1)) {
10537       if (!Info.noteFailure())
10538         return false;
10539       Success = false;
10540     }
10541   }
10542 
10543   if (!Result.hasArrayFiller())
10544     return Success;
10545 
10546   // If we get here, we have a trivial filler, which we can just evaluate
10547   // once and splat over the rest of the array elements.
10548   assert(FillerExpr && "no array filler for incomplete init list");
10549   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
10550                          FillerExpr) && Success;
10551 }
10552 
10553 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
10554   LValue CommonLV;
10555   if (E->getCommonExpr() &&
10556       !Evaluate(Info.CurrentCall->createTemporary(
10557                     E->getCommonExpr(),
10558                     getStorageType(Info.Ctx, E->getCommonExpr()),
10559                     ScopeKind::FullExpression, CommonLV),
10560                 Info, E->getCommonExpr()->getSourceExpr()))
10561     return false;
10562 
10563   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
10564 
10565   uint64_t Elements = CAT->getSize().getZExtValue();
10566   Result = APValue(APValue::UninitArray(), Elements, Elements);
10567 
10568   LValue Subobject = This;
10569   Subobject.addArray(Info, E, CAT);
10570 
10571   bool Success = true;
10572   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
10573     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
10574                          Info, Subobject, E->getSubExpr()) ||
10575         !HandleLValueArrayAdjustment(Info, E, Subobject,
10576                                      CAT->getElementType(), 1)) {
10577       if (!Info.noteFailure())
10578         return false;
10579       Success = false;
10580     }
10581   }
10582 
10583   return Success;
10584 }
10585 
10586 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
10587   return VisitCXXConstructExpr(E, This, &Result, E->getType());
10588 }
10589 
10590 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
10591                                                const LValue &Subobject,
10592                                                APValue *Value,
10593                                                QualType Type) {
10594   bool HadZeroInit = Value->hasValue();
10595 
10596   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
10597     unsigned N = CAT->getSize().getZExtValue();
10598 
10599     // Preserve the array filler if we had prior zero-initialization.
10600     APValue Filler =
10601       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
10602                                              : APValue();
10603 
10604     *Value = APValue(APValue::UninitArray(), N, N);
10605 
10606     if (HadZeroInit)
10607       for (unsigned I = 0; I != N; ++I)
10608         Value->getArrayInitializedElt(I) = Filler;
10609 
10610     // Initialize the elements.
10611     LValue ArrayElt = Subobject;
10612     ArrayElt.addArray(Info, E, CAT);
10613     for (unsigned I = 0; I != N; ++I)
10614       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
10615                                  CAT->getElementType()) ||
10616           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
10617                                        CAT->getElementType(), 1))
10618         return false;
10619 
10620     return true;
10621   }
10622 
10623   if (!Type->isRecordType())
10624     return Error(E);
10625 
10626   return RecordExprEvaluator(Info, Subobject, *Value)
10627              .VisitCXXConstructExpr(E, Type);
10628 }
10629 
10630 //===----------------------------------------------------------------------===//
10631 // Integer Evaluation
10632 //
10633 // As a GNU extension, we support casting pointers to sufficiently-wide integer
10634 // types and back in constant folding. Integer values are thus represented
10635 // either as an integer-valued APValue, or as an lvalue-valued APValue.
10636 //===----------------------------------------------------------------------===//
10637 
10638 namespace {
10639 class IntExprEvaluator
10640         : public ExprEvaluatorBase<IntExprEvaluator> {
10641   APValue &Result;
10642 public:
10643   IntExprEvaluator(EvalInfo &info, APValue &result)
10644       : ExprEvaluatorBaseTy(info), Result(result) {}
10645 
10646   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
10647     assert(E->getType()->isIntegralOrEnumerationType() &&
10648            "Invalid evaluation result.");
10649     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
10650            "Invalid evaluation result.");
10651     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10652            "Invalid evaluation result.");
10653     Result = APValue(SI);
10654     return true;
10655   }
10656   bool Success(const llvm::APSInt &SI, const Expr *E) {
10657     return Success(SI, E, Result);
10658   }
10659 
10660   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
10661     assert(E->getType()->isIntegralOrEnumerationType() &&
10662            "Invalid evaluation result.");
10663     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10664            "Invalid evaluation result.");
10665     Result = APValue(APSInt(I));
10666     Result.getInt().setIsUnsigned(
10667                             E->getType()->isUnsignedIntegerOrEnumerationType());
10668     return true;
10669   }
10670   bool Success(const llvm::APInt &I, const Expr *E) {
10671     return Success(I, E, Result);
10672   }
10673 
10674   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10675     assert(E->getType()->isIntegralOrEnumerationType() &&
10676            "Invalid evaluation result.");
10677     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
10678     return true;
10679   }
10680   bool Success(uint64_t Value, const Expr *E) {
10681     return Success(Value, E, Result);
10682   }
10683 
10684   bool Success(CharUnits Size, const Expr *E) {
10685     return Success(Size.getQuantity(), E);
10686   }
10687 
10688   bool Success(const APValue &V, const Expr *E) {
10689     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
10690       Result = V;
10691       return true;
10692     }
10693     return Success(V.getInt(), E);
10694   }
10695 
10696   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
10697 
10698   //===--------------------------------------------------------------------===//
10699   //                            Visitor Methods
10700   //===--------------------------------------------------------------------===//
10701 
10702   bool VisitIntegerLiteral(const IntegerLiteral *E) {
10703     return Success(E->getValue(), E);
10704   }
10705   bool VisitCharacterLiteral(const CharacterLiteral *E) {
10706     return Success(E->getValue(), E);
10707   }
10708 
10709   bool CheckReferencedDecl(const Expr *E, const Decl *D);
10710   bool VisitDeclRefExpr(const DeclRefExpr *E) {
10711     if (CheckReferencedDecl(E, E->getDecl()))
10712       return true;
10713 
10714     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
10715   }
10716   bool VisitMemberExpr(const MemberExpr *E) {
10717     if (CheckReferencedDecl(E, E->getMemberDecl())) {
10718       VisitIgnoredBaseExpression(E->getBase());
10719       return true;
10720     }
10721 
10722     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
10723   }
10724 
10725   bool VisitCallExpr(const CallExpr *E);
10726   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
10727   bool VisitBinaryOperator(const BinaryOperator *E);
10728   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
10729   bool VisitUnaryOperator(const UnaryOperator *E);
10730 
10731   bool VisitCastExpr(const CastExpr* E);
10732   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
10733 
10734   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
10735     return Success(E->getValue(), E);
10736   }
10737 
10738   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
10739     return Success(E->getValue(), E);
10740   }
10741 
10742   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
10743     if (Info.ArrayInitIndex == uint64_t(-1)) {
10744       // We were asked to evaluate this subexpression independent of the
10745       // enclosing ArrayInitLoopExpr. We can't do that.
10746       Info.FFDiag(E);
10747       return false;
10748     }
10749     return Success(Info.ArrayInitIndex, E);
10750   }
10751 
10752   // Note, GNU defines __null as an integer, not a pointer.
10753   bool VisitGNUNullExpr(const GNUNullExpr *E) {
10754     return ZeroInitialization(E);
10755   }
10756 
10757   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
10758     return Success(E->getValue(), E);
10759   }
10760 
10761   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
10762     return Success(E->getValue(), E);
10763   }
10764 
10765   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
10766     return Success(E->getValue(), E);
10767   }
10768 
10769   bool VisitUnaryReal(const UnaryOperator *E);
10770   bool VisitUnaryImag(const UnaryOperator *E);
10771 
10772   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
10773   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
10774   bool VisitSourceLocExpr(const SourceLocExpr *E);
10775   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
10776   bool VisitRequiresExpr(const RequiresExpr *E);
10777   // FIXME: Missing: array subscript of vector, member of vector
10778 };
10779 
10780 class FixedPointExprEvaluator
10781     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
10782   APValue &Result;
10783 
10784  public:
10785   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
10786       : ExprEvaluatorBaseTy(info), Result(result) {}
10787 
10788   bool Success(const llvm::APInt &I, const Expr *E) {
10789     return Success(
10790         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10791   }
10792 
10793   bool Success(uint64_t Value, const Expr *E) {
10794     return Success(
10795         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
10796   }
10797 
10798   bool Success(const APValue &V, const Expr *E) {
10799     return Success(V.getFixedPoint(), E);
10800   }
10801 
10802   bool Success(const APFixedPoint &V, const Expr *E) {
10803     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
10804     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
10805            "Invalid evaluation result.");
10806     Result = APValue(V);
10807     return true;
10808   }
10809 
10810   //===--------------------------------------------------------------------===//
10811   //                            Visitor Methods
10812   //===--------------------------------------------------------------------===//
10813 
10814   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
10815     return Success(E->getValue(), E);
10816   }
10817 
10818   bool VisitCastExpr(const CastExpr *E);
10819   bool VisitUnaryOperator(const UnaryOperator *E);
10820   bool VisitBinaryOperator(const BinaryOperator *E);
10821 };
10822 } // end anonymous namespace
10823 
10824 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
10825 /// produce either the integer value or a pointer.
10826 ///
10827 /// GCC has a heinous extension which folds casts between pointer types and
10828 /// pointer-sized integral types. We support this by allowing the evaluation of
10829 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
10830 /// Some simple arithmetic on such values is supported (they are treated much
10831 /// like char*).
10832 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
10833                                     EvalInfo &Info) {
10834   assert(!E->isValueDependent());
10835   assert(E->isPRValue() && E->getType()->isIntegralOrEnumerationType());
10836   return IntExprEvaluator(Info, Result).Visit(E);
10837 }
10838 
10839 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
10840   assert(!E->isValueDependent());
10841   APValue Val;
10842   if (!EvaluateIntegerOrLValue(E, Val, Info))
10843     return false;
10844   if (!Val.isInt()) {
10845     // FIXME: It would be better to produce the diagnostic for casting
10846     //        a pointer to an integer.
10847     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10848     return false;
10849   }
10850   Result = Val.getInt();
10851   return true;
10852 }
10853 
10854 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
10855   APValue Evaluated = E->EvaluateInContext(
10856       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
10857   return Success(Evaluated, E);
10858 }
10859 
10860 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
10861                                EvalInfo &Info) {
10862   assert(!E->isValueDependent());
10863   if (E->getType()->isFixedPointType()) {
10864     APValue Val;
10865     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
10866       return false;
10867     if (!Val.isFixedPoint())
10868       return false;
10869 
10870     Result = Val.getFixedPoint();
10871     return true;
10872   }
10873   return false;
10874 }
10875 
10876 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
10877                                         EvalInfo &Info) {
10878   assert(!E->isValueDependent());
10879   if (E->getType()->isIntegerType()) {
10880     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
10881     APSInt Val;
10882     if (!EvaluateInteger(E, Val, Info))
10883       return false;
10884     Result = APFixedPoint(Val, FXSema);
10885     return true;
10886   } else if (E->getType()->isFixedPointType()) {
10887     return EvaluateFixedPoint(E, Result, Info);
10888   }
10889   return false;
10890 }
10891 
10892 /// Check whether the given declaration can be directly converted to an integral
10893 /// rvalue. If not, no diagnostic is produced; there are other things we can
10894 /// try.
10895 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
10896   // Enums are integer constant exprs.
10897   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
10898     // Check for signedness/width mismatches between E type and ECD value.
10899     bool SameSign = (ECD->getInitVal().isSigned()
10900                      == E->getType()->isSignedIntegerOrEnumerationType());
10901     bool SameWidth = (ECD->getInitVal().getBitWidth()
10902                       == Info.Ctx.getIntWidth(E->getType()));
10903     if (SameSign && SameWidth)
10904       return Success(ECD->getInitVal(), E);
10905     else {
10906       // Get rid of mismatch (otherwise Success assertions will fail)
10907       // by computing a new value matching the type of E.
10908       llvm::APSInt Val = ECD->getInitVal();
10909       if (!SameSign)
10910         Val.setIsSigned(!ECD->getInitVal().isSigned());
10911       if (!SameWidth)
10912         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
10913       return Success(Val, E);
10914     }
10915   }
10916   return false;
10917 }
10918 
10919 /// Values returned by __builtin_classify_type, chosen to match the values
10920 /// produced by GCC's builtin.
10921 enum class GCCTypeClass {
10922   None = -1,
10923   Void = 0,
10924   Integer = 1,
10925   // GCC reserves 2 for character types, but instead classifies them as
10926   // integers.
10927   Enum = 3,
10928   Bool = 4,
10929   Pointer = 5,
10930   // GCC reserves 6 for references, but appears to never use it (because
10931   // expressions never have reference type, presumably).
10932   PointerToDataMember = 7,
10933   RealFloat = 8,
10934   Complex = 9,
10935   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
10936   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
10937   // GCC claims to reserve 11 for pointers to member functions, but *actually*
10938   // uses 12 for that purpose, same as for a class or struct. Maybe it
10939   // internally implements a pointer to member as a struct?  Who knows.
10940   PointerToMemberFunction = 12, // Not a bug, see above.
10941   ClassOrStruct = 12,
10942   Union = 13,
10943   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
10944   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
10945   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
10946   // literals.
10947 };
10948 
10949 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
10950 /// as GCC.
10951 static GCCTypeClass
10952 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
10953   assert(!T->isDependentType() && "unexpected dependent type");
10954 
10955   QualType CanTy = T.getCanonicalType();
10956   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
10957 
10958   switch (CanTy->getTypeClass()) {
10959 #define TYPE(ID, BASE)
10960 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
10961 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
10962 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
10963 #include "clang/AST/TypeNodes.inc"
10964   case Type::Auto:
10965   case Type::DeducedTemplateSpecialization:
10966       llvm_unreachable("unexpected non-canonical or dependent type");
10967 
10968   case Type::Builtin:
10969     switch (BT->getKind()) {
10970 #define BUILTIN_TYPE(ID, SINGLETON_ID)
10971 #define SIGNED_TYPE(ID, SINGLETON_ID) \
10972     case BuiltinType::ID: return GCCTypeClass::Integer;
10973 #define FLOATING_TYPE(ID, SINGLETON_ID) \
10974     case BuiltinType::ID: return GCCTypeClass::RealFloat;
10975 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
10976     case BuiltinType::ID: break;
10977 #include "clang/AST/BuiltinTypes.def"
10978     case BuiltinType::Void:
10979       return GCCTypeClass::Void;
10980 
10981     case BuiltinType::Bool:
10982       return GCCTypeClass::Bool;
10983 
10984     case BuiltinType::Char_U:
10985     case BuiltinType::UChar:
10986     case BuiltinType::WChar_U:
10987     case BuiltinType::Char8:
10988     case BuiltinType::Char16:
10989     case BuiltinType::Char32:
10990     case BuiltinType::UShort:
10991     case BuiltinType::UInt:
10992     case BuiltinType::ULong:
10993     case BuiltinType::ULongLong:
10994     case BuiltinType::UInt128:
10995       return GCCTypeClass::Integer;
10996 
10997     case BuiltinType::UShortAccum:
10998     case BuiltinType::UAccum:
10999     case BuiltinType::ULongAccum:
11000     case BuiltinType::UShortFract:
11001     case BuiltinType::UFract:
11002     case BuiltinType::ULongFract:
11003     case BuiltinType::SatUShortAccum:
11004     case BuiltinType::SatUAccum:
11005     case BuiltinType::SatULongAccum:
11006     case BuiltinType::SatUShortFract:
11007     case BuiltinType::SatUFract:
11008     case BuiltinType::SatULongFract:
11009       return GCCTypeClass::None;
11010 
11011     case BuiltinType::NullPtr:
11012 
11013     case BuiltinType::ObjCId:
11014     case BuiltinType::ObjCClass:
11015     case BuiltinType::ObjCSel:
11016 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
11017     case BuiltinType::Id:
11018 #include "clang/Basic/OpenCLImageTypes.def"
11019 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
11020     case BuiltinType::Id:
11021 #include "clang/Basic/OpenCLExtensionTypes.def"
11022     case BuiltinType::OCLSampler:
11023     case BuiltinType::OCLEvent:
11024     case BuiltinType::OCLClkEvent:
11025     case BuiltinType::OCLQueue:
11026     case BuiltinType::OCLReserveID:
11027 #define SVE_TYPE(Name, Id, SingletonId) \
11028     case BuiltinType::Id:
11029 #include "clang/Basic/AArch64SVEACLETypes.def"
11030 #define PPC_VECTOR_TYPE(Name, Id, Size) \
11031     case BuiltinType::Id:
11032 #include "clang/Basic/PPCTypes.def"
11033 #define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
11034 #include "clang/Basic/RISCVVTypes.def"
11035       return GCCTypeClass::None;
11036 
11037     case BuiltinType::Dependent:
11038       llvm_unreachable("unexpected dependent type");
11039     };
11040     llvm_unreachable("unexpected placeholder type");
11041 
11042   case Type::Enum:
11043     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
11044 
11045   case Type::Pointer:
11046   case Type::ConstantArray:
11047   case Type::VariableArray:
11048   case Type::IncompleteArray:
11049   case Type::FunctionNoProto:
11050   case Type::FunctionProto:
11051     return GCCTypeClass::Pointer;
11052 
11053   case Type::MemberPointer:
11054     return CanTy->isMemberDataPointerType()
11055                ? GCCTypeClass::PointerToDataMember
11056                : GCCTypeClass::PointerToMemberFunction;
11057 
11058   case Type::Complex:
11059     return GCCTypeClass::Complex;
11060 
11061   case Type::Record:
11062     return CanTy->isUnionType() ? GCCTypeClass::Union
11063                                 : GCCTypeClass::ClassOrStruct;
11064 
11065   case Type::Atomic:
11066     // GCC classifies _Atomic T the same as T.
11067     return EvaluateBuiltinClassifyType(
11068         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
11069 
11070   case Type::BlockPointer:
11071   case Type::Vector:
11072   case Type::ExtVector:
11073   case Type::ConstantMatrix:
11074   case Type::ObjCObject:
11075   case Type::ObjCInterface:
11076   case Type::ObjCObjectPointer:
11077   case Type::Pipe:
11078   case Type::ExtInt:
11079     // GCC classifies vectors as None. We follow its lead and classify all
11080     // other types that don't fit into the regular classification the same way.
11081     return GCCTypeClass::None;
11082 
11083   case Type::LValueReference:
11084   case Type::RValueReference:
11085     llvm_unreachable("invalid type for expression");
11086   }
11087 
11088   llvm_unreachable("unexpected type class");
11089 }
11090 
11091 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
11092 /// as GCC.
11093 static GCCTypeClass
11094 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
11095   // If no argument was supplied, default to None. This isn't
11096   // ideal, however it is what gcc does.
11097   if (E->getNumArgs() == 0)
11098     return GCCTypeClass::None;
11099 
11100   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
11101   // being an ICE, but still folds it to a constant using the type of the first
11102   // argument.
11103   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
11104 }
11105 
11106 /// EvaluateBuiltinConstantPForLValue - Determine the result of
11107 /// __builtin_constant_p when applied to the given pointer.
11108 ///
11109 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
11110 /// or it points to the first character of a string literal.
11111 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
11112   APValue::LValueBase Base = LV.getLValueBase();
11113   if (Base.isNull()) {
11114     // A null base is acceptable.
11115     return true;
11116   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
11117     if (!isa<StringLiteral>(E))
11118       return false;
11119     return LV.getLValueOffset().isZero();
11120   } else if (Base.is<TypeInfoLValue>()) {
11121     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
11122     // evaluate to true.
11123     return true;
11124   } else {
11125     // Any other base is not constant enough for GCC.
11126     return false;
11127   }
11128 }
11129 
11130 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
11131 /// GCC as we can manage.
11132 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
11133   // This evaluation is not permitted to have side-effects, so evaluate it in
11134   // a speculative evaluation context.
11135   SpeculativeEvaluationRAII SpeculativeEval(Info);
11136 
11137   // Constant-folding is always enabled for the operand of __builtin_constant_p
11138   // (even when the enclosing evaluation context otherwise requires a strict
11139   // language-specific constant expression).
11140   FoldConstant Fold(Info, true);
11141 
11142   QualType ArgType = Arg->getType();
11143 
11144   // __builtin_constant_p always has one operand. The rules which gcc follows
11145   // are not precisely documented, but are as follows:
11146   //
11147   //  - If the operand is of integral, floating, complex or enumeration type,
11148   //    and can be folded to a known value of that type, it returns 1.
11149   //  - If the operand can be folded to a pointer to the first character
11150   //    of a string literal (or such a pointer cast to an integral type)
11151   //    or to a null pointer or an integer cast to a pointer, it returns 1.
11152   //
11153   // Otherwise, it returns 0.
11154   //
11155   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
11156   // its support for this did not work prior to GCC 9 and is not yet well
11157   // understood.
11158   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
11159       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
11160       ArgType->isNullPtrType()) {
11161     APValue V;
11162     if (!::EvaluateAsRValue(Info, Arg, V) || Info.EvalStatus.HasSideEffects) {
11163       Fold.keepDiagnostics();
11164       return false;
11165     }
11166 
11167     // For a pointer (possibly cast to integer), there are special rules.
11168     if (V.getKind() == APValue::LValue)
11169       return EvaluateBuiltinConstantPForLValue(V);
11170 
11171     // Otherwise, any constant value is good enough.
11172     return V.hasValue();
11173   }
11174 
11175   // Anything else isn't considered to be sufficiently constant.
11176   return false;
11177 }
11178 
11179 /// Retrieves the "underlying object type" of the given expression,
11180 /// as used by __builtin_object_size.
11181 static QualType getObjectType(APValue::LValueBase B) {
11182   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
11183     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
11184       return VD->getType();
11185   } else if (const Expr *E = B.dyn_cast<const Expr*>()) {
11186     if (isa<CompoundLiteralExpr>(E))
11187       return E->getType();
11188   } else if (B.is<TypeInfoLValue>()) {
11189     return B.getTypeInfoType();
11190   } else if (B.is<DynamicAllocLValue>()) {
11191     return B.getDynamicAllocType();
11192   }
11193 
11194   return QualType();
11195 }
11196 
11197 /// A more selective version of E->IgnoreParenCasts for
11198 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
11199 /// to change the type of E.
11200 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
11201 ///
11202 /// Always returns an RValue with a pointer representation.
11203 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
11204   assert(E->isPRValue() && E->getType()->hasPointerRepresentation());
11205 
11206   auto *NoParens = E->IgnoreParens();
11207   auto *Cast = dyn_cast<CastExpr>(NoParens);
11208   if (Cast == nullptr)
11209     return NoParens;
11210 
11211   // We only conservatively allow a few kinds of casts, because this code is
11212   // inherently a simple solution that seeks to support the common case.
11213   auto CastKind = Cast->getCastKind();
11214   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
11215       CastKind != CK_AddressSpaceConversion)
11216     return NoParens;
11217 
11218   auto *SubExpr = Cast->getSubExpr();
11219   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isPRValue())
11220     return NoParens;
11221   return ignorePointerCastsAndParens(SubExpr);
11222 }
11223 
11224 /// Checks to see if the given LValue's Designator is at the end of the LValue's
11225 /// record layout. e.g.
11226 ///   struct { struct { int a, b; } fst, snd; } obj;
11227 ///   obj.fst   // no
11228 ///   obj.snd   // yes
11229 ///   obj.fst.a // no
11230 ///   obj.fst.b // no
11231 ///   obj.snd.a // no
11232 ///   obj.snd.b // yes
11233 ///
11234 /// Please note: this function is specialized for how __builtin_object_size
11235 /// views "objects".
11236 ///
11237 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
11238 /// correct result, it will always return true.
11239 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
11240   assert(!LVal.Designator.Invalid);
11241 
11242   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
11243     const RecordDecl *Parent = FD->getParent();
11244     Invalid = Parent->isInvalidDecl();
11245     if (Invalid || Parent->isUnion())
11246       return true;
11247     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
11248     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
11249   };
11250 
11251   auto &Base = LVal.getLValueBase();
11252   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
11253     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
11254       bool Invalid;
11255       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11256         return Invalid;
11257     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
11258       for (auto *FD : IFD->chain()) {
11259         bool Invalid;
11260         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
11261           return Invalid;
11262       }
11263     }
11264   }
11265 
11266   unsigned I = 0;
11267   QualType BaseType = getType(Base);
11268   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
11269     // If we don't know the array bound, conservatively assume we're looking at
11270     // the final array element.
11271     ++I;
11272     if (BaseType->isIncompleteArrayType())
11273       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
11274     else
11275       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
11276   }
11277 
11278   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
11279     const auto &Entry = LVal.Designator.Entries[I];
11280     if (BaseType->isArrayType()) {
11281       // Because __builtin_object_size treats arrays as objects, we can ignore
11282       // the index iff this is the last array in the Designator.
11283       if (I + 1 == E)
11284         return true;
11285       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
11286       uint64_t Index = Entry.getAsArrayIndex();
11287       if (Index + 1 != CAT->getSize())
11288         return false;
11289       BaseType = CAT->getElementType();
11290     } else if (BaseType->isAnyComplexType()) {
11291       const auto *CT = BaseType->castAs<ComplexType>();
11292       uint64_t Index = Entry.getAsArrayIndex();
11293       if (Index != 1)
11294         return false;
11295       BaseType = CT->getElementType();
11296     } else if (auto *FD = getAsField(Entry)) {
11297       bool Invalid;
11298       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
11299         return Invalid;
11300       BaseType = FD->getType();
11301     } else {
11302       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
11303       return false;
11304     }
11305   }
11306   return true;
11307 }
11308 
11309 /// Tests to see if the LValue has a user-specified designator (that isn't
11310 /// necessarily valid). Note that this always returns 'true' if the LValue has
11311 /// an unsized array as its first designator entry, because there's currently no
11312 /// way to tell if the user typed *foo or foo[0].
11313 static bool refersToCompleteObject(const LValue &LVal) {
11314   if (LVal.Designator.Invalid)
11315     return false;
11316 
11317   if (!LVal.Designator.Entries.empty())
11318     return LVal.Designator.isMostDerivedAnUnsizedArray();
11319 
11320   if (!LVal.InvalidBase)
11321     return true;
11322 
11323   // If `E` is a MemberExpr, then the first part of the designator is hiding in
11324   // the LValueBase.
11325   const auto *E = LVal.Base.dyn_cast<const Expr *>();
11326   return !E || !isa<MemberExpr>(E);
11327 }
11328 
11329 /// Attempts to detect a user writing into a piece of memory that's impossible
11330 /// to figure out the size of by just using types.
11331 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
11332   const SubobjectDesignator &Designator = LVal.Designator;
11333   // Notes:
11334   // - Users can only write off of the end when we have an invalid base. Invalid
11335   //   bases imply we don't know where the memory came from.
11336   // - We used to be a bit more aggressive here; we'd only be conservative if
11337   //   the array at the end was flexible, or if it had 0 or 1 elements. This
11338   //   broke some common standard library extensions (PR30346), but was
11339   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
11340   //   with some sort of list. OTOH, it seems that GCC is always
11341   //   conservative with the last element in structs (if it's an array), so our
11342   //   current behavior is more compatible than an explicit list approach would
11343   //   be.
11344   return LVal.InvalidBase &&
11345          Designator.Entries.size() == Designator.MostDerivedPathLength &&
11346          Designator.MostDerivedIsArrayElement &&
11347          isDesignatorAtObjectEnd(Ctx, LVal);
11348 }
11349 
11350 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
11351 /// Fails if the conversion would cause loss of precision.
11352 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
11353                                             CharUnits &Result) {
11354   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
11355   if (Int.ugt(CharUnitsMax))
11356     return false;
11357   Result = CharUnits::fromQuantity(Int.getZExtValue());
11358   return true;
11359 }
11360 
11361 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
11362 /// determine how many bytes exist from the beginning of the object to either
11363 /// the end of the current subobject, or the end of the object itself, depending
11364 /// on what the LValue looks like + the value of Type.
11365 ///
11366 /// If this returns false, the value of Result is undefined.
11367 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
11368                                unsigned Type, const LValue &LVal,
11369                                CharUnits &EndOffset) {
11370   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
11371 
11372   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
11373     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
11374       return false;
11375     return HandleSizeof(Info, ExprLoc, Ty, Result);
11376   };
11377 
11378   // We want to evaluate the size of the entire object. This is a valid fallback
11379   // for when Type=1 and the designator is invalid, because we're asked for an
11380   // upper-bound.
11381   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
11382     // Type=3 wants a lower bound, so we can't fall back to this.
11383     if (Type == 3 && !DetermineForCompleteObject)
11384       return false;
11385 
11386     llvm::APInt APEndOffset;
11387     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11388         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11389       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11390 
11391     if (LVal.InvalidBase)
11392       return false;
11393 
11394     QualType BaseTy = getObjectType(LVal.getLValueBase());
11395     return CheckedHandleSizeof(BaseTy, EndOffset);
11396   }
11397 
11398   // We want to evaluate the size of a subobject.
11399   const SubobjectDesignator &Designator = LVal.Designator;
11400 
11401   // The following is a moderately common idiom in C:
11402   //
11403   // struct Foo { int a; char c[1]; };
11404   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
11405   // strcpy(&F->c[0], Bar);
11406   //
11407   // In order to not break too much legacy code, we need to support it.
11408   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
11409     // If we can resolve this to an alloc_size call, we can hand that back,
11410     // because we know for certain how many bytes there are to write to.
11411     llvm::APInt APEndOffset;
11412     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
11413         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
11414       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
11415 
11416     // If we cannot determine the size of the initial allocation, then we can't
11417     // given an accurate upper-bound. However, we are still able to give
11418     // conservative lower-bounds for Type=3.
11419     if (Type == 1)
11420       return false;
11421   }
11422 
11423   CharUnits BytesPerElem;
11424   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
11425     return false;
11426 
11427   // According to the GCC documentation, we want the size of the subobject
11428   // denoted by the pointer. But that's not quite right -- what we actually
11429   // want is the size of the immediately-enclosing array, if there is one.
11430   int64_t ElemsRemaining;
11431   if (Designator.MostDerivedIsArrayElement &&
11432       Designator.Entries.size() == Designator.MostDerivedPathLength) {
11433     uint64_t ArraySize = Designator.getMostDerivedArraySize();
11434     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
11435     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
11436   } else {
11437     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
11438   }
11439 
11440   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
11441   return true;
11442 }
11443 
11444 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
11445 /// returns true and stores the result in @p Size.
11446 ///
11447 /// If @p WasError is non-null, this will report whether the failure to evaluate
11448 /// is to be treated as an Error in IntExprEvaluator.
11449 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
11450                                          EvalInfo &Info, uint64_t &Size) {
11451   // Determine the denoted object.
11452   LValue LVal;
11453   {
11454     // The operand of __builtin_object_size is never evaluated for side-effects.
11455     // If there are any, but we can determine the pointed-to object anyway, then
11456     // ignore the side-effects.
11457     SpeculativeEvaluationRAII SpeculativeEval(Info);
11458     IgnoreSideEffectsRAII Fold(Info);
11459 
11460     if (E->isGLValue()) {
11461       // It's possible for us to be given GLValues if we're called via
11462       // Expr::tryEvaluateObjectSize.
11463       APValue RVal;
11464       if (!EvaluateAsRValue(Info, E, RVal))
11465         return false;
11466       LVal.setFrom(Info.Ctx, RVal);
11467     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
11468                                 /*InvalidBaseOK=*/true))
11469       return false;
11470   }
11471 
11472   // If we point to before the start of the object, there are no accessible
11473   // bytes.
11474   if (LVal.getLValueOffset().isNegative()) {
11475     Size = 0;
11476     return true;
11477   }
11478 
11479   CharUnits EndOffset;
11480   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
11481     return false;
11482 
11483   // If we've fallen outside of the end offset, just pretend there's nothing to
11484   // write to/read from.
11485   if (EndOffset <= LVal.getLValueOffset())
11486     Size = 0;
11487   else
11488     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
11489   return true;
11490 }
11491 
11492 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
11493   if (unsigned BuiltinOp = E->getBuiltinCallee())
11494     return VisitBuiltinCallExpr(E, BuiltinOp);
11495 
11496   return ExprEvaluatorBaseTy::VisitCallExpr(E);
11497 }
11498 
11499 static bool getBuiltinAlignArguments(const CallExpr *E, EvalInfo &Info,
11500                                      APValue &Val, APSInt &Alignment) {
11501   QualType SrcTy = E->getArg(0)->getType();
11502   if (!getAlignmentArgument(E->getArg(1), SrcTy, Info, Alignment))
11503     return false;
11504   // Even though we are evaluating integer expressions we could get a pointer
11505   // argument for the __builtin_is_aligned() case.
11506   if (SrcTy->isPointerType()) {
11507     LValue Ptr;
11508     if (!EvaluatePointer(E->getArg(0), Ptr, Info))
11509       return false;
11510     Ptr.moveInto(Val);
11511   } else if (!SrcTy->isIntegralOrEnumerationType()) {
11512     Info.FFDiag(E->getArg(0));
11513     return false;
11514   } else {
11515     APSInt SrcInt;
11516     if (!EvaluateInteger(E->getArg(0), SrcInt, Info))
11517       return false;
11518     assert(SrcInt.getBitWidth() >= Alignment.getBitWidth() &&
11519            "Bit widths must be the same");
11520     Val = APValue(SrcInt);
11521   }
11522   assert(Val.hasValue());
11523   return true;
11524 }
11525 
11526 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
11527                                             unsigned BuiltinOp) {
11528   switch (BuiltinOp) {
11529   default:
11530     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11531 
11532   case Builtin::BI__builtin_dynamic_object_size:
11533   case Builtin::BI__builtin_object_size: {
11534     // The type was checked when we built the expression.
11535     unsigned Type =
11536         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11537     assert(Type <= 3 && "unexpected type");
11538 
11539     uint64_t Size;
11540     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
11541       return Success(Size, E);
11542 
11543     if (E->getArg(0)->HasSideEffects(Info.Ctx))
11544       return Success((Type & 2) ? 0 : -1, E);
11545 
11546     // Expression had no side effects, but we couldn't statically determine the
11547     // size of the referenced object.
11548     switch (Info.EvalMode) {
11549     case EvalInfo::EM_ConstantExpression:
11550     case EvalInfo::EM_ConstantFold:
11551     case EvalInfo::EM_IgnoreSideEffects:
11552       // Leave it to IR generation.
11553       return Error(E);
11554     case EvalInfo::EM_ConstantExpressionUnevaluated:
11555       // Reduce it to a constant now.
11556       return Success((Type & 2) ? 0 : -1, E);
11557     }
11558 
11559     llvm_unreachable("unexpected EvalMode");
11560   }
11561 
11562   case Builtin::BI__builtin_os_log_format_buffer_size: {
11563     analyze_os_log::OSLogBufferLayout Layout;
11564     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
11565     return Success(Layout.size().getQuantity(), E);
11566   }
11567 
11568   case Builtin::BI__builtin_is_aligned: {
11569     APValue Src;
11570     APSInt Alignment;
11571     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11572       return false;
11573     if (Src.isLValue()) {
11574       // If we evaluated a pointer, check the minimum known alignment.
11575       LValue Ptr;
11576       Ptr.setFrom(Info.Ctx, Src);
11577       CharUnits BaseAlignment = getBaseAlignment(Info, Ptr);
11578       CharUnits PtrAlign = BaseAlignment.alignmentAtOffset(Ptr.Offset);
11579       // We can return true if the known alignment at the computed offset is
11580       // greater than the requested alignment.
11581       assert(PtrAlign.isPowerOfTwo());
11582       assert(Alignment.isPowerOf2());
11583       if (PtrAlign.getQuantity() >= Alignment)
11584         return Success(1, E);
11585       // If the alignment is not known to be sufficient, some cases could still
11586       // be aligned at run time. However, if the requested alignment is less or
11587       // equal to the base alignment and the offset is not aligned, we know that
11588       // the run-time value can never be aligned.
11589       if (BaseAlignment.getQuantity() >= Alignment &&
11590           PtrAlign.getQuantity() < Alignment)
11591         return Success(0, E);
11592       // Otherwise we can't infer whether the value is sufficiently aligned.
11593       // TODO: __builtin_is_aligned(__builtin_align_{down,up{(expr, N), N)
11594       //  in cases where we can't fully evaluate the pointer.
11595       Info.FFDiag(E->getArg(0), diag::note_constexpr_alignment_compute)
11596           << Alignment;
11597       return false;
11598     }
11599     assert(Src.isInt());
11600     return Success((Src.getInt() & (Alignment - 1)) == 0 ? 1 : 0, E);
11601   }
11602   case Builtin::BI__builtin_align_up: {
11603     APValue Src;
11604     APSInt Alignment;
11605     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11606       return false;
11607     if (!Src.isInt())
11608       return Error(E);
11609     APSInt AlignedVal =
11610         APSInt((Src.getInt() + (Alignment - 1)) & ~(Alignment - 1),
11611                Src.getInt().isUnsigned());
11612     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11613     return Success(AlignedVal, E);
11614   }
11615   case Builtin::BI__builtin_align_down: {
11616     APValue Src;
11617     APSInt Alignment;
11618     if (!getBuiltinAlignArguments(E, Info, Src, Alignment))
11619       return false;
11620     if (!Src.isInt())
11621       return Error(E);
11622     APSInt AlignedVal =
11623         APSInt(Src.getInt() & ~(Alignment - 1), Src.getInt().isUnsigned());
11624     assert(AlignedVal.getBitWidth() == Src.getInt().getBitWidth());
11625     return Success(AlignedVal, E);
11626   }
11627 
11628   case Builtin::BI__builtin_bitreverse8:
11629   case Builtin::BI__builtin_bitreverse16:
11630   case Builtin::BI__builtin_bitreverse32:
11631   case Builtin::BI__builtin_bitreverse64: {
11632     APSInt Val;
11633     if (!EvaluateInteger(E->getArg(0), Val, Info))
11634       return false;
11635 
11636     return Success(Val.reverseBits(), E);
11637   }
11638 
11639   case Builtin::BI__builtin_bswap16:
11640   case Builtin::BI__builtin_bswap32:
11641   case Builtin::BI__builtin_bswap64: {
11642     APSInt Val;
11643     if (!EvaluateInteger(E->getArg(0), Val, Info))
11644       return false;
11645 
11646     return Success(Val.byteSwap(), E);
11647   }
11648 
11649   case Builtin::BI__builtin_classify_type:
11650     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
11651 
11652   case Builtin::BI__builtin_clrsb:
11653   case Builtin::BI__builtin_clrsbl:
11654   case Builtin::BI__builtin_clrsbll: {
11655     APSInt Val;
11656     if (!EvaluateInteger(E->getArg(0), Val, Info))
11657       return false;
11658 
11659     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
11660   }
11661 
11662   case Builtin::BI__builtin_clz:
11663   case Builtin::BI__builtin_clzl:
11664   case Builtin::BI__builtin_clzll:
11665   case Builtin::BI__builtin_clzs: {
11666     APSInt Val;
11667     if (!EvaluateInteger(E->getArg(0), Val, Info))
11668       return false;
11669     if (!Val)
11670       return Error(E);
11671 
11672     return Success(Val.countLeadingZeros(), E);
11673   }
11674 
11675   case Builtin::BI__builtin_constant_p: {
11676     const Expr *Arg = E->getArg(0);
11677     if (EvaluateBuiltinConstantP(Info, Arg))
11678       return Success(true, E);
11679     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
11680       // Outside a constant context, eagerly evaluate to false in the presence
11681       // of side-effects in order to avoid -Wunsequenced false-positives in
11682       // a branch on __builtin_constant_p(expr).
11683       return Success(false, E);
11684     }
11685     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
11686     return false;
11687   }
11688 
11689   case Builtin::BI__builtin_is_constant_evaluated: {
11690     const auto *Callee = Info.CurrentCall->getCallee();
11691     if (Info.InConstantContext && !Info.CheckingPotentialConstantExpression &&
11692         (Info.CallStackDepth == 1 ||
11693          (Info.CallStackDepth == 2 && Callee->isInStdNamespace() &&
11694           Callee->getIdentifier() &&
11695           Callee->getIdentifier()->isStr("is_constant_evaluated")))) {
11696       // FIXME: Find a better way to avoid duplicated diagnostics.
11697       if (Info.EvalStatus.Diag)
11698         Info.report((Info.CallStackDepth == 1) ? E->getExprLoc()
11699                                                : Info.CurrentCall->CallLoc,
11700                     diag::warn_is_constant_evaluated_always_true_constexpr)
11701             << (Info.CallStackDepth == 1 ? "__builtin_is_constant_evaluated"
11702                                          : "std::is_constant_evaluated");
11703     }
11704 
11705     return Success(Info.InConstantContext, E);
11706   }
11707 
11708   case Builtin::BI__builtin_ctz:
11709   case Builtin::BI__builtin_ctzl:
11710   case Builtin::BI__builtin_ctzll:
11711   case Builtin::BI__builtin_ctzs: {
11712     APSInt Val;
11713     if (!EvaluateInteger(E->getArg(0), Val, Info))
11714       return false;
11715     if (!Val)
11716       return Error(E);
11717 
11718     return Success(Val.countTrailingZeros(), E);
11719   }
11720 
11721   case Builtin::BI__builtin_eh_return_data_regno: {
11722     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
11723     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
11724     return Success(Operand, E);
11725   }
11726 
11727   case Builtin::BI__builtin_expect:
11728   case Builtin::BI__builtin_expect_with_probability:
11729     return Visit(E->getArg(0));
11730 
11731   case Builtin::BI__builtin_ffs:
11732   case Builtin::BI__builtin_ffsl:
11733   case Builtin::BI__builtin_ffsll: {
11734     APSInt Val;
11735     if (!EvaluateInteger(E->getArg(0), Val, Info))
11736       return false;
11737 
11738     unsigned N = Val.countTrailingZeros();
11739     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
11740   }
11741 
11742   case Builtin::BI__builtin_fpclassify: {
11743     APFloat Val(0.0);
11744     if (!EvaluateFloat(E->getArg(5), Val, Info))
11745       return false;
11746     unsigned Arg;
11747     switch (Val.getCategory()) {
11748     case APFloat::fcNaN: Arg = 0; break;
11749     case APFloat::fcInfinity: Arg = 1; break;
11750     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
11751     case APFloat::fcZero: Arg = 4; break;
11752     }
11753     return Visit(E->getArg(Arg));
11754   }
11755 
11756   case Builtin::BI__builtin_isinf_sign: {
11757     APFloat Val(0.0);
11758     return EvaluateFloat(E->getArg(0), Val, Info) &&
11759            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
11760   }
11761 
11762   case Builtin::BI__builtin_isinf: {
11763     APFloat Val(0.0);
11764     return EvaluateFloat(E->getArg(0), Val, Info) &&
11765            Success(Val.isInfinity() ? 1 : 0, E);
11766   }
11767 
11768   case Builtin::BI__builtin_isfinite: {
11769     APFloat Val(0.0);
11770     return EvaluateFloat(E->getArg(0), Val, Info) &&
11771            Success(Val.isFinite() ? 1 : 0, E);
11772   }
11773 
11774   case Builtin::BI__builtin_isnan: {
11775     APFloat Val(0.0);
11776     return EvaluateFloat(E->getArg(0), Val, Info) &&
11777            Success(Val.isNaN() ? 1 : 0, E);
11778   }
11779 
11780   case Builtin::BI__builtin_isnormal: {
11781     APFloat Val(0.0);
11782     return EvaluateFloat(E->getArg(0), Val, Info) &&
11783            Success(Val.isNormal() ? 1 : 0, E);
11784   }
11785 
11786   case Builtin::BI__builtin_parity:
11787   case Builtin::BI__builtin_parityl:
11788   case Builtin::BI__builtin_parityll: {
11789     APSInt Val;
11790     if (!EvaluateInteger(E->getArg(0), Val, Info))
11791       return false;
11792 
11793     return Success(Val.countPopulation() % 2, E);
11794   }
11795 
11796   case Builtin::BI__builtin_popcount:
11797   case Builtin::BI__builtin_popcountl:
11798   case Builtin::BI__builtin_popcountll: {
11799     APSInt Val;
11800     if (!EvaluateInteger(E->getArg(0), Val, Info))
11801       return false;
11802 
11803     return Success(Val.countPopulation(), E);
11804   }
11805 
11806   case Builtin::BI__builtin_rotateleft8:
11807   case Builtin::BI__builtin_rotateleft16:
11808   case Builtin::BI__builtin_rotateleft32:
11809   case Builtin::BI__builtin_rotateleft64:
11810   case Builtin::BI_rotl8: // Microsoft variants of rotate right
11811   case Builtin::BI_rotl16:
11812   case Builtin::BI_rotl:
11813   case Builtin::BI_lrotl:
11814   case Builtin::BI_rotl64: {
11815     APSInt Val, Amt;
11816     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11817         !EvaluateInteger(E->getArg(1), Amt, Info))
11818       return false;
11819 
11820     return Success(Val.rotl(Amt.urem(Val.getBitWidth())), E);
11821   }
11822 
11823   case Builtin::BI__builtin_rotateright8:
11824   case Builtin::BI__builtin_rotateright16:
11825   case Builtin::BI__builtin_rotateright32:
11826   case Builtin::BI__builtin_rotateright64:
11827   case Builtin::BI_rotr8: // Microsoft variants of rotate right
11828   case Builtin::BI_rotr16:
11829   case Builtin::BI_rotr:
11830   case Builtin::BI_lrotr:
11831   case Builtin::BI_rotr64: {
11832     APSInt Val, Amt;
11833     if (!EvaluateInteger(E->getArg(0), Val, Info) ||
11834         !EvaluateInteger(E->getArg(1), Amt, Info))
11835       return false;
11836 
11837     return Success(Val.rotr(Amt.urem(Val.getBitWidth())), E);
11838   }
11839 
11840   case Builtin::BIstrlen:
11841   case Builtin::BIwcslen:
11842     // A call to strlen is not a constant expression.
11843     if (Info.getLangOpts().CPlusPlus11)
11844       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11845         << /*isConstexpr*/0 << /*isConstructor*/0
11846         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11847     else
11848       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11849     LLVM_FALLTHROUGH;
11850   case Builtin::BI__builtin_strlen:
11851   case Builtin::BI__builtin_wcslen: {
11852     // As an extension, we support __builtin_strlen() as a constant expression,
11853     // and support folding strlen() to a constant.
11854     uint64_t StrLen;
11855     if (EvaluateBuiltinStrLen(E->getArg(0), StrLen, Info))
11856       return Success(StrLen, E);
11857     return false;
11858   }
11859 
11860   case Builtin::BIstrcmp:
11861   case Builtin::BIwcscmp:
11862   case Builtin::BIstrncmp:
11863   case Builtin::BIwcsncmp:
11864   case Builtin::BImemcmp:
11865   case Builtin::BIbcmp:
11866   case Builtin::BIwmemcmp:
11867     // A call to strlen is not a constant expression.
11868     if (Info.getLangOpts().CPlusPlus11)
11869       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
11870         << /*isConstexpr*/0 << /*isConstructor*/0
11871         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
11872     else
11873       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
11874     LLVM_FALLTHROUGH;
11875   case Builtin::BI__builtin_strcmp:
11876   case Builtin::BI__builtin_wcscmp:
11877   case Builtin::BI__builtin_strncmp:
11878   case Builtin::BI__builtin_wcsncmp:
11879   case Builtin::BI__builtin_memcmp:
11880   case Builtin::BI__builtin_bcmp:
11881   case Builtin::BI__builtin_wmemcmp: {
11882     LValue String1, String2;
11883     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
11884         !EvaluatePointer(E->getArg(1), String2, Info))
11885       return false;
11886 
11887     uint64_t MaxLength = uint64_t(-1);
11888     if (BuiltinOp != Builtin::BIstrcmp &&
11889         BuiltinOp != Builtin::BIwcscmp &&
11890         BuiltinOp != Builtin::BI__builtin_strcmp &&
11891         BuiltinOp != Builtin::BI__builtin_wcscmp) {
11892       APSInt N;
11893       if (!EvaluateInteger(E->getArg(2), N, Info))
11894         return false;
11895       MaxLength = N.getExtValue();
11896     }
11897 
11898     // Empty substrings compare equal by definition.
11899     if (MaxLength == 0u)
11900       return Success(0, E);
11901 
11902     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11903         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
11904         String1.Designator.Invalid || String2.Designator.Invalid)
11905       return false;
11906 
11907     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
11908     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
11909 
11910     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
11911                      BuiltinOp == Builtin::BIbcmp ||
11912                      BuiltinOp == Builtin::BI__builtin_memcmp ||
11913                      BuiltinOp == Builtin::BI__builtin_bcmp;
11914 
11915     assert(IsRawByte ||
11916            (Info.Ctx.hasSameUnqualifiedType(
11917                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
11918             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
11919 
11920     // For memcmp, allow comparing any arrays of '[[un]signed] char' or
11921     // 'char8_t', but no other types.
11922     if (IsRawByte &&
11923         !(isOneByteCharacterType(CharTy1) && isOneByteCharacterType(CharTy2))) {
11924       // FIXME: Consider using our bit_cast implementation to support this.
11925       Info.FFDiag(E, diag::note_constexpr_memcmp_unsupported)
11926           << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'")
11927           << CharTy1 << CharTy2;
11928       return false;
11929     }
11930 
11931     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
11932       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
11933              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
11934              Char1.isInt() && Char2.isInt();
11935     };
11936     const auto &AdvanceElems = [&] {
11937       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
11938              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
11939     };
11940 
11941     bool StopAtNull =
11942         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
11943          BuiltinOp != Builtin::BIwmemcmp &&
11944          BuiltinOp != Builtin::BI__builtin_memcmp &&
11945          BuiltinOp != Builtin::BI__builtin_bcmp &&
11946          BuiltinOp != Builtin::BI__builtin_wmemcmp);
11947     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
11948                   BuiltinOp == Builtin::BIwcsncmp ||
11949                   BuiltinOp == Builtin::BIwmemcmp ||
11950                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
11951                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
11952                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
11953 
11954     for (; MaxLength; --MaxLength) {
11955       APValue Char1, Char2;
11956       if (!ReadCurElems(Char1, Char2))
11957         return false;
11958       if (Char1.getInt().ne(Char2.getInt())) {
11959         if (IsWide) // wmemcmp compares with wchar_t signedness.
11960           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
11961         // memcmp always compares unsigned chars.
11962         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
11963       }
11964       if (StopAtNull && !Char1.getInt())
11965         return Success(0, E);
11966       assert(!(StopAtNull && !Char2.getInt()));
11967       if (!AdvanceElems())
11968         return false;
11969     }
11970     // We hit the strncmp / memcmp limit.
11971     return Success(0, E);
11972   }
11973 
11974   case Builtin::BI__atomic_always_lock_free:
11975   case Builtin::BI__atomic_is_lock_free:
11976   case Builtin::BI__c11_atomic_is_lock_free: {
11977     APSInt SizeVal;
11978     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
11979       return false;
11980 
11981     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
11982     // of two less than or equal to the maximum inline atomic width, we know it
11983     // is lock-free.  If the size isn't a power of two, or greater than the
11984     // maximum alignment where we promote atomics, we know it is not lock-free
11985     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
11986     // the answer can only be determined at runtime; for example, 16-byte
11987     // atomics have lock-free implementations on some, but not all,
11988     // x86-64 processors.
11989 
11990     // Check power-of-two.
11991     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
11992     if (Size.isPowerOfTwo()) {
11993       // Check against inlining width.
11994       unsigned InlineWidthBits =
11995           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
11996       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
11997         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
11998             Size == CharUnits::One() ||
11999             E->getArg(1)->isNullPointerConstant(Info.Ctx,
12000                                                 Expr::NPC_NeverValueDependent))
12001           // OK, we will inline appropriately-aligned operations of this size,
12002           // and _Atomic(T) is appropriately-aligned.
12003           return Success(1, E);
12004 
12005         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
12006           castAs<PointerType>()->getPointeeType();
12007         if (!PointeeType->isIncompleteType() &&
12008             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
12009           // OK, we will inline operations on this object.
12010           return Success(1, E);
12011         }
12012       }
12013     }
12014 
12015     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
12016         Success(0, E) : Error(E);
12017   }
12018   case Builtin::BI__builtin_add_overflow:
12019   case Builtin::BI__builtin_sub_overflow:
12020   case Builtin::BI__builtin_mul_overflow:
12021   case Builtin::BI__builtin_sadd_overflow:
12022   case Builtin::BI__builtin_uadd_overflow:
12023   case Builtin::BI__builtin_uaddl_overflow:
12024   case Builtin::BI__builtin_uaddll_overflow:
12025   case Builtin::BI__builtin_usub_overflow:
12026   case Builtin::BI__builtin_usubl_overflow:
12027   case Builtin::BI__builtin_usubll_overflow:
12028   case Builtin::BI__builtin_umul_overflow:
12029   case Builtin::BI__builtin_umull_overflow:
12030   case Builtin::BI__builtin_umulll_overflow:
12031   case Builtin::BI__builtin_saddl_overflow:
12032   case Builtin::BI__builtin_saddll_overflow:
12033   case Builtin::BI__builtin_ssub_overflow:
12034   case Builtin::BI__builtin_ssubl_overflow:
12035   case Builtin::BI__builtin_ssubll_overflow:
12036   case Builtin::BI__builtin_smul_overflow:
12037   case Builtin::BI__builtin_smull_overflow:
12038   case Builtin::BI__builtin_smulll_overflow: {
12039     LValue ResultLValue;
12040     APSInt LHS, RHS;
12041 
12042     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
12043     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
12044         !EvaluateInteger(E->getArg(1), RHS, Info) ||
12045         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
12046       return false;
12047 
12048     APSInt Result;
12049     bool DidOverflow = false;
12050 
12051     // If the types don't have to match, enlarge all 3 to the largest of them.
12052     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12053         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12054         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12055       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
12056                       ResultType->isSignedIntegerOrEnumerationType();
12057       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
12058                       ResultType->isSignedIntegerOrEnumerationType();
12059       uint64_t LHSSize = LHS.getBitWidth();
12060       uint64_t RHSSize = RHS.getBitWidth();
12061       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
12062       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
12063 
12064       // Add an additional bit if the signedness isn't uniformly agreed to. We
12065       // could do this ONLY if there is a signed and an unsigned that both have
12066       // MaxBits, but the code to check that is pretty nasty.  The issue will be
12067       // caught in the shrink-to-result later anyway.
12068       if (IsSigned && !AllSigned)
12069         ++MaxBits;
12070 
12071       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
12072       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
12073       Result = APSInt(MaxBits, !IsSigned);
12074     }
12075 
12076     // Find largest int.
12077     switch (BuiltinOp) {
12078     default:
12079       llvm_unreachable("Invalid value for BuiltinOp");
12080     case Builtin::BI__builtin_add_overflow:
12081     case Builtin::BI__builtin_sadd_overflow:
12082     case Builtin::BI__builtin_saddl_overflow:
12083     case Builtin::BI__builtin_saddll_overflow:
12084     case Builtin::BI__builtin_uadd_overflow:
12085     case Builtin::BI__builtin_uaddl_overflow:
12086     case Builtin::BI__builtin_uaddll_overflow:
12087       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
12088                               : LHS.uadd_ov(RHS, DidOverflow);
12089       break;
12090     case Builtin::BI__builtin_sub_overflow:
12091     case Builtin::BI__builtin_ssub_overflow:
12092     case Builtin::BI__builtin_ssubl_overflow:
12093     case Builtin::BI__builtin_ssubll_overflow:
12094     case Builtin::BI__builtin_usub_overflow:
12095     case Builtin::BI__builtin_usubl_overflow:
12096     case Builtin::BI__builtin_usubll_overflow:
12097       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
12098                               : LHS.usub_ov(RHS, DidOverflow);
12099       break;
12100     case Builtin::BI__builtin_mul_overflow:
12101     case Builtin::BI__builtin_smul_overflow:
12102     case Builtin::BI__builtin_smull_overflow:
12103     case Builtin::BI__builtin_smulll_overflow:
12104     case Builtin::BI__builtin_umul_overflow:
12105     case Builtin::BI__builtin_umull_overflow:
12106     case Builtin::BI__builtin_umulll_overflow:
12107       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
12108                               : LHS.umul_ov(RHS, DidOverflow);
12109       break;
12110     }
12111 
12112     // In the case where multiple sizes are allowed, truncate and see if
12113     // the values are the same.
12114     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
12115         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
12116         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
12117       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
12118       // since it will give us the behavior of a TruncOrSelf in the case where
12119       // its parameter <= its size.  We previously set Result to be at least the
12120       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
12121       // will work exactly like TruncOrSelf.
12122       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
12123       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
12124 
12125       if (!APSInt::isSameValue(Temp, Result))
12126         DidOverflow = true;
12127       Result = Temp;
12128     }
12129 
12130     APValue APV{Result};
12131     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
12132       return false;
12133     return Success(DidOverflow, E);
12134   }
12135   }
12136 }
12137 
12138 /// Determine whether this is a pointer past the end of the complete
12139 /// object referred to by the lvalue.
12140 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
12141                                             const LValue &LV) {
12142   // A null pointer can be viewed as being "past the end" but we don't
12143   // choose to look at it that way here.
12144   if (!LV.getLValueBase())
12145     return false;
12146 
12147   // If the designator is valid and refers to a subobject, we're not pointing
12148   // past the end.
12149   if (!LV.getLValueDesignator().Invalid &&
12150       !LV.getLValueDesignator().isOnePastTheEnd())
12151     return false;
12152 
12153   // A pointer to an incomplete type might be past-the-end if the type's size is
12154   // zero.  We cannot tell because the type is incomplete.
12155   QualType Ty = getType(LV.getLValueBase());
12156   if (Ty->isIncompleteType())
12157     return true;
12158 
12159   // We're a past-the-end pointer if we point to the byte after the object,
12160   // no matter what our type or path is.
12161   auto Size = Ctx.getTypeSizeInChars(Ty);
12162   return LV.getLValueOffset() == Size;
12163 }
12164 
12165 namespace {
12166 
12167 /// Data recursive integer evaluator of certain binary operators.
12168 ///
12169 /// We use a data recursive algorithm for binary operators so that we are able
12170 /// to handle extreme cases of chained binary operators without causing stack
12171 /// overflow.
12172 class DataRecursiveIntBinOpEvaluator {
12173   struct EvalResult {
12174     APValue Val;
12175     bool Failed;
12176 
12177     EvalResult() : Failed(false) { }
12178 
12179     void swap(EvalResult &RHS) {
12180       Val.swap(RHS.Val);
12181       Failed = RHS.Failed;
12182       RHS.Failed = false;
12183     }
12184   };
12185 
12186   struct Job {
12187     const Expr *E;
12188     EvalResult LHSResult; // meaningful only for binary operator expression.
12189     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
12190 
12191     Job() = default;
12192     Job(Job &&) = default;
12193 
12194     void startSpeculativeEval(EvalInfo &Info) {
12195       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
12196     }
12197 
12198   private:
12199     SpeculativeEvaluationRAII SpecEvalRAII;
12200   };
12201 
12202   SmallVector<Job, 16> Queue;
12203 
12204   IntExprEvaluator &IntEval;
12205   EvalInfo &Info;
12206   APValue &FinalResult;
12207 
12208 public:
12209   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
12210     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
12211 
12212   /// True if \param E is a binary operator that we are going to handle
12213   /// data recursively.
12214   /// We handle binary operators that are comma, logical, or that have operands
12215   /// with integral or enumeration type.
12216   static bool shouldEnqueue(const BinaryOperator *E) {
12217     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
12218            (E->isPRValue() && E->getType()->isIntegralOrEnumerationType() &&
12219             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12220             E->getRHS()->getType()->isIntegralOrEnumerationType());
12221   }
12222 
12223   bool Traverse(const BinaryOperator *E) {
12224     enqueue(E);
12225     EvalResult PrevResult;
12226     while (!Queue.empty())
12227       process(PrevResult);
12228 
12229     if (PrevResult.Failed) return false;
12230 
12231     FinalResult.swap(PrevResult.Val);
12232     return true;
12233   }
12234 
12235 private:
12236   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
12237     return IntEval.Success(Value, E, Result);
12238   }
12239   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
12240     return IntEval.Success(Value, E, Result);
12241   }
12242   bool Error(const Expr *E) {
12243     return IntEval.Error(E);
12244   }
12245   bool Error(const Expr *E, diag::kind D) {
12246     return IntEval.Error(E, D);
12247   }
12248 
12249   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
12250     return Info.CCEDiag(E, D);
12251   }
12252 
12253   // Returns true if visiting the RHS is necessary, false otherwise.
12254   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12255                          bool &SuppressRHSDiags);
12256 
12257   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12258                   const BinaryOperator *E, APValue &Result);
12259 
12260   void EvaluateExpr(const Expr *E, EvalResult &Result) {
12261     Result.Failed = !Evaluate(Result.Val, Info, E);
12262     if (Result.Failed)
12263       Result.Val = APValue();
12264   }
12265 
12266   void process(EvalResult &Result);
12267 
12268   void enqueue(const Expr *E) {
12269     E = E->IgnoreParens();
12270     Queue.resize(Queue.size()+1);
12271     Queue.back().E = E;
12272     Queue.back().Kind = Job::AnyExprKind;
12273   }
12274 };
12275 
12276 }
12277 
12278 bool DataRecursiveIntBinOpEvaluator::
12279        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
12280                          bool &SuppressRHSDiags) {
12281   if (E->getOpcode() == BO_Comma) {
12282     // Ignore LHS but note if we could not evaluate it.
12283     if (LHSResult.Failed)
12284       return Info.noteSideEffect();
12285     return true;
12286   }
12287 
12288   if (E->isLogicalOp()) {
12289     bool LHSAsBool;
12290     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
12291       // We were able to evaluate the LHS, see if we can get away with not
12292       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
12293       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
12294         Success(LHSAsBool, E, LHSResult.Val);
12295         return false; // Ignore RHS
12296       }
12297     } else {
12298       LHSResult.Failed = true;
12299 
12300       // Since we weren't able to evaluate the left hand side, it
12301       // might have had side effects.
12302       if (!Info.noteSideEffect())
12303         return false;
12304 
12305       // We can't evaluate the LHS; however, sometimes the result
12306       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12307       // Don't ignore RHS and suppress diagnostics from this arm.
12308       SuppressRHSDiags = true;
12309     }
12310 
12311     return true;
12312   }
12313 
12314   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12315          E->getRHS()->getType()->isIntegralOrEnumerationType());
12316 
12317   if (LHSResult.Failed && !Info.noteFailure())
12318     return false; // Ignore RHS;
12319 
12320   return true;
12321 }
12322 
12323 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
12324                                     bool IsSub) {
12325   // Compute the new offset in the appropriate width, wrapping at 64 bits.
12326   // FIXME: When compiling for a 32-bit target, we should use 32-bit
12327   // offsets.
12328   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
12329   CharUnits &Offset = LVal.getLValueOffset();
12330   uint64_t Offset64 = Offset.getQuantity();
12331   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
12332   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
12333                                          : Offset64 + Index64);
12334 }
12335 
12336 bool DataRecursiveIntBinOpEvaluator::
12337        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
12338                   const BinaryOperator *E, APValue &Result) {
12339   if (E->getOpcode() == BO_Comma) {
12340     if (RHSResult.Failed)
12341       return false;
12342     Result = RHSResult.Val;
12343     return true;
12344   }
12345 
12346   if (E->isLogicalOp()) {
12347     bool lhsResult, rhsResult;
12348     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
12349     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
12350 
12351     if (LHSIsOK) {
12352       if (RHSIsOK) {
12353         if (E->getOpcode() == BO_LOr)
12354           return Success(lhsResult || rhsResult, E, Result);
12355         else
12356           return Success(lhsResult && rhsResult, E, Result);
12357       }
12358     } else {
12359       if (RHSIsOK) {
12360         // We can't evaluate the LHS; however, sometimes the result
12361         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
12362         if (rhsResult == (E->getOpcode() == BO_LOr))
12363           return Success(rhsResult, E, Result);
12364       }
12365     }
12366 
12367     return false;
12368   }
12369 
12370   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
12371          E->getRHS()->getType()->isIntegralOrEnumerationType());
12372 
12373   if (LHSResult.Failed || RHSResult.Failed)
12374     return false;
12375 
12376   const APValue &LHSVal = LHSResult.Val;
12377   const APValue &RHSVal = RHSResult.Val;
12378 
12379   // Handle cases like (unsigned long)&a + 4.
12380   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
12381     Result = LHSVal;
12382     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
12383     return true;
12384   }
12385 
12386   // Handle cases like 4 + (unsigned long)&a
12387   if (E->getOpcode() == BO_Add &&
12388       RHSVal.isLValue() && LHSVal.isInt()) {
12389     Result = RHSVal;
12390     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
12391     return true;
12392   }
12393 
12394   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
12395     // Handle (intptr_t)&&A - (intptr_t)&&B.
12396     if (!LHSVal.getLValueOffset().isZero() ||
12397         !RHSVal.getLValueOffset().isZero())
12398       return false;
12399     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
12400     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
12401     if (!LHSExpr || !RHSExpr)
12402       return false;
12403     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12404     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12405     if (!LHSAddrExpr || !RHSAddrExpr)
12406       return false;
12407     // Make sure both labels come from the same function.
12408     if (LHSAddrExpr->getLabel()->getDeclContext() !=
12409         RHSAddrExpr->getLabel()->getDeclContext())
12410       return false;
12411     Result = APValue(LHSAddrExpr, RHSAddrExpr);
12412     return true;
12413   }
12414 
12415   // All the remaining cases expect both operands to be an integer
12416   if (!LHSVal.isInt() || !RHSVal.isInt())
12417     return Error(E);
12418 
12419   // Set up the width and signedness manually, in case it can't be deduced
12420   // from the operation we're performing.
12421   // FIXME: Don't do this in the cases where we can deduce it.
12422   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
12423                E->getType()->isUnsignedIntegerOrEnumerationType());
12424   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
12425                          RHSVal.getInt(), Value))
12426     return false;
12427   return Success(Value, E, Result);
12428 }
12429 
12430 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
12431   Job &job = Queue.back();
12432 
12433   switch (job.Kind) {
12434     case Job::AnyExprKind: {
12435       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
12436         if (shouldEnqueue(Bop)) {
12437           job.Kind = Job::BinOpKind;
12438           enqueue(Bop->getLHS());
12439           return;
12440         }
12441       }
12442 
12443       EvaluateExpr(job.E, Result);
12444       Queue.pop_back();
12445       return;
12446     }
12447 
12448     case Job::BinOpKind: {
12449       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12450       bool SuppressRHSDiags = false;
12451       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
12452         Queue.pop_back();
12453         return;
12454       }
12455       if (SuppressRHSDiags)
12456         job.startSpeculativeEval(Info);
12457       job.LHSResult.swap(Result);
12458       job.Kind = Job::BinOpVisitedLHSKind;
12459       enqueue(Bop->getRHS());
12460       return;
12461     }
12462 
12463     case Job::BinOpVisitedLHSKind: {
12464       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
12465       EvalResult RHS;
12466       RHS.swap(Result);
12467       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
12468       Queue.pop_back();
12469       return;
12470     }
12471   }
12472 
12473   llvm_unreachable("Invalid Job::Kind!");
12474 }
12475 
12476 namespace {
12477 enum class CmpResult {
12478   Unequal,
12479   Less,
12480   Equal,
12481   Greater,
12482   Unordered,
12483 };
12484 }
12485 
12486 template <class SuccessCB, class AfterCB>
12487 static bool
12488 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
12489                                  SuccessCB &&Success, AfterCB &&DoAfter) {
12490   assert(!E->isValueDependent());
12491   assert(E->isComparisonOp() && "expected comparison operator");
12492   assert((E->getOpcode() == BO_Cmp ||
12493           E->getType()->isIntegralOrEnumerationType()) &&
12494          "unsupported binary expression evaluation");
12495   auto Error = [&](const Expr *E) {
12496     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12497     return false;
12498   };
12499 
12500   bool IsRelational = E->isRelationalOp() || E->getOpcode() == BO_Cmp;
12501   bool IsEquality = E->isEqualityOp();
12502 
12503   QualType LHSTy = E->getLHS()->getType();
12504   QualType RHSTy = E->getRHS()->getType();
12505 
12506   if (LHSTy->isIntegralOrEnumerationType() &&
12507       RHSTy->isIntegralOrEnumerationType()) {
12508     APSInt LHS, RHS;
12509     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
12510     if (!LHSOK && !Info.noteFailure())
12511       return false;
12512     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
12513       return false;
12514     if (LHS < RHS)
12515       return Success(CmpResult::Less, E);
12516     if (LHS > RHS)
12517       return Success(CmpResult::Greater, E);
12518     return Success(CmpResult::Equal, E);
12519   }
12520 
12521   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
12522     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
12523     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
12524 
12525     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
12526     if (!LHSOK && !Info.noteFailure())
12527       return false;
12528     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
12529       return false;
12530     if (LHSFX < RHSFX)
12531       return Success(CmpResult::Less, E);
12532     if (LHSFX > RHSFX)
12533       return Success(CmpResult::Greater, E);
12534     return Success(CmpResult::Equal, E);
12535   }
12536 
12537   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
12538     ComplexValue LHS, RHS;
12539     bool LHSOK;
12540     if (E->isAssignmentOp()) {
12541       LValue LV;
12542       EvaluateLValue(E->getLHS(), LV, Info);
12543       LHSOK = false;
12544     } else if (LHSTy->isRealFloatingType()) {
12545       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
12546       if (LHSOK) {
12547         LHS.makeComplexFloat();
12548         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
12549       }
12550     } else {
12551       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
12552     }
12553     if (!LHSOK && !Info.noteFailure())
12554       return false;
12555 
12556     if (E->getRHS()->getType()->isRealFloatingType()) {
12557       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
12558         return false;
12559       RHS.makeComplexFloat();
12560       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
12561     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
12562       return false;
12563 
12564     if (LHS.isComplexFloat()) {
12565       APFloat::cmpResult CR_r =
12566         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
12567       APFloat::cmpResult CR_i =
12568         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
12569       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
12570       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12571     } else {
12572       assert(IsEquality && "invalid complex comparison");
12573       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
12574                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
12575       return Success(IsEqual ? CmpResult::Equal : CmpResult::Unequal, E);
12576     }
12577   }
12578 
12579   if (LHSTy->isRealFloatingType() &&
12580       RHSTy->isRealFloatingType()) {
12581     APFloat RHS(0.0), LHS(0.0);
12582 
12583     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
12584     if (!LHSOK && !Info.noteFailure())
12585       return false;
12586 
12587     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
12588       return false;
12589 
12590     assert(E->isComparisonOp() && "Invalid binary operator!");
12591     llvm::APFloatBase::cmpResult APFloatCmpResult = LHS.compare(RHS);
12592     if (!Info.InConstantContext &&
12593         APFloatCmpResult == APFloat::cmpUnordered &&
12594         E->getFPFeaturesInEffect(Info.Ctx.getLangOpts()).isFPConstrained()) {
12595       // Note: Compares may raise invalid in some cases involving NaN or sNaN.
12596       Info.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
12597       return false;
12598     }
12599     auto GetCmpRes = [&]() {
12600       switch (APFloatCmpResult) {
12601       case APFloat::cmpEqual:
12602         return CmpResult::Equal;
12603       case APFloat::cmpLessThan:
12604         return CmpResult::Less;
12605       case APFloat::cmpGreaterThan:
12606         return CmpResult::Greater;
12607       case APFloat::cmpUnordered:
12608         return CmpResult::Unordered;
12609       }
12610       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
12611     };
12612     return Success(GetCmpRes(), E);
12613   }
12614 
12615   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
12616     LValue LHSValue, RHSValue;
12617 
12618     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12619     if (!LHSOK && !Info.noteFailure())
12620       return false;
12621 
12622     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12623       return false;
12624 
12625     // Reject differing bases from the normal codepath; we special-case
12626     // comparisons to null.
12627     if (!HasSameBase(LHSValue, RHSValue)) {
12628       // Inequalities and subtractions between unrelated pointers have
12629       // unspecified or undefined behavior.
12630       if (!IsEquality) {
12631         Info.FFDiag(E, diag::note_constexpr_pointer_comparison_unspecified);
12632         return false;
12633       }
12634       // A constant address may compare equal to the address of a symbol.
12635       // The one exception is that address of an object cannot compare equal
12636       // to a null pointer constant.
12637       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
12638           (!RHSValue.Base && !RHSValue.Offset.isZero()))
12639         return Error(E);
12640       // It's implementation-defined whether distinct literals will have
12641       // distinct addresses. In clang, the result of such a comparison is
12642       // unspecified, so it is not a constant expression. However, we do know
12643       // that the address of a literal will be non-null.
12644       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
12645           LHSValue.Base && RHSValue.Base)
12646         return Error(E);
12647       // We can't tell whether weak symbols will end up pointing to the same
12648       // object.
12649       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
12650         return Error(E);
12651       // We can't compare the address of the start of one object with the
12652       // past-the-end address of another object, per C++ DR1652.
12653       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
12654            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
12655           (RHSValue.Base && RHSValue.Offset.isZero() &&
12656            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
12657         return Error(E);
12658       // We can't tell whether an object is at the same address as another
12659       // zero sized object.
12660       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
12661           (LHSValue.Base && isZeroSized(RHSValue)))
12662         return Error(E);
12663       return Success(CmpResult::Unequal, E);
12664     }
12665 
12666     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12667     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12668 
12669     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12670     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12671 
12672     // C++11 [expr.rel]p3:
12673     //   Pointers to void (after pointer conversions) can be compared, with a
12674     //   result defined as follows: If both pointers represent the same
12675     //   address or are both the null pointer value, the result is true if the
12676     //   operator is <= or >= and false otherwise; otherwise the result is
12677     //   unspecified.
12678     // We interpret this as applying to pointers to *cv* void.
12679     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
12680       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
12681 
12682     // C++11 [expr.rel]p2:
12683     // - If two pointers point to non-static data members of the same object,
12684     //   or to subobjects or array elements fo such members, recursively, the
12685     //   pointer to the later declared member compares greater provided the
12686     //   two members have the same access control and provided their class is
12687     //   not a union.
12688     //   [...]
12689     // - Otherwise pointer comparisons are unspecified.
12690     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
12691       bool WasArrayIndex;
12692       unsigned Mismatch = FindDesignatorMismatch(
12693           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
12694       // At the point where the designators diverge, the comparison has a
12695       // specified value if:
12696       //  - we are comparing array indices
12697       //  - we are comparing fields of a union, or fields with the same access
12698       // Otherwise, the result is unspecified and thus the comparison is not a
12699       // constant expression.
12700       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
12701           Mismatch < RHSDesignator.Entries.size()) {
12702         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
12703         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
12704         if (!LF && !RF)
12705           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
12706         else if (!LF)
12707           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12708               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
12709               << RF->getParent() << RF;
12710         else if (!RF)
12711           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
12712               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
12713               << LF->getParent() << LF;
12714         else if (!LF->getParent()->isUnion() &&
12715                  LF->getAccess() != RF->getAccess())
12716           Info.CCEDiag(E,
12717                        diag::note_constexpr_pointer_comparison_differing_access)
12718               << LF << LF->getAccess() << RF << RF->getAccess()
12719               << LF->getParent();
12720       }
12721     }
12722 
12723     // The comparison here must be unsigned, and performed with the same
12724     // width as the pointer.
12725     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
12726     uint64_t CompareLHS = LHSOffset.getQuantity();
12727     uint64_t CompareRHS = RHSOffset.getQuantity();
12728     assert(PtrSize <= 64 && "Unexpected pointer width");
12729     uint64_t Mask = ~0ULL >> (64 - PtrSize);
12730     CompareLHS &= Mask;
12731     CompareRHS &= Mask;
12732 
12733     // If there is a base and this is a relational operator, we can only
12734     // compare pointers within the object in question; otherwise, the result
12735     // depends on where the object is located in memory.
12736     if (!LHSValue.Base.isNull() && IsRelational) {
12737       QualType BaseTy = getType(LHSValue.Base);
12738       if (BaseTy->isIncompleteType())
12739         return Error(E);
12740       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
12741       uint64_t OffsetLimit = Size.getQuantity();
12742       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
12743         return Error(E);
12744     }
12745 
12746     if (CompareLHS < CompareRHS)
12747       return Success(CmpResult::Less, E);
12748     if (CompareLHS > CompareRHS)
12749       return Success(CmpResult::Greater, E);
12750     return Success(CmpResult::Equal, E);
12751   }
12752 
12753   if (LHSTy->isMemberPointerType()) {
12754     assert(IsEquality && "unexpected member pointer operation");
12755     assert(RHSTy->isMemberPointerType() && "invalid comparison");
12756 
12757     MemberPtr LHSValue, RHSValue;
12758 
12759     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
12760     if (!LHSOK && !Info.noteFailure())
12761       return false;
12762 
12763     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12764       return false;
12765 
12766     // C++11 [expr.eq]p2:
12767     //   If both operands are null, they compare equal. Otherwise if only one is
12768     //   null, they compare unequal.
12769     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
12770       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
12771       return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12772     }
12773 
12774     //   Otherwise if either is a pointer to a virtual member function, the
12775     //   result is unspecified.
12776     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
12777       if (MD->isVirtual())
12778         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12779     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
12780       if (MD->isVirtual())
12781         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
12782 
12783     //   Otherwise they compare equal if and only if they would refer to the
12784     //   same member of the same most derived object or the same subobject if
12785     //   they were dereferenced with a hypothetical object of the associated
12786     //   class type.
12787     bool Equal = LHSValue == RHSValue;
12788     return Success(Equal ? CmpResult::Equal : CmpResult::Unequal, E);
12789   }
12790 
12791   if (LHSTy->isNullPtrType()) {
12792     assert(E->isComparisonOp() && "unexpected nullptr operation");
12793     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
12794     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
12795     // are compared, the result is true of the operator is <=, >= or ==, and
12796     // false otherwise.
12797     return Success(CmpResult::Equal, E);
12798   }
12799 
12800   return DoAfter();
12801 }
12802 
12803 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
12804   if (!CheckLiteralType(Info, E))
12805     return false;
12806 
12807   auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12808     ComparisonCategoryResult CCR;
12809     switch (CR) {
12810     case CmpResult::Unequal:
12811       llvm_unreachable("should never produce Unequal for three-way comparison");
12812     case CmpResult::Less:
12813       CCR = ComparisonCategoryResult::Less;
12814       break;
12815     case CmpResult::Equal:
12816       CCR = ComparisonCategoryResult::Equal;
12817       break;
12818     case CmpResult::Greater:
12819       CCR = ComparisonCategoryResult::Greater;
12820       break;
12821     case CmpResult::Unordered:
12822       CCR = ComparisonCategoryResult::Unordered;
12823       break;
12824     }
12825     // Evaluation succeeded. Lookup the information for the comparison category
12826     // type and fetch the VarDecl for the result.
12827     const ComparisonCategoryInfo &CmpInfo =
12828         Info.Ctx.CompCategories.getInfoForType(E->getType());
12829     const VarDecl *VD = CmpInfo.getValueInfo(CmpInfo.makeWeakResult(CCR))->VD;
12830     // Check and evaluate the result as a constant expression.
12831     LValue LV;
12832     LV.set(VD);
12833     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12834       return false;
12835     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
12836                                    ConstantExprKind::Normal);
12837   };
12838   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12839     return ExprEvaluatorBaseTy::VisitBinCmp(E);
12840   });
12841 }
12842 
12843 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
12844   // We don't support assignment in C. C++ assignments don't get here because
12845   // assignment is an lvalue in C++.
12846   if (E->isAssignmentOp()) {
12847     Error(E);
12848     if (!Info.noteFailure())
12849       return false;
12850   }
12851 
12852   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
12853     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
12854 
12855   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
12856           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
12857          "DataRecursiveIntBinOpEvaluator should have handled integral types");
12858 
12859   if (E->isComparisonOp()) {
12860     // Evaluate builtin binary comparisons by evaluating them as three-way
12861     // comparisons and then translating the result.
12862     auto OnSuccess = [&](CmpResult CR, const BinaryOperator *E) {
12863       assert((CR != CmpResult::Unequal || E->isEqualityOp()) &&
12864              "should only produce Unequal for equality comparisons");
12865       bool IsEqual   = CR == CmpResult::Equal,
12866            IsLess    = CR == CmpResult::Less,
12867            IsGreater = CR == CmpResult::Greater;
12868       auto Op = E->getOpcode();
12869       switch (Op) {
12870       default:
12871         llvm_unreachable("unsupported binary operator");
12872       case BO_EQ:
12873       case BO_NE:
12874         return Success(IsEqual == (Op == BO_EQ), E);
12875       case BO_LT:
12876         return Success(IsLess, E);
12877       case BO_GT:
12878         return Success(IsGreater, E);
12879       case BO_LE:
12880         return Success(IsEqual || IsLess, E);
12881       case BO_GE:
12882         return Success(IsEqual || IsGreater, E);
12883       }
12884     };
12885     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
12886       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12887     });
12888   }
12889 
12890   QualType LHSTy = E->getLHS()->getType();
12891   QualType RHSTy = E->getRHS()->getType();
12892 
12893   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
12894       E->getOpcode() == BO_Sub) {
12895     LValue LHSValue, RHSValue;
12896 
12897     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
12898     if (!LHSOK && !Info.noteFailure())
12899       return false;
12900 
12901     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
12902       return false;
12903 
12904     // Reject differing bases from the normal codepath; we special-case
12905     // comparisons to null.
12906     if (!HasSameBase(LHSValue, RHSValue)) {
12907       // Handle &&A - &&B.
12908       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
12909         return Error(E);
12910       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
12911       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
12912       if (!LHSExpr || !RHSExpr)
12913         return Error(E);
12914       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
12915       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
12916       if (!LHSAddrExpr || !RHSAddrExpr)
12917         return Error(E);
12918       // Make sure both labels come from the same function.
12919       if (LHSAddrExpr->getLabel()->getDeclContext() !=
12920           RHSAddrExpr->getLabel()->getDeclContext())
12921         return Error(E);
12922       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
12923     }
12924     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
12925     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
12926 
12927     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
12928     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
12929 
12930     // C++11 [expr.add]p6:
12931     //   Unless both pointers point to elements of the same array object, or
12932     //   one past the last element of the array object, the behavior is
12933     //   undefined.
12934     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
12935         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
12936                                 RHSDesignator))
12937       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
12938 
12939     QualType Type = E->getLHS()->getType();
12940     QualType ElementType = Type->castAs<PointerType>()->getPointeeType();
12941 
12942     CharUnits ElementSize;
12943     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
12944       return false;
12945 
12946     // As an extension, a type may have zero size (empty struct or union in
12947     // C, array of zero length). Pointer subtraction in such cases has
12948     // undefined behavior, so is not constant.
12949     if (ElementSize.isZero()) {
12950       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
12951           << ElementType;
12952       return false;
12953     }
12954 
12955     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
12956     // and produce incorrect results when it overflows. Such behavior
12957     // appears to be non-conforming, but is common, so perhaps we should
12958     // assume the standard intended for such cases to be undefined behavior
12959     // and check for them.
12960 
12961     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
12962     // overflow in the final conversion to ptrdiff_t.
12963     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
12964     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
12965     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
12966                     false);
12967     APSInt TrueResult = (LHS - RHS) / ElemSize;
12968     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
12969 
12970     if (Result.extend(65) != TrueResult &&
12971         !HandleOverflow(Info, E, TrueResult, E->getType()))
12972       return false;
12973     return Success(Result, E);
12974   }
12975 
12976   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
12977 }
12978 
12979 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
12980 /// a result as the expression's type.
12981 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
12982                                     const UnaryExprOrTypeTraitExpr *E) {
12983   switch(E->getKind()) {
12984   case UETT_PreferredAlignOf:
12985   case UETT_AlignOf: {
12986     if (E->isArgumentType())
12987       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
12988                      E);
12989     else
12990       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
12991                      E);
12992   }
12993 
12994   case UETT_VecStep: {
12995     QualType Ty = E->getTypeOfArgument();
12996 
12997     if (Ty->isVectorType()) {
12998       unsigned n = Ty->castAs<VectorType>()->getNumElements();
12999 
13000       // The vec_step built-in functions that take a 3-component
13001       // vector return 4. (OpenCL 1.1 spec 6.11.12)
13002       if (n == 3)
13003         n = 4;
13004 
13005       return Success(n, E);
13006     } else
13007       return Success(1, E);
13008   }
13009 
13010   case UETT_SizeOf: {
13011     QualType SrcTy = E->getTypeOfArgument();
13012     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
13013     //   the result is the size of the referenced type."
13014     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
13015       SrcTy = Ref->getPointeeType();
13016 
13017     CharUnits Sizeof;
13018     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
13019       return false;
13020     return Success(Sizeof, E);
13021   }
13022   case UETT_OpenMPRequiredSimdAlign:
13023     assert(E->isArgumentType());
13024     return Success(
13025         Info.Ctx.toCharUnitsFromBits(
13026                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
13027             .getQuantity(),
13028         E);
13029   }
13030 
13031   llvm_unreachable("unknown expr/type trait");
13032 }
13033 
13034 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
13035   CharUnits Result;
13036   unsigned n = OOE->getNumComponents();
13037   if (n == 0)
13038     return Error(OOE);
13039   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
13040   for (unsigned i = 0; i != n; ++i) {
13041     OffsetOfNode ON = OOE->getComponent(i);
13042     switch (ON.getKind()) {
13043     case OffsetOfNode::Array: {
13044       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
13045       APSInt IdxResult;
13046       if (!EvaluateInteger(Idx, IdxResult, Info))
13047         return false;
13048       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
13049       if (!AT)
13050         return Error(OOE);
13051       CurrentType = AT->getElementType();
13052       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
13053       Result += IdxResult.getSExtValue() * ElementSize;
13054       break;
13055     }
13056 
13057     case OffsetOfNode::Field: {
13058       FieldDecl *MemberDecl = ON.getField();
13059       const RecordType *RT = CurrentType->getAs<RecordType>();
13060       if (!RT)
13061         return Error(OOE);
13062       RecordDecl *RD = RT->getDecl();
13063       if (RD->isInvalidDecl()) return false;
13064       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13065       unsigned i = MemberDecl->getFieldIndex();
13066       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
13067       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
13068       CurrentType = MemberDecl->getType().getNonReferenceType();
13069       break;
13070     }
13071 
13072     case OffsetOfNode::Identifier:
13073       llvm_unreachable("dependent __builtin_offsetof");
13074 
13075     case OffsetOfNode::Base: {
13076       CXXBaseSpecifier *BaseSpec = ON.getBase();
13077       if (BaseSpec->isVirtual())
13078         return Error(OOE);
13079 
13080       // Find the layout of the class whose base we are looking into.
13081       const RecordType *RT = CurrentType->getAs<RecordType>();
13082       if (!RT)
13083         return Error(OOE);
13084       RecordDecl *RD = RT->getDecl();
13085       if (RD->isInvalidDecl()) return false;
13086       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
13087 
13088       // Find the base class itself.
13089       CurrentType = BaseSpec->getType();
13090       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
13091       if (!BaseRT)
13092         return Error(OOE);
13093 
13094       // Add the offset to the base.
13095       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
13096       break;
13097     }
13098     }
13099   }
13100   return Success(Result, OOE);
13101 }
13102 
13103 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13104   switch (E->getOpcode()) {
13105   default:
13106     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
13107     // See C99 6.6p3.
13108     return Error(E);
13109   case UO_Extension:
13110     // FIXME: Should extension allow i-c-e extension expressions in its scope?
13111     // If so, we could clear the diagnostic ID.
13112     return Visit(E->getSubExpr());
13113   case UO_Plus:
13114     // The result is just the value.
13115     return Visit(E->getSubExpr());
13116   case UO_Minus: {
13117     if (!Visit(E->getSubExpr()))
13118       return false;
13119     if (!Result.isInt()) return Error(E);
13120     const APSInt &Value = Result.getInt();
13121     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
13122         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
13123                         E->getType()))
13124       return false;
13125     return Success(-Value, E);
13126   }
13127   case UO_Not: {
13128     if (!Visit(E->getSubExpr()))
13129       return false;
13130     if (!Result.isInt()) return Error(E);
13131     return Success(~Result.getInt(), E);
13132   }
13133   case UO_LNot: {
13134     bool bres;
13135     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13136       return false;
13137     return Success(!bres, E);
13138   }
13139   }
13140 }
13141 
13142 /// HandleCast - This is used to evaluate implicit or explicit casts where the
13143 /// result type is integer.
13144 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
13145   const Expr *SubExpr = E->getSubExpr();
13146   QualType DestType = E->getType();
13147   QualType SrcType = SubExpr->getType();
13148 
13149   switch (E->getCastKind()) {
13150   case CK_BaseToDerived:
13151   case CK_DerivedToBase:
13152   case CK_UncheckedDerivedToBase:
13153   case CK_Dynamic:
13154   case CK_ToUnion:
13155   case CK_ArrayToPointerDecay:
13156   case CK_FunctionToPointerDecay:
13157   case CK_NullToPointer:
13158   case CK_NullToMemberPointer:
13159   case CK_BaseToDerivedMemberPointer:
13160   case CK_DerivedToBaseMemberPointer:
13161   case CK_ReinterpretMemberPointer:
13162   case CK_ConstructorConversion:
13163   case CK_IntegralToPointer:
13164   case CK_ToVoid:
13165   case CK_VectorSplat:
13166   case CK_IntegralToFloating:
13167   case CK_FloatingCast:
13168   case CK_CPointerToObjCPointerCast:
13169   case CK_BlockPointerToObjCPointerCast:
13170   case CK_AnyPointerToBlockPointerCast:
13171   case CK_ObjCObjectLValueCast:
13172   case CK_FloatingRealToComplex:
13173   case CK_FloatingComplexToReal:
13174   case CK_FloatingComplexCast:
13175   case CK_FloatingComplexToIntegralComplex:
13176   case CK_IntegralRealToComplex:
13177   case CK_IntegralComplexCast:
13178   case CK_IntegralComplexToFloatingComplex:
13179   case CK_BuiltinFnToFnPtr:
13180   case CK_ZeroToOCLOpaqueType:
13181   case CK_NonAtomicToAtomic:
13182   case CK_AddressSpaceConversion:
13183   case CK_IntToOCLSampler:
13184   case CK_FloatingToFixedPoint:
13185   case CK_FixedPointToFloating:
13186   case CK_FixedPointCast:
13187   case CK_IntegralToFixedPoint:
13188   case CK_MatrixCast:
13189     llvm_unreachable("invalid cast kind for integral value");
13190 
13191   case CK_BitCast:
13192   case CK_Dependent:
13193   case CK_LValueBitCast:
13194   case CK_ARCProduceObject:
13195   case CK_ARCConsumeObject:
13196   case CK_ARCReclaimReturnedObject:
13197   case CK_ARCExtendBlockObject:
13198   case CK_CopyAndAutoreleaseBlockObject:
13199     return Error(E);
13200 
13201   case CK_UserDefinedConversion:
13202   case CK_LValueToRValue:
13203   case CK_AtomicToNonAtomic:
13204   case CK_NoOp:
13205   case CK_LValueToRValueBitCast:
13206     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13207 
13208   case CK_MemberPointerToBoolean:
13209   case CK_PointerToBoolean:
13210   case CK_IntegralToBoolean:
13211   case CK_FloatingToBoolean:
13212   case CK_BooleanToSignedIntegral:
13213   case CK_FloatingComplexToBoolean:
13214   case CK_IntegralComplexToBoolean: {
13215     bool BoolResult;
13216     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
13217       return false;
13218     uint64_t IntResult = BoolResult;
13219     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
13220       IntResult = (uint64_t)-1;
13221     return Success(IntResult, E);
13222   }
13223 
13224   case CK_FixedPointToIntegral: {
13225     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
13226     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13227       return false;
13228     bool Overflowed;
13229     llvm::APSInt Result = Src.convertToInt(
13230         Info.Ctx.getIntWidth(DestType),
13231         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
13232     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
13233       return false;
13234     return Success(Result, E);
13235   }
13236 
13237   case CK_FixedPointToBoolean: {
13238     // Unsigned padding does not affect this.
13239     APValue Val;
13240     if (!Evaluate(Val, Info, SubExpr))
13241       return false;
13242     return Success(Val.getFixedPoint().getBoolValue(), E);
13243   }
13244 
13245   case CK_IntegralCast: {
13246     if (!Visit(SubExpr))
13247       return false;
13248 
13249     if (!Result.isInt()) {
13250       // Allow casts of address-of-label differences if they are no-ops
13251       // or narrowing.  (The narrowing case isn't actually guaranteed to
13252       // be constant-evaluatable except in some narrow cases which are hard
13253       // to detect here.  We let it through on the assumption the user knows
13254       // what they are doing.)
13255       if (Result.isAddrLabelDiff())
13256         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
13257       // Only allow casts of lvalues if they are lossless.
13258       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
13259     }
13260 
13261     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
13262                                       Result.getInt()), E);
13263   }
13264 
13265   case CK_PointerToIntegral: {
13266     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
13267 
13268     LValue LV;
13269     if (!EvaluatePointer(SubExpr, LV, Info))
13270       return false;
13271 
13272     if (LV.getLValueBase()) {
13273       // Only allow based lvalue casts if they are lossless.
13274       // FIXME: Allow a larger integer size than the pointer size, and allow
13275       // narrowing back down to pointer width in subsequent integral casts.
13276       // FIXME: Check integer type's active bits, not its type size.
13277       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
13278         return Error(E);
13279 
13280       LV.Designator.setInvalid();
13281       LV.moveInto(Result);
13282       return true;
13283     }
13284 
13285     APSInt AsInt;
13286     APValue V;
13287     LV.moveInto(V);
13288     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
13289       llvm_unreachable("Can't cast this!");
13290 
13291     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
13292   }
13293 
13294   case CK_IntegralComplexToReal: {
13295     ComplexValue C;
13296     if (!EvaluateComplex(SubExpr, C, Info))
13297       return false;
13298     return Success(C.getComplexIntReal(), E);
13299   }
13300 
13301   case CK_FloatingToIntegral: {
13302     APFloat F(0.0);
13303     if (!EvaluateFloat(SubExpr, F, Info))
13304       return false;
13305 
13306     APSInt Value;
13307     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
13308       return false;
13309     return Success(Value, E);
13310   }
13311   }
13312 
13313   llvm_unreachable("unknown cast resulting in integral value");
13314 }
13315 
13316 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13317   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13318     ComplexValue LV;
13319     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13320       return false;
13321     if (!LV.isComplexInt())
13322       return Error(E);
13323     return Success(LV.getComplexIntReal(), E);
13324   }
13325 
13326   return Visit(E->getSubExpr());
13327 }
13328 
13329 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13330   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
13331     ComplexValue LV;
13332     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
13333       return false;
13334     if (!LV.isComplexInt())
13335       return Error(E);
13336     return Success(LV.getComplexIntImag(), E);
13337   }
13338 
13339   VisitIgnoredValue(E->getSubExpr());
13340   return Success(0, E);
13341 }
13342 
13343 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
13344   return Success(E->getPackLength(), E);
13345 }
13346 
13347 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
13348   return Success(E->getValue(), E);
13349 }
13350 
13351 bool IntExprEvaluator::VisitConceptSpecializationExpr(
13352        const ConceptSpecializationExpr *E) {
13353   return Success(E->isSatisfied(), E);
13354 }
13355 
13356 bool IntExprEvaluator::VisitRequiresExpr(const RequiresExpr *E) {
13357   return Success(E->isSatisfied(), E);
13358 }
13359 
13360 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13361   switch (E->getOpcode()) {
13362     default:
13363       // Invalid unary operators
13364       return Error(E);
13365     case UO_Plus:
13366       // The result is just the value.
13367       return Visit(E->getSubExpr());
13368     case UO_Minus: {
13369       if (!Visit(E->getSubExpr())) return false;
13370       if (!Result.isFixedPoint())
13371         return Error(E);
13372       bool Overflowed;
13373       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
13374       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
13375         return false;
13376       return Success(Negated, E);
13377     }
13378     case UO_LNot: {
13379       bool bres;
13380       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
13381         return false;
13382       return Success(!bres, E);
13383     }
13384   }
13385 }
13386 
13387 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
13388   const Expr *SubExpr = E->getSubExpr();
13389   QualType DestType = E->getType();
13390   assert(DestType->isFixedPointType() &&
13391          "Expected destination type to be a fixed point type");
13392   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
13393 
13394   switch (E->getCastKind()) {
13395   case CK_FixedPointCast: {
13396     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13397     if (!EvaluateFixedPoint(SubExpr, Src, Info))
13398       return false;
13399     bool Overflowed;
13400     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
13401     if (Overflowed) {
13402       if (Info.checkingForUndefinedBehavior())
13403         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13404                                          diag::warn_fixedpoint_constant_overflow)
13405           << Result.toString() << E->getType();
13406       if (!HandleOverflow(Info, E, Result, E->getType()))
13407         return false;
13408     }
13409     return Success(Result, E);
13410   }
13411   case CK_IntegralToFixedPoint: {
13412     APSInt Src;
13413     if (!EvaluateInteger(SubExpr, Src, Info))
13414       return false;
13415 
13416     bool Overflowed;
13417     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
13418         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13419 
13420     if (Overflowed) {
13421       if (Info.checkingForUndefinedBehavior())
13422         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13423                                          diag::warn_fixedpoint_constant_overflow)
13424           << IntResult.toString() << E->getType();
13425       if (!HandleOverflow(Info, E, IntResult, E->getType()))
13426         return false;
13427     }
13428 
13429     return Success(IntResult, E);
13430   }
13431   case CK_FloatingToFixedPoint: {
13432     APFloat Src(0.0);
13433     if (!EvaluateFloat(SubExpr, Src, Info))
13434       return false;
13435 
13436     bool Overflowed;
13437     APFixedPoint Result = APFixedPoint::getFromFloatValue(
13438         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
13439 
13440     if (Overflowed) {
13441       if (Info.checkingForUndefinedBehavior())
13442         Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13443                                          diag::warn_fixedpoint_constant_overflow)
13444           << Result.toString() << E->getType();
13445       if (!HandleOverflow(Info, E, Result, E->getType()))
13446         return false;
13447     }
13448 
13449     return Success(Result, E);
13450   }
13451   case CK_NoOp:
13452   case CK_LValueToRValue:
13453     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13454   default:
13455     return Error(E);
13456   }
13457 }
13458 
13459 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13460   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13461     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13462 
13463   const Expr *LHS = E->getLHS();
13464   const Expr *RHS = E->getRHS();
13465   FixedPointSemantics ResultFXSema =
13466       Info.Ctx.getFixedPointSemantics(E->getType());
13467 
13468   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
13469   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
13470     return false;
13471   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
13472   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
13473     return false;
13474 
13475   bool OpOverflow = false, ConversionOverflow = false;
13476   APFixedPoint Result(LHSFX.getSemantics());
13477   switch (E->getOpcode()) {
13478   case BO_Add: {
13479     Result = LHSFX.add(RHSFX, &OpOverflow)
13480                   .convert(ResultFXSema, &ConversionOverflow);
13481     break;
13482   }
13483   case BO_Sub: {
13484     Result = LHSFX.sub(RHSFX, &OpOverflow)
13485                   .convert(ResultFXSema, &ConversionOverflow);
13486     break;
13487   }
13488   case BO_Mul: {
13489     Result = LHSFX.mul(RHSFX, &OpOverflow)
13490                   .convert(ResultFXSema, &ConversionOverflow);
13491     break;
13492   }
13493   case BO_Div: {
13494     if (RHSFX.getValue() == 0) {
13495       Info.FFDiag(E, diag::note_expr_divide_by_zero);
13496       return false;
13497     }
13498     Result = LHSFX.div(RHSFX, &OpOverflow)
13499                   .convert(ResultFXSema, &ConversionOverflow);
13500     break;
13501   }
13502   case BO_Shl:
13503   case BO_Shr: {
13504     FixedPointSemantics LHSSema = LHSFX.getSemantics();
13505     llvm::APSInt RHSVal = RHSFX.getValue();
13506 
13507     unsigned ShiftBW =
13508         LHSSema.getWidth() - (unsigned)LHSSema.hasUnsignedPadding();
13509     unsigned Amt = RHSVal.getLimitedValue(ShiftBW - 1);
13510     // Embedded-C 4.1.6.2.2:
13511     //   The right operand must be nonnegative and less than the total number
13512     //   of (nonpadding) bits of the fixed-point operand ...
13513     if (RHSVal.isNegative())
13514       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHSVal;
13515     else if (Amt != RHSVal)
13516       Info.CCEDiag(E, diag::note_constexpr_large_shift)
13517           << RHSVal << E->getType() << ShiftBW;
13518 
13519     if (E->getOpcode() == BO_Shl)
13520       Result = LHSFX.shl(Amt, &OpOverflow);
13521     else
13522       Result = LHSFX.shr(Amt, &OpOverflow);
13523     break;
13524   }
13525   default:
13526     return false;
13527   }
13528   if (OpOverflow || ConversionOverflow) {
13529     if (Info.checkingForUndefinedBehavior())
13530       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
13531                                        diag::warn_fixedpoint_constant_overflow)
13532         << Result.toString() << E->getType();
13533     if (!HandleOverflow(Info, E, Result, E->getType()))
13534       return false;
13535   }
13536   return Success(Result, E);
13537 }
13538 
13539 //===----------------------------------------------------------------------===//
13540 // Float Evaluation
13541 //===----------------------------------------------------------------------===//
13542 
13543 namespace {
13544 class FloatExprEvaluator
13545   : public ExprEvaluatorBase<FloatExprEvaluator> {
13546   APFloat &Result;
13547 public:
13548   FloatExprEvaluator(EvalInfo &info, APFloat &result)
13549     : ExprEvaluatorBaseTy(info), Result(result) {}
13550 
13551   bool Success(const APValue &V, const Expr *e) {
13552     Result = V.getFloat();
13553     return true;
13554   }
13555 
13556   bool ZeroInitialization(const Expr *E) {
13557     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
13558     return true;
13559   }
13560 
13561   bool VisitCallExpr(const CallExpr *E);
13562 
13563   bool VisitUnaryOperator(const UnaryOperator *E);
13564   bool VisitBinaryOperator(const BinaryOperator *E);
13565   bool VisitFloatingLiteral(const FloatingLiteral *E);
13566   bool VisitCastExpr(const CastExpr *E);
13567 
13568   bool VisitUnaryReal(const UnaryOperator *E);
13569   bool VisitUnaryImag(const UnaryOperator *E);
13570 
13571   // FIXME: Missing: array subscript of vector, member of vector
13572 };
13573 } // end anonymous namespace
13574 
13575 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
13576   assert(!E->isValueDependent());
13577   assert(E->isPRValue() && E->getType()->isRealFloatingType());
13578   return FloatExprEvaluator(Info, Result).Visit(E);
13579 }
13580 
13581 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
13582                                   QualType ResultTy,
13583                                   const Expr *Arg,
13584                                   bool SNaN,
13585                                   llvm::APFloat &Result) {
13586   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
13587   if (!S) return false;
13588 
13589   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
13590 
13591   llvm::APInt fill;
13592 
13593   // Treat empty strings as if they were zero.
13594   if (S->getString().empty())
13595     fill = llvm::APInt(32, 0);
13596   else if (S->getString().getAsInteger(0, fill))
13597     return false;
13598 
13599   if (Context.getTargetInfo().isNan2008()) {
13600     if (SNaN)
13601       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13602     else
13603       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13604   } else {
13605     // Prior to IEEE 754-2008, architectures were allowed to choose whether
13606     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
13607     // a different encoding to what became a standard in 2008, and for pre-
13608     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
13609     // sNaN. This is now known as "legacy NaN" encoding.
13610     if (SNaN)
13611       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
13612     else
13613       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
13614   }
13615 
13616   return true;
13617 }
13618 
13619 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
13620   switch (E->getBuiltinCallee()) {
13621   default:
13622     return ExprEvaluatorBaseTy::VisitCallExpr(E);
13623 
13624   case Builtin::BI__builtin_huge_val:
13625   case Builtin::BI__builtin_huge_valf:
13626   case Builtin::BI__builtin_huge_vall:
13627   case Builtin::BI__builtin_huge_valf128:
13628   case Builtin::BI__builtin_inf:
13629   case Builtin::BI__builtin_inff:
13630   case Builtin::BI__builtin_infl:
13631   case Builtin::BI__builtin_inff128: {
13632     const llvm::fltSemantics &Sem =
13633       Info.Ctx.getFloatTypeSemantics(E->getType());
13634     Result = llvm::APFloat::getInf(Sem);
13635     return true;
13636   }
13637 
13638   case Builtin::BI__builtin_nans:
13639   case Builtin::BI__builtin_nansf:
13640   case Builtin::BI__builtin_nansl:
13641   case Builtin::BI__builtin_nansf128:
13642     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13643                                true, Result))
13644       return Error(E);
13645     return true;
13646 
13647   case Builtin::BI__builtin_nan:
13648   case Builtin::BI__builtin_nanf:
13649   case Builtin::BI__builtin_nanl:
13650   case Builtin::BI__builtin_nanf128:
13651     // If this is __builtin_nan() turn this into a nan, otherwise we
13652     // can't constant fold it.
13653     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
13654                                false, Result))
13655       return Error(E);
13656     return true;
13657 
13658   case Builtin::BI__builtin_fabs:
13659   case Builtin::BI__builtin_fabsf:
13660   case Builtin::BI__builtin_fabsl:
13661   case Builtin::BI__builtin_fabsf128:
13662     // The C standard says "fabs raises no floating-point exceptions,
13663     // even if x is a signaling NaN. The returned value is independent of
13664     // the current rounding direction mode."  Therefore constant folding can
13665     // proceed without regard to the floating point settings.
13666     // Reference, WG14 N2478 F.10.4.3
13667     if (!EvaluateFloat(E->getArg(0), Result, Info))
13668       return false;
13669 
13670     if (Result.isNegative())
13671       Result.changeSign();
13672     return true;
13673 
13674   case Builtin::BI__arithmetic_fence:
13675     return EvaluateFloat(E->getArg(0), Result, Info);
13676 
13677   // FIXME: Builtin::BI__builtin_powi
13678   // FIXME: Builtin::BI__builtin_powif
13679   // FIXME: Builtin::BI__builtin_powil
13680 
13681   case Builtin::BI__builtin_copysign:
13682   case Builtin::BI__builtin_copysignf:
13683   case Builtin::BI__builtin_copysignl:
13684   case Builtin::BI__builtin_copysignf128: {
13685     APFloat RHS(0.);
13686     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
13687         !EvaluateFloat(E->getArg(1), RHS, Info))
13688       return false;
13689     Result.copySign(RHS);
13690     return true;
13691   }
13692   }
13693 }
13694 
13695 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
13696   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13697     ComplexValue CV;
13698     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13699       return false;
13700     Result = CV.FloatReal;
13701     return true;
13702   }
13703 
13704   return Visit(E->getSubExpr());
13705 }
13706 
13707 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
13708   if (E->getSubExpr()->getType()->isAnyComplexType()) {
13709     ComplexValue CV;
13710     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
13711       return false;
13712     Result = CV.FloatImag;
13713     return true;
13714   }
13715 
13716   VisitIgnoredValue(E->getSubExpr());
13717   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
13718   Result = llvm::APFloat::getZero(Sem);
13719   return true;
13720 }
13721 
13722 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
13723   switch (E->getOpcode()) {
13724   default: return Error(E);
13725   case UO_Plus:
13726     return EvaluateFloat(E->getSubExpr(), Result, Info);
13727   case UO_Minus:
13728     // In C standard, WG14 N2478 F.3 p4
13729     // "the unary - raises no floating point exceptions,
13730     // even if the operand is signalling."
13731     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
13732       return false;
13733     Result.changeSign();
13734     return true;
13735   }
13736 }
13737 
13738 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
13739   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
13740     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
13741 
13742   APFloat RHS(0.0);
13743   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
13744   if (!LHSOK && !Info.noteFailure())
13745     return false;
13746   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
13747          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
13748 }
13749 
13750 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
13751   Result = E->getValue();
13752   return true;
13753 }
13754 
13755 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
13756   const Expr* SubExpr = E->getSubExpr();
13757 
13758   switch (E->getCastKind()) {
13759   default:
13760     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13761 
13762   case CK_IntegralToFloating: {
13763     APSInt IntResult;
13764     const FPOptions FPO = E->getFPFeaturesInEffect(
13765                                   Info.Ctx.getLangOpts());
13766     return EvaluateInteger(SubExpr, IntResult, Info) &&
13767            HandleIntToFloatCast(Info, E, FPO, SubExpr->getType(),
13768                                 IntResult, E->getType(), Result);
13769   }
13770 
13771   case CK_FixedPointToFloating: {
13772     APFixedPoint FixResult(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
13773     if (!EvaluateFixedPoint(SubExpr, FixResult, Info))
13774       return false;
13775     Result =
13776         FixResult.convertToFloat(Info.Ctx.getFloatTypeSemantics(E->getType()));
13777     return true;
13778   }
13779 
13780   case CK_FloatingCast: {
13781     if (!Visit(SubExpr))
13782       return false;
13783     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
13784                                   Result);
13785   }
13786 
13787   case CK_FloatingComplexToReal: {
13788     ComplexValue V;
13789     if (!EvaluateComplex(SubExpr, V, Info))
13790       return false;
13791     Result = V.getComplexFloatReal();
13792     return true;
13793   }
13794   }
13795 }
13796 
13797 //===----------------------------------------------------------------------===//
13798 // Complex Evaluation (for float and integer)
13799 //===----------------------------------------------------------------------===//
13800 
13801 namespace {
13802 class ComplexExprEvaluator
13803   : public ExprEvaluatorBase<ComplexExprEvaluator> {
13804   ComplexValue &Result;
13805 
13806 public:
13807   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
13808     : ExprEvaluatorBaseTy(info), Result(Result) {}
13809 
13810   bool Success(const APValue &V, const Expr *e) {
13811     Result.setFrom(V);
13812     return true;
13813   }
13814 
13815   bool ZeroInitialization(const Expr *E);
13816 
13817   //===--------------------------------------------------------------------===//
13818   //                            Visitor Methods
13819   //===--------------------------------------------------------------------===//
13820 
13821   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
13822   bool VisitCastExpr(const CastExpr *E);
13823   bool VisitBinaryOperator(const BinaryOperator *E);
13824   bool VisitUnaryOperator(const UnaryOperator *E);
13825   bool VisitInitListExpr(const InitListExpr *E);
13826   bool VisitCallExpr(const CallExpr *E);
13827 };
13828 } // end anonymous namespace
13829 
13830 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
13831                             EvalInfo &Info) {
13832   assert(!E->isValueDependent());
13833   assert(E->isPRValue() && E->getType()->isAnyComplexType());
13834   return ComplexExprEvaluator(Info, Result).Visit(E);
13835 }
13836 
13837 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
13838   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
13839   if (ElemTy->isRealFloatingType()) {
13840     Result.makeComplexFloat();
13841     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
13842     Result.FloatReal = Zero;
13843     Result.FloatImag = Zero;
13844   } else {
13845     Result.makeComplexInt();
13846     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
13847     Result.IntReal = Zero;
13848     Result.IntImag = Zero;
13849   }
13850   return true;
13851 }
13852 
13853 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
13854   const Expr* SubExpr = E->getSubExpr();
13855 
13856   if (SubExpr->getType()->isRealFloatingType()) {
13857     Result.makeComplexFloat();
13858     APFloat &Imag = Result.FloatImag;
13859     if (!EvaluateFloat(SubExpr, Imag, Info))
13860       return false;
13861 
13862     Result.FloatReal = APFloat(Imag.getSemantics());
13863     return true;
13864   } else {
13865     assert(SubExpr->getType()->isIntegerType() &&
13866            "Unexpected imaginary literal.");
13867 
13868     Result.makeComplexInt();
13869     APSInt &Imag = Result.IntImag;
13870     if (!EvaluateInteger(SubExpr, Imag, Info))
13871       return false;
13872 
13873     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
13874     return true;
13875   }
13876 }
13877 
13878 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
13879 
13880   switch (E->getCastKind()) {
13881   case CK_BitCast:
13882   case CK_BaseToDerived:
13883   case CK_DerivedToBase:
13884   case CK_UncheckedDerivedToBase:
13885   case CK_Dynamic:
13886   case CK_ToUnion:
13887   case CK_ArrayToPointerDecay:
13888   case CK_FunctionToPointerDecay:
13889   case CK_NullToPointer:
13890   case CK_NullToMemberPointer:
13891   case CK_BaseToDerivedMemberPointer:
13892   case CK_DerivedToBaseMemberPointer:
13893   case CK_MemberPointerToBoolean:
13894   case CK_ReinterpretMemberPointer:
13895   case CK_ConstructorConversion:
13896   case CK_IntegralToPointer:
13897   case CK_PointerToIntegral:
13898   case CK_PointerToBoolean:
13899   case CK_ToVoid:
13900   case CK_VectorSplat:
13901   case CK_IntegralCast:
13902   case CK_BooleanToSignedIntegral:
13903   case CK_IntegralToBoolean:
13904   case CK_IntegralToFloating:
13905   case CK_FloatingToIntegral:
13906   case CK_FloatingToBoolean:
13907   case CK_FloatingCast:
13908   case CK_CPointerToObjCPointerCast:
13909   case CK_BlockPointerToObjCPointerCast:
13910   case CK_AnyPointerToBlockPointerCast:
13911   case CK_ObjCObjectLValueCast:
13912   case CK_FloatingComplexToReal:
13913   case CK_FloatingComplexToBoolean:
13914   case CK_IntegralComplexToReal:
13915   case CK_IntegralComplexToBoolean:
13916   case CK_ARCProduceObject:
13917   case CK_ARCConsumeObject:
13918   case CK_ARCReclaimReturnedObject:
13919   case CK_ARCExtendBlockObject:
13920   case CK_CopyAndAutoreleaseBlockObject:
13921   case CK_BuiltinFnToFnPtr:
13922   case CK_ZeroToOCLOpaqueType:
13923   case CK_NonAtomicToAtomic:
13924   case CK_AddressSpaceConversion:
13925   case CK_IntToOCLSampler:
13926   case CK_FloatingToFixedPoint:
13927   case CK_FixedPointToFloating:
13928   case CK_FixedPointCast:
13929   case CK_FixedPointToBoolean:
13930   case CK_FixedPointToIntegral:
13931   case CK_IntegralToFixedPoint:
13932   case CK_MatrixCast:
13933     llvm_unreachable("invalid cast kind for complex value");
13934 
13935   case CK_LValueToRValue:
13936   case CK_AtomicToNonAtomic:
13937   case CK_NoOp:
13938   case CK_LValueToRValueBitCast:
13939     return ExprEvaluatorBaseTy::VisitCastExpr(E);
13940 
13941   case CK_Dependent:
13942   case CK_LValueBitCast:
13943   case CK_UserDefinedConversion:
13944     return Error(E);
13945 
13946   case CK_FloatingRealToComplex: {
13947     APFloat &Real = Result.FloatReal;
13948     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
13949       return false;
13950 
13951     Result.makeComplexFloat();
13952     Result.FloatImag = APFloat(Real.getSemantics());
13953     return true;
13954   }
13955 
13956   case CK_FloatingComplexCast: {
13957     if (!Visit(E->getSubExpr()))
13958       return false;
13959 
13960     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13961     QualType From
13962       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13963 
13964     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
13965            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
13966   }
13967 
13968   case CK_FloatingComplexToIntegralComplex: {
13969     if (!Visit(E->getSubExpr()))
13970       return false;
13971 
13972     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13973     QualType From
13974       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13975     Result.makeComplexInt();
13976     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
13977                                 To, Result.IntReal) &&
13978            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
13979                                 To, Result.IntImag);
13980   }
13981 
13982   case CK_IntegralRealToComplex: {
13983     APSInt &Real = Result.IntReal;
13984     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
13985       return false;
13986 
13987     Result.makeComplexInt();
13988     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
13989     return true;
13990   }
13991 
13992   case CK_IntegralComplexCast: {
13993     if (!Visit(E->getSubExpr()))
13994       return false;
13995 
13996     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
13997     QualType From
13998       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
13999 
14000     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
14001     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
14002     return true;
14003   }
14004 
14005   case CK_IntegralComplexToFloatingComplex: {
14006     if (!Visit(E->getSubExpr()))
14007       return false;
14008 
14009     const FPOptions FPO = E->getFPFeaturesInEffect(
14010                                   Info.Ctx.getLangOpts());
14011     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
14012     QualType From
14013       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
14014     Result.makeComplexFloat();
14015     return HandleIntToFloatCast(Info, E, FPO, From, Result.IntReal,
14016                                 To, Result.FloatReal) &&
14017            HandleIntToFloatCast(Info, E, FPO, From, Result.IntImag,
14018                                 To, Result.FloatImag);
14019   }
14020   }
14021 
14022   llvm_unreachable("unknown cast resulting in complex value");
14023 }
14024 
14025 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
14026   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
14027     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
14028 
14029   // Track whether the LHS or RHS is real at the type system level. When this is
14030   // the case we can simplify our evaluation strategy.
14031   bool LHSReal = false, RHSReal = false;
14032 
14033   bool LHSOK;
14034   if (E->getLHS()->getType()->isRealFloatingType()) {
14035     LHSReal = true;
14036     APFloat &Real = Result.FloatReal;
14037     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
14038     if (LHSOK) {
14039       Result.makeComplexFloat();
14040       Result.FloatImag = APFloat(Real.getSemantics());
14041     }
14042   } else {
14043     LHSOK = Visit(E->getLHS());
14044   }
14045   if (!LHSOK && !Info.noteFailure())
14046     return false;
14047 
14048   ComplexValue RHS;
14049   if (E->getRHS()->getType()->isRealFloatingType()) {
14050     RHSReal = true;
14051     APFloat &Real = RHS.FloatReal;
14052     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
14053       return false;
14054     RHS.makeComplexFloat();
14055     RHS.FloatImag = APFloat(Real.getSemantics());
14056   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
14057     return false;
14058 
14059   assert(!(LHSReal && RHSReal) &&
14060          "Cannot have both operands of a complex operation be real.");
14061   switch (E->getOpcode()) {
14062   default: return Error(E);
14063   case BO_Add:
14064     if (Result.isComplexFloat()) {
14065       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
14066                                        APFloat::rmNearestTiesToEven);
14067       if (LHSReal)
14068         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14069       else if (!RHSReal)
14070         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
14071                                          APFloat::rmNearestTiesToEven);
14072     } else {
14073       Result.getComplexIntReal() += RHS.getComplexIntReal();
14074       Result.getComplexIntImag() += RHS.getComplexIntImag();
14075     }
14076     break;
14077   case BO_Sub:
14078     if (Result.isComplexFloat()) {
14079       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
14080                                             APFloat::rmNearestTiesToEven);
14081       if (LHSReal) {
14082         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
14083         Result.getComplexFloatImag().changeSign();
14084       } else if (!RHSReal) {
14085         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
14086                                               APFloat::rmNearestTiesToEven);
14087       }
14088     } else {
14089       Result.getComplexIntReal() -= RHS.getComplexIntReal();
14090       Result.getComplexIntImag() -= RHS.getComplexIntImag();
14091     }
14092     break;
14093   case BO_Mul:
14094     if (Result.isComplexFloat()) {
14095       // This is an implementation of complex multiplication according to the
14096       // constraints laid out in C11 Annex G. The implementation uses the
14097       // following naming scheme:
14098       //   (a + ib) * (c + id)
14099       ComplexValue LHS = Result;
14100       APFloat &A = LHS.getComplexFloatReal();
14101       APFloat &B = LHS.getComplexFloatImag();
14102       APFloat &C = RHS.getComplexFloatReal();
14103       APFloat &D = RHS.getComplexFloatImag();
14104       APFloat &ResR = Result.getComplexFloatReal();
14105       APFloat &ResI = Result.getComplexFloatImag();
14106       if (LHSReal) {
14107         assert(!RHSReal && "Cannot have two real operands for a complex op!");
14108         ResR = A * C;
14109         ResI = A * D;
14110       } else if (RHSReal) {
14111         ResR = C * A;
14112         ResI = C * B;
14113       } else {
14114         // In the fully general case, we need to handle NaNs and infinities
14115         // robustly.
14116         APFloat AC = A * C;
14117         APFloat BD = B * D;
14118         APFloat AD = A * D;
14119         APFloat BC = B * C;
14120         ResR = AC - BD;
14121         ResI = AD + BC;
14122         if (ResR.isNaN() && ResI.isNaN()) {
14123           bool Recalc = false;
14124           if (A.isInfinity() || B.isInfinity()) {
14125             A = APFloat::copySign(
14126                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14127             B = APFloat::copySign(
14128                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14129             if (C.isNaN())
14130               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14131             if (D.isNaN())
14132               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14133             Recalc = true;
14134           }
14135           if (C.isInfinity() || D.isInfinity()) {
14136             C = APFloat::copySign(
14137                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14138             D = APFloat::copySign(
14139                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14140             if (A.isNaN())
14141               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14142             if (B.isNaN())
14143               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14144             Recalc = true;
14145           }
14146           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
14147                           AD.isInfinity() || BC.isInfinity())) {
14148             if (A.isNaN())
14149               A = APFloat::copySign(APFloat(A.getSemantics()), A);
14150             if (B.isNaN())
14151               B = APFloat::copySign(APFloat(B.getSemantics()), B);
14152             if (C.isNaN())
14153               C = APFloat::copySign(APFloat(C.getSemantics()), C);
14154             if (D.isNaN())
14155               D = APFloat::copySign(APFloat(D.getSemantics()), D);
14156             Recalc = true;
14157           }
14158           if (Recalc) {
14159             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
14160             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
14161           }
14162         }
14163       }
14164     } else {
14165       ComplexValue LHS = Result;
14166       Result.getComplexIntReal() =
14167         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
14168          LHS.getComplexIntImag() * RHS.getComplexIntImag());
14169       Result.getComplexIntImag() =
14170         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
14171          LHS.getComplexIntImag() * RHS.getComplexIntReal());
14172     }
14173     break;
14174   case BO_Div:
14175     if (Result.isComplexFloat()) {
14176       // This is an implementation of complex division according to the
14177       // constraints laid out in C11 Annex G. The implementation uses the
14178       // following naming scheme:
14179       //   (a + ib) / (c + id)
14180       ComplexValue LHS = Result;
14181       APFloat &A = LHS.getComplexFloatReal();
14182       APFloat &B = LHS.getComplexFloatImag();
14183       APFloat &C = RHS.getComplexFloatReal();
14184       APFloat &D = RHS.getComplexFloatImag();
14185       APFloat &ResR = Result.getComplexFloatReal();
14186       APFloat &ResI = Result.getComplexFloatImag();
14187       if (RHSReal) {
14188         ResR = A / C;
14189         ResI = B / C;
14190       } else {
14191         if (LHSReal) {
14192           // No real optimizations we can do here, stub out with zero.
14193           B = APFloat::getZero(A.getSemantics());
14194         }
14195         int DenomLogB = 0;
14196         APFloat MaxCD = maxnum(abs(C), abs(D));
14197         if (MaxCD.isFinite()) {
14198           DenomLogB = ilogb(MaxCD);
14199           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
14200           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
14201         }
14202         APFloat Denom = C * C + D * D;
14203         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
14204                       APFloat::rmNearestTiesToEven);
14205         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
14206                       APFloat::rmNearestTiesToEven);
14207         if (ResR.isNaN() && ResI.isNaN()) {
14208           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
14209             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
14210             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
14211           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
14212                      D.isFinite()) {
14213             A = APFloat::copySign(
14214                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
14215             B = APFloat::copySign(
14216                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
14217             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
14218             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
14219           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
14220             C = APFloat::copySign(
14221                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
14222             D = APFloat::copySign(
14223                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
14224             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
14225             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
14226           }
14227         }
14228       }
14229     } else {
14230       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
14231         return Error(E, diag::note_expr_divide_by_zero);
14232 
14233       ComplexValue LHS = Result;
14234       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
14235         RHS.getComplexIntImag() * RHS.getComplexIntImag();
14236       Result.getComplexIntReal() =
14237         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
14238          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
14239       Result.getComplexIntImag() =
14240         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
14241          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
14242     }
14243     break;
14244   }
14245 
14246   return true;
14247 }
14248 
14249 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
14250   // Get the operand value into 'Result'.
14251   if (!Visit(E->getSubExpr()))
14252     return false;
14253 
14254   switch (E->getOpcode()) {
14255   default:
14256     return Error(E);
14257   case UO_Extension:
14258     return true;
14259   case UO_Plus:
14260     // The result is always just the subexpr.
14261     return true;
14262   case UO_Minus:
14263     if (Result.isComplexFloat()) {
14264       Result.getComplexFloatReal().changeSign();
14265       Result.getComplexFloatImag().changeSign();
14266     }
14267     else {
14268       Result.getComplexIntReal() = -Result.getComplexIntReal();
14269       Result.getComplexIntImag() = -Result.getComplexIntImag();
14270     }
14271     return true;
14272   case UO_Not:
14273     if (Result.isComplexFloat())
14274       Result.getComplexFloatImag().changeSign();
14275     else
14276       Result.getComplexIntImag() = -Result.getComplexIntImag();
14277     return true;
14278   }
14279 }
14280 
14281 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
14282   if (E->getNumInits() == 2) {
14283     if (E->getType()->isComplexType()) {
14284       Result.makeComplexFloat();
14285       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
14286         return false;
14287       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
14288         return false;
14289     } else {
14290       Result.makeComplexInt();
14291       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
14292         return false;
14293       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
14294         return false;
14295     }
14296     return true;
14297   }
14298   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
14299 }
14300 
14301 bool ComplexExprEvaluator::VisitCallExpr(const CallExpr *E) {
14302   switch (E->getBuiltinCallee()) {
14303   case Builtin::BI__builtin_complex:
14304     Result.makeComplexFloat();
14305     if (!EvaluateFloat(E->getArg(0), Result.FloatReal, Info))
14306       return false;
14307     if (!EvaluateFloat(E->getArg(1), Result.FloatImag, Info))
14308       return false;
14309     return true;
14310 
14311   default:
14312     break;
14313   }
14314 
14315   return ExprEvaluatorBaseTy::VisitCallExpr(E);
14316 }
14317 
14318 //===----------------------------------------------------------------------===//
14319 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
14320 // implicit conversion.
14321 //===----------------------------------------------------------------------===//
14322 
14323 namespace {
14324 class AtomicExprEvaluator :
14325     public ExprEvaluatorBase<AtomicExprEvaluator> {
14326   const LValue *This;
14327   APValue &Result;
14328 public:
14329   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
14330       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
14331 
14332   bool Success(const APValue &V, const Expr *E) {
14333     Result = V;
14334     return true;
14335   }
14336 
14337   bool ZeroInitialization(const Expr *E) {
14338     ImplicitValueInitExpr VIE(
14339         E->getType()->castAs<AtomicType>()->getValueType());
14340     // For atomic-qualified class (and array) types in C++, initialize the
14341     // _Atomic-wrapped subobject directly, in-place.
14342     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
14343                 : Evaluate(Result, Info, &VIE);
14344   }
14345 
14346   bool VisitCastExpr(const CastExpr *E) {
14347     switch (E->getCastKind()) {
14348     default:
14349       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14350     case CK_NonAtomicToAtomic:
14351       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
14352                   : Evaluate(Result, Info, E->getSubExpr());
14353     }
14354   }
14355 };
14356 } // end anonymous namespace
14357 
14358 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
14359                            EvalInfo &Info) {
14360   assert(!E->isValueDependent());
14361   assert(E->isPRValue() && E->getType()->isAtomicType());
14362   return AtomicExprEvaluator(Info, This, Result).Visit(E);
14363 }
14364 
14365 //===----------------------------------------------------------------------===//
14366 // Void expression evaluation, primarily for a cast to void on the LHS of a
14367 // comma operator
14368 //===----------------------------------------------------------------------===//
14369 
14370 namespace {
14371 class VoidExprEvaluator
14372   : public ExprEvaluatorBase<VoidExprEvaluator> {
14373 public:
14374   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
14375 
14376   bool Success(const APValue &V, const Expr *e) { return true; }
14377 
14378   bool ZeroInitialization(const Expr *E) { return true; }
14379 
14380   bool VisitCastExpr(const CastExpr *E) {
14381     switch (E->getCastKind()) {
14382     default:
14383       return ExprEvaluatorBaseTy::VisitCastExpr(E);
14384     case CK_ToVoid:
14385       VisitIgnoredValue(E->getSubExpr());
14386       return true;
14387     }
14388   }
14389 
14390   bool VisitCallExpr(const CallExpr *E) {
14391     switch (E->getBuiltinCallee()) {
14392     case Builtin::BI__assume:
14393     case Builtin::BI__builtin_assume:
14394       // The argument is not evaluated!
14395       return true;
14396 
14397     case Builtin::BI__builtin_operator_delete:
14398       return HandleOperatorDeleteCall(Info, E);
14399 
14400     default:
14401       break;
14402     }
14403 
14404     return ExprEvaluatorBaseTy::VisitCallExpr(E);
14405   }
14406 
14407   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
14408 };
14409 } // end anonymous namespace
14410 
14411 bool VoidExprEvaluator::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
14412   // We cannot speculatively evaluate a delete expression.
14413   if (Info.SpeculativeEvaluationDepth)
14414     return false;
14415 
14416   FunctionDecl *OperatorDelete = E->getOperatorDelete();
14417   if (!OperatorDelete->isReplaceableGlobalAllocationFunction()) {
14418     Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14419         << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
14420     return false;
14421   }
14422 
14423   const Expr *Arg = E->getArgument();
14424 
14425   LValue Pointer;
14426   if (!EvaluatePointer(Arg, Pointer, Info))
14427     return false;
14428   if (Pointer.Designator.Invalid)
14429     return false;
14430 
14431   // Deleting a null pointer has no effect.
14432   if (Pointer.isNullPointer()) {
14433     // This is the only case where we need to produce an extension warning:
14434     // the only other way we can succeed is if we find a dynamic allocation,
14435     // and we will have warned when we allocated it in that case.
14436     if (!Info.getLangOpts().CPlusPlus20)
14437       Info.CCEDiag(E, diag::note_constexpr_new);
14438     return true;
14439   }
14440 
14441   Optional<DynAlloc *> Alloc = CheckDeleteKind(
14442       Info, E, Pointer, E->isArrayForm() ? DynAlloc::ArrayNew : DynAlloc::New);
14443   if (!Alloc)
14444     return false;
14445   QualType AllocType = Pointer.Base.getDynamicAllocType();
14446 
14447   // For the non-array case, the designator must be empty if the static type
14448   // does not have a virtual destructor.
14449   if (!E->isArrayForm() && Pointer.Designator.Entries.size() != 0 &&
14450       !hasVirtualDestructor(Arg->getType()->getPointeeType())) {
14451     Info.FFDiag(E, diag::note_constexpr_delete_base_nonvirt_dtor)
14452         << Arg->getType()->getPointeeType() << AllocType;
14453     return false;
14454   }
14455 
14456   // For a class type with a virtual destructor, the selected operator delete
14457   // is the one looked up when building the destructor.
14458   if (!E->isArrayForm() && !E->isGlobalDelete()) {
14459     const FunctionDecl *VirtualDelete = getVirtualOperatorDelete(AllocType);
14460     if (VirtualDelete &&
14461         !VirtualDelete->isReplaceableGlobalAllocationFunction()) {
14462       Info.FFDiag(E, diag::note_constexpr_new_non_replaceable)
14463           << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
14464       return false;
14465     }
14466   }
14467 
14468   if (!HandleDestruction(Info, E->getExprLoc(), Pointer.getLValueBase(),
14469                          (*Alloc)->Value, AllocType))
14470     return false;
14471 
14472   if (!Info.HeapAllocs.erase(Pointer.Base.dyn_cast<DynamicAllocLValue>())) {
14473     // The element was already erased. This means the destructor call also
14474     // deleted the object.
14475     // FIXME: This probably results in undefined behavior before we get this
14476     // far, and should be diagnosed elsewhere first.
14477     Info.FFDiag(E, diag::note_constexpr_double_delete);
14478     return false;
14479   }
14480 
14481   return true;
14482 }
14483 
14484 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
14485   assert(!E->isValueDependent());
14486   assert(E->isPRValue() && E->getType()->isVoidType());
14487   return VoidExprEvaluator(Info).Visit(E);
14488 }
14489 
14490 //===----------------------------------------------------------------------===//
14491 // Top level Expr::EvaluateAsRValue method.
14492 //===----------------------------------------------------------------------===//
14493 
14494 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
14495   assert(!E->isValueDependent());
14496   // In C, function designators are not lvalues, but we evaluate them as if they
14497   // are.
14498   QualType T = E->getType();
14499   if (E->isGLValue() || T->isFunctionType()) {
14500     LValue LV;
14501     if (!EvaluateLValue(E, LV, Info))
14502       return false;
14503     LV.moveInto(Result);
14504   } else if (T->isVectorType()) {
14505     if (!EvaluateVector(E, Result, Info))
14506       return false;
14507   } else if (T->isIntegralOrEnumerationType()) {
14508     if (!IntExprEvaluator(Info, Result).Visit(E))
14509       return false;
14510   } else if (T->hasPointerRepresentation()) {
14511     LValue LV;
14512     if (!EvaluatePointer(E, LV, Info))
14513       return false;
14514     LV.moveInto(Result);
14515   } else if (T->isRealFloatingType()) {
14516     llvm::APFloat F(0.0);
14517     if (!EvaluateFloat(E, F, Info))
14518       return false;
14519     Result = APValue(F);
14520   } else if (T->isAnyComplexType()) {
14521     ComplexValue C;
14522     if (!EvaluateComplex(E, C, Info))
14523       return false;
14524     C.moveInto(Result);
14525   } else if (T->isFixedPointType()) {
14526     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
14527   } else if (T->isMemberPointerType()) {
14528     MemberPtr P;
14529     if (!EvaluateMemberPointer(E, P, Info))
14530       return false;
14531     P.moveInto(Result);
14532     return true;
14533   } else if (T->isArrayType()) {
14534     LValue LV;
14535     APValue &Value =
14536         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14537     if (!EvaluateArray(E, LV, Value, Info))
14538       return false;
14539     Result = Value;
14540   } else if (T->isRecordType()) {
14541     LValue LV;
14542     APValue &Value =
14543         Info.CurrentCall->createTemporary(E, T, ScopeKind::FullExpression, LV);
14544     if (!EvaluateRecord(E, LV, Value, Info))
14545       return false;
14546     Result = Value;
14547   } else if (T->isVoidType()) {
14548     if (!Info.getLangOpts().CPlusPlus11)
14549       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
14550         << E->getType();
14551     if (!EvaluateVoid(E, Info))
14552       return false;
14553   } else if (T->isAtomicType()) {
14554     QualType Unqual = T.getAtomicUnqualifiedType();
14555     if (Unqual->isArrayType() || Unqual->isRecordType()) {
14556       LValue LV;
14557       APValue &Value = Info.CurrentCall->createTemporary(
14558           E, Unqual, ScopeKind::FullExpression, LV);
14559       if (!EvaluateAtomic(E, &LV, Value, Info))
14560         return false;
14561     } else {
14562       if (!EvaluateAtomic(E, nullptr, Result, Info))
14563         return false;
14564     }
14565   } else if (Info.getLangOpts().CPlusPlus11) {
14566     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
14567     return false;
14568   } else {
14569     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
14570     return false;
14571   }
14572 
14573   return true;
14574 }
14575 
14576 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
14577 /// cases, the in-place evaluation is essential, since later initializers for
14578 /// an object can indirectly refer to subobjects which were initialized earlier.
14579 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
14580                             const Expr *E, bool AllowNonLiteralTypes) {
14581   assert(!E->isValueDependent());
14582 
14583   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
14584     return false;
14585 
14586   if (E->isPRValue()) {
14587     // Evaluate arrays and record types in-place, so that later initializers can
14588     // refer to earlier-initialized members of the object.
14589     QualType T = E->getType();
14590     if (T->isArrayType())
14591       return EvaluateArray(E, This, Result, Info);
14592     else if (T->isRecordType())
14593       return EvaluateRecord(E, This, Result, Info);
14594     else if (T->isAtomicType()) {
14595       QualType Unqual = T.getAtomicUnqualifiedType();
14596       if (Unqual->isArrayType() || Unqual->isRecordType())
14597         return EvaluateAtomic(E, &This, Result, Info);
14598     }
14599   }
14600 
14601   // For any other type, in-place evaluation is unimportant.
14602   return Evaluate(Result, Info, E);
14603 }
14604 
14605 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
14606 /// lvalue-to-rvalue cast if it is an lvalue.
14607 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
14608   assert(!E->isValueDependent());
14609   if (Info.EnableNewConstInterp) {
14610     if (!Info.Ctx.getInterpContext().evaluateAsRValue(Info, E, Result))
14611       return false;
14612   } else {
14613     if (E->getType().isNull())
14614       return false;
14615 
14616     if (!CheckLiteralType(Info, E))
14617       return false;
14618 
14619     if (!::Evaluate(Result, Info, E))
14620       return false;
14621 
14622     if (E->isGLValue()) {
14623       LValue LV;
14624       LV.setFrom(Info.Ctx, Result);
14625       if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
14626         return false;
14627     }
14628   }
14629 
14630   // Check this core constant expression is a constant expression.
14631   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result,
14632                                  ConstantExprKind::Normal) &&
14633          CheckMemoryLeaks(Info);
14634 }
14635 
14636 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
14637                                  const ASTContext &Ctx, bool &IsConst) {
14638   // Fast-path evaluations of integer literals, since we sometimes see files
14639   // containing vast quantities of these.
14640   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
14641     Result.Val = APValue(APSInt(L->getValue(),
14642                                 L->getType()->isUnsignedIntegerType()));
14643     IsConst = true;
14644     return true;
14645   }
14646 
14647   // This case should be rare, but we need to check it before we check on
14648   // the type below.
14649   if (Exp->getType().isNull()) {
14650     IsConst = false;
14651     return true;
14652   }
14653 
14654   // FIXME: Evaluating values of large array and record types can cause
14655   // performance problems. Only do so in C++11 for now.
14656   if (Exp->isPRValue() &&
14657       (Exp->getType()->isArrayType() || Exp->getType()->isRecordType()) &&
14658       !Ctx.getLangOpts().CPlusPlus11) {
14659     IsConst = false;
14660     return true;
14661   }
14662   return false;
14663 }
14664 
14665 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
14666                                       Expr::SideEffectsKind SEK) {
14667   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
14668          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
14669 }
14670 
14671 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
14672                              const ASTContext &Ctx, EvalInfo &Info) {
14673   assert(!E->isValueDependent());
14674   bool IsConst;
14675   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
14676     return IsConst;
14677 
14678   return EvaluateAsRValue(Info, E, Result.Val);
14679 }
14680 
14681 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
14682                           const ASTContext &Ctx,
14683                           Expr::SideEffectsKind AllowSideEffects,
14684                           EvalInfo &Info) {
14685   assert(!E->isValueDependent());
14686   if (!E->getType()->isIntegralOrEnumerationType())
14687     return false;
14688 
14689   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
14690       !ExprResult.Val.isInt() ||
14691       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14692     return false;
14693 
14694   return true;
14695 }
14696 
14697 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
14698                                  const ASTContext &Ctx,
14699                                  Expr::SideEffectsKind AllowSideEffects,
14700                                  EvalInfo &Info) {
14701   assert(!E->isValueDependent());
14702   if (!E->getType()->isFixedPointType())
14703     return false;
14704 
14705   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
14706     return false;
14707 
14708   if (!ExprResult.Val.isFixedPoint() ||
14709       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14710     return false;
14711 
14712   return true;
14713 }
14714 
14715 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
14716 /// any crazy technique (that has nothing to do with language standards) that
14717 /// we want to.  If this function returns true, it returns the folded constant
14718 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
14719 /// will be applied to the result.
14720 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
14721                             bool InConstantContext) const {
14722   assert(!isValueDependent() &&
14723          "Expression evaluator can't be called on a dependent expression.");
14724   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14725   Info.InConstantContext = InConstantContext;
14726   return ::EvaluateAsRValue(this, Result, Ctx, Info);
14727 }
14728 
14729 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
14730                                       bool InConstantContext) const {
14731   assert(!isValueDependent() &&
14732          "Expression evaluator can't be called on a dependent expression.");
14733   EvalResult Scratch;
14734   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
14735          HandleConversionToBool(Scratch.Val, Result);
14736 }
14737 
14738 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
14739                          SideEffectsKind AllowSideEffects,
14740                          bool InConstantContext) const {
14741   assert(!isValueDependent() &&
14742          "Expression evaluator can't be called on a dependent expression.");
14743   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14744   Info.InConstantContext = InConstantContext;
14745   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
14746 }
14747 
14748 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
14749                                 SideEffectsKind AllowSideEffects,
14750                                 bool InConstantContext) const {
14751   assert(!isValueDependent() &&
14752          "Expression evaluator can't be called on a dependent expression.");
14753   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
14754   Info.InConstantContext = InConstantContext;
14755   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
14756 }
14757 
14758 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
14759                            SideEffectsKind AllowSideEffects,
14760                            bool InConstantContext) const {
14761   assert(!isValueDependent() &&
14762          "Expression evaluator can't be called on a dependent expression.");
14763 
14764   if (!getType()->isRealFloatingType())
14765     return false;
14766 
14767   EvalResult ExprResult;
14768   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
14769       !ExprResult.Val.isFloat() ||
14770       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
14771     return false;
14772 
14773   Result = ExprResult.Val.getFloat();
14774   return true;
14775 }
14776 
14777 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
14778                             bool InConstantContext) const {
14779   assert(!isValueDependent() &&
14780          "Expression evaluator can't be called on a dependent expression.");
14781 
14782   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
14783   Info.InConstantContext = InConstantContext;
14784   LValue LV;
14785   CheckedTemporaries CheckedTemps;
14786   if (!EvaluateLValue(this, LV, Info) || !Info.discardCleanups() ||
14787       Result.HasSideEffects ||
14788       !CheckLValueConstantExpression(Info, getExprLoc(),
14789                                      Ctx.getLValueReferenceType(getType()), LV,
14790                                      ConstantExprKind::Normal, CheckedTemps))
14791     return false;
14792 
14793   LV.moveInto(Result.Val);
14794   return true;
14795 }
14796 
14797 static bool EvaluateDestruction(const ASTContext &Ctx, APValue::LValueBase Base,
14798                                 APValue DestroyedValue, QualType Type,
14799                                 SourceLocation Loc, Expr::EvalStatus &EStatus,
14800                                 bool IsConstantDestruction) {
14801   EvalInfo Info(Ctx, EStatus,
14802                 IsConstantDestruction ? EvalInfo::EM_ConstantExpression
14803                                       : EvalInfo::EM_ConstantFold);
14804   Info.setEvaluatingDecl(Base, DestroyedValue,
14805                          EvalInfo::EvaluatingDeclKind::Dtor);
14806   Info.InConstantContext = IsConstantDestruction;
14807 
14808   LValue LVal;
14809   LVal.set(Base);
14810 
14811   if (!HandleDestruction(Info, Loc, Base, DestroyedValue, Type) ||
14812       EStatus.HasSideEffects)
14813     return false;
14814 
14815   if (!Info.discardCleanups())
14816     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14817 
14818   return true;
14819 }
14820 
14821 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, const ASTContext &Ctx,
14822                                   ConstantExprKind Kind) const {
14823   assert(!isValueDependent() &&
14824          "Expression evaluator can't be called on a dependent expression.");
14825 
14826   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
14827   EvalInfo Info(Ctx, Result, EM);
14828   Info.InConstantContext = true;
14829 
14830   // The type of the object we're initializing is 'const T' for a class NTTP.
14831   QualType T = getType();
14832   if (Kind == ConstantExprKind::ClassTemplateArgument)
14833     T.addConst();
14834 
14835   // If we're evaluating a prvalue, fake up a MaterializeTemporaryExpr to
14836   // represent the result of the evaluation. CheckConstantExpression ensures
14837   // this doesn't escape.
14838   MaterializeTemporaryExpr BaseMTE(T, const_cast<Expr*>(this), true);
14839   APValue::LValueBase Base(&BaseMTE);
14840 
14841   Info.setEvaluatingDecl(Base, Result.Val);
14842   LValue LVal;
14843   LVal.set(Base);
14844 
14845   if (!::EvaluateInPlace(Result.Val, Info, LVal, this) || Result.HasSideEffects)
14846     return false;
14847 
14848   if (!Info.discardCleanups())
14849     llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14850 
14851   if (!CheckConstantExpression(Info, getExprLoc(), getStorageType(Ctx, this),
14852                                Result.Val, Kind))
14853     return false;
14854   if (!CheckMemoryLeaks(Info))
14855     return false;
14856 
14857   // If this is a class template argument, it's required to have constant
14858   // destruction too.
14859   if (Kind == ConstantExprKind::ClassTemplateArgument &&
14860       (!EvaluateDestruction(Ctx, Base, Result.Val, T, getBeginLoc(), Result,
14861                             true) ||
14862        Result.HasSideEffects)) {
14863     // FIXME: Prefix a note to indicate that the problem is lack of constant
14864     // destruction.
14865     return false;
14866   }
14867 
14868   return true;
14869 }
14870 
14871 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
14872                                  const VarDecl *VD,
14873                                  SmallVectorImpl<PartialDiagnosticAt> &Notes,
14874                                  bool IsConstantInitialization) const {
14875   assert(!isValueDependent() &&
14876          "Expression evaluator can't be called on a dependent expression.");
14877 
14878   // FIXME: Evaluating initializers for large array and record types can cause
14879   // performance problems. Only do so in C++11 for now.
14880   if (isPRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
14881       !Ctx.getLangOpts().CPlusPlus11)
14882     return false;
14883 
14884   Expr::EvalStatus EStatus;
14885   EStatus.Diag = &Notes;
14886 
14887   EvalInfo Info(Ctx, EStatus,
14888                 (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11)
14889                     ? EvalInfo::EM_ConstantExpression
14890                     : EvalInfo::EM_ConstantFold);
14891   Info.setEvaluatingDecl(VD, Value);
14892   Info.InConstantContext = IsConstantInitialization;
14893 
14894   SourceLocation DeclLoc = VD->getLocation();
14895   QualType DeclTy = VD->getType();
14896 
14897   if (Info.EnableNewConstInterp) {
14898     auto &InterpCtx = const_cast<ASTContext &>(Ctx).getInterpContext();
14899     if (!InterpCtx.evaluateAsInitializer(Info, VD, Value))
14900       return false;
14901   } else {
14902     LValue LVal;
14903     LVal.set(VD);
14904 
14905     if (!EvaluateInPlace(Value, Info, LVal, this,
14906                          /*AllowNonLiteralTypes=*/true) ||
14907         EStatus.HasSideEffects)
14908       return false;
14909 
14910     // At this point, any lifetime-extended temporaries are completely
14911     // initialized.
14912     Info.performLifetimeExtension();
14913 
14914     if (!Info.discardCleanups())
14915       llvm_unreachable("Unhandled cleanup; missing full expression marker?");
14916   }
14917   return CheckConstantExpression(Info, DeclLoc, DeclTy, Value,
14918                                  ConstantExprKind::Normal) &&
14919          CheckMemoryLeaks(Info);
14920 }
14921 
14922 bool VarDecl::evaluateDestruction(
14923     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
14924   Expr::EvalStatus EStatus;
14925   EStatus.Diag = &Notes;
14926 
14927   // Only treat the destruction as constant destruction if we formally have
14928   // constant initialization (or are usable in a constant expression).
14929   bool IsConstantDestruction = hasConstantInitialization();
14930 
14931   // Make a copy of the value for the destructor to mutate, if we know it.
14932   // Otherwise, treat the value as default-initialized; if the destructor works
14933   // anyway, then the destruction is constant (and must be essentially empty).
14934   APValue DestroyedValue;
14935   if (getEvaluatedValue() && !getEvaluatedValue()->isAbsent())
14936     DestroyedValue = *getEvaluatedValue();
14937   else if (!getDefaultInitValue(getType(), DestroyedValue))
14938     return false;
14939 
14940   if (!EvaluateDestruction(getASTContext(), this, std::move(DestroyedValue),
14941                            getType(), getLocation(), EStatus,
14942                            IsConstantDestruction) ||
14943       EStatus.HasSideEffects)
14944     return false;
14945 
14946   ensureEvaluatedStmt()->HasConstantDestruction = true;
14947   return true;
14948 }
14949 
14950 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
14951 /// constant folded, but discard the result.
14952 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
14953   assert(!isValueDependent() &&
14954          "Expression evaluator can't be called on a dependent expression.");
14955 
14956   EvalResult Result;
14957   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
14958          !hasUnacceptableSideEffect(Result, SEK);
14959 }
14960 
14961 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
14962                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14963   assert(!isValueDependent() &&
14964          "Expression evaluator can't be called on a dependent expression.");
14965 
14966   EvalResult EVResult;
14967   EVResult.Diag = Diag;
14968   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14969   Info.InConstantContext = true;
14970 
14971   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
14972   (void)Result;
14973   assert(Result && "Could not evaluate expression");
14974   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14975 
14976   return EVResult.Val.getInt();
14977 }
14978 
14979 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
14980     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
14981   assert(!isValueDependent() &&
14982          "Expression evaluator can't be called on a dependent expression.");
14983 
14984   EvalResult EVResult;
14985   EVResult.Diag = Diag;
14986   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
14987   Info.InConstantContext = true;
14988   Info.CheckingForUndefinedBehavior = true;
14989 
14990   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
14991   (void)Result;
14992   assert(Result && "Could not evaluate expression");
14993   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
14994 
14995   return EVResult.Val.getInt();
14996 }
14997 
14998 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
14999   assert(!isValueDependent() &&
15000          "Expression evaluator can't be called on a dependent expression.");
15001 
15002   bool IsConst;
15003   EvalResult EVResult;
15004   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
15005     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
15006     Info.CheckingForUndefinedBehavior = true;
15007     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
15008   }
15009 }
15010 
15011 bool Expr::EvalResult::isGlobalLValue() const {
15012   assert(Val.isLValue());
15013   return IsGlobalLValue(Val.getLValueBase());
15014 }
15015 
15016 /// isIntegerConstantExpr - this recursive routine will test if an expression is
15017 /// an integer constant expression.
15018 
15019 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
15020 /// comma, etc
15021 
15022 // CheckICE - This function does the fundamental ICE checking: the returned
15023 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
15024 // and a (possibly null) SourceLocation indicating the location of the problem.
15025 //
15026 // Note that to reduce code duplication, this helper does no evaluation
15027 // itself; the caller checks whether the expression is evaluatable, and
15028 // in the rare cases where CheckICE actually cares about the evaluated
15029 // value, it calls into Evaluate.
15030 
15031 namespace {
15032 
15033 enum ICEKind {
15034   /// This expression is an ICE.
15035   IK_ICE,
15036   /// This expression is not an ICE, but if it isn't evaluated, it's
15037   /// a legal subexpression for an ICE. This return value is used to handle
15038   /// the comma operator in C99 mode, and non-constant subexpressions.
15039   IK_ICEIfUnevaluated,
15040   /// This expression is not an ICE, and is not a legal subexpression for one.
15041   IK_NotICE
15042 };
15043 
15044 struct ICEDiag {
15045   ICEKind Kind;
15046   SourceLocation Loc;
15047 
15048   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
15049 };
15050 
15051 }
15052 
15053 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
15054 
15055 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
15056 
15057 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
15058   Expr::EvalResult EVResult;
15059   Expr::EvalStatus Status;
15060   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15061 
15062   Info.InConstantContext = true;
15063   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
15064       !EVResult.Val.isInt())
15065     return ICEDiag(IK_NotICE, E->getBeginLoc());
15066 
15067   return NoDiag();
15068 }
15069 
15070 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
15071   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
15072   if (!E->getType()->isIntegralOrEnumerationType())
15073     return ICEDiag(IK_NotICE, E->getBeginLoc());
15074 
15075   switch (E->getStmtClass()) {
15076 #define ABSTRACT_STMT(Node)
15077 #define STMT(Node, Base) case Expr::Node##Class:
15078 #define EXPR(Node, Base)
15079 #include "clang/AST/StmtNodes.inc"
15080   case Expr::PredefinedExprClass:
15081   case Expr::FloatingLiteralClass:
15082   case Expr::ImaginaryLiteralClass:
15083   case Expr::StringLiteralClass:
15084   case Expr::ArraySubscriptExprClass:
15085   case Expr::MatrixSubscriptExprClass:
15086   case Expr::OMPArraySectionExprClass:
15087   case Expr::OMPArrayShapingExprClass:
15088   case Expr::OMPIteratorExprClass:
15089   case Expr::MemberExprClass:
15090   case Expr::CompoundAssignOperatorClass:
15091   case Expr::CompoundLiteralExprClass:
15092   case Expr::ExtVectorElementExprClass:
15093   case Expr::DesignatedInitExprClass:
15094   case Expr::ArrayInitLoopExprClass:
15095   case Expr::ArrayInitIndexExprClass:
15096   case Expr::NoInitExprClass:
15097   case Expr::DesignatedInitUpdateExprClass:
15098   case Expr::ImplicitValueInitExprClass:
15099   case Expr::ParenListExprClass:
15100   case Expr::VAArgExprClass:
15101   case Expr::AddrLabelExprClass:
15102   case Expr::StmtExprClass:
15103   case Expr::CXXMemberCallExprClass:
15104   case Expr::CUDAKernelCallExprClass:
15105   case Expr::CXXAddrspaceCastExprClass:
15106   case Expr::CXXDynamicCastExprClass:
15107   case Expr::CXXTypeidExprClass:
15108   case Expr::CXXUuidofExprClass:
15109   case Expr::MSPropertyRefExprClass:
15110   case Expr::MSPropertySubscriptExprClass:
15111   case Expr::CXXNullPtrLiteralExprClass:
15112   case Expr::UserDefinedLiteralClass:
15113   case Expr::CXXThisExprClass:
15114   case Expr::CXXThrowExprClass:
15115   case Expr::CXXNewExprClass:
15116   case Expr::CXXDeleteExprClass:
15117   case Expr::CXXPseudoDestructorExprClass:
15118   case Expr::UnresolvedLookupExprClass:
15119   case Expr::TypoExprClass:
15120   case Expr::RecoveryExprClass:
15121   case Expr::DependentScopeDeclRefExprClass:
15122   case Expr::CXXConstructExprClass:
15123   case Expr::CXXInheritedCtorInitExprClass:
15124   case Expr::CXXStdInitializerListExprClass:
15125   case Expr::CXXBindTemporaryExprClass:
15126   case Expr::ExprWithCleanupsClass:
15127   case Expr::CXXTemporaryObjectExprClass:
15128   case Expr::CXXUnresolvedConstructExprClass:
15129   case Expr::CXXDependentScopeMemberExprClass:
15130   case Expr::UnresolvedMemberExprClass:
15131   case Expr::ObjCStringLiteralClass:
15132   case Expr::ObjCBoxedExprClass:
15133   case Expr::ObjCArrayLiteralClass:
15134   case Expr::ObjCDictionaryLiteralClass:
15135   case Expr::ObjCEncodeExprClass:
15136   case Expr::ObjCMessageExprClass:
15137   case Expr::ObjCSelectorExprClass:
15138   case Expr::ObjCProtocolExprClass:
15139   case Expr::ObjCIvarRefExprClass:
15140   case Expr::ObjCPropertyRefExprClass:
15141   case Expr::ObjCSubscriptRefExprClass:
15142   case Expr::ObjCIsaExprClass:
15143   case Expr::ObjCAvailabilityCheckExprClass:
15144   case Expr::ShuffleVectorExprClass:
15145   case Expr::ConvertVectorExprClass:
15146   case Expr::BlockExprClass:
15147   case Expr::NoStmtClass:
15148   case Expr::OpaqueValueExprClass:
15149   case Expr::PackExpansionExprClass:
15150   case Expr::SubstNonTypeTemplateParmPackExprClass:
15151   case Expr::FunctionParmPackExprClass:
15152   case Expr::AsTypeExprClass:
15153   case Expr::ObjCIndirectCopyRestoreExprClass:
15154   case Expr::MaterializeTemporaryExprClass:
15155   case Expr::PseudoObjectExprClass:
15156   case Expr::AtomicExprClass:
15157   case Expr::LambdaExprClass:
15158   case Expr::CXXFoldExprClass:
15159   case Expr::CoawaitExprClass:
15160   case Expr::DependentCoawaitExprClass:
15161   case Expr::CoyieldExprClass:
15162   case Expr::SYCLUniqueStableNameExprClass:
15163     return ICEDiag(IK_NotICE, E->getBeginLoc());
15164 
15165   case Expr::InitListExprClass: {
15166     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
15167     // form "T x = { a };" is equivalent to "T x = a;".
15168     // Unless we're initializing a reference, T is a scalar as it is known to be
15169     // of integral or enumeration type.
15170     if (E->isPRValue())
15171       if (cast<InitListExpr>(E)->getNumInits() == 1)
15172         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
15173     return ICEDiag(IK_NotICE, E->getBeginLoc());
15174   }
15175 
15176   case Expr::SizeOfPackExprClass:
15177   case Expr::GNUNullExprClass:
15178   case Expr::SourceLocExprClass:
15179     return NoDiag();
15180 
15181   case Expr::SubstNonTypeTemplateParmExprClass:
15182     return
15183       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
15184 
15185   case Expr::ConstantExprClass:
15186     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
15187 
15188   case Expr::ParenExprClass:
15189     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
15190   case Expr::GenericSelectionExprClass:
15191     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
15192   case Expr::IntegerLiteralClass:
15193   case Expr::FixedPointLiteralClass:
15194   case Expr::CharacterLiteralClass:
15195   case Expr::ObjCBoolLiteralExprClass:
15196   case Expr::CXXBoolLiteralExprClass:
15197   case Expr::CXXScalarValueInitExprClass:
15198   case Expr::TypeTraitExprClass:
15199   case Expr::ConceptSpecializationExprClass:
15200   case Expr::RequiresExprClass:
15201   case Expr::ArrayTypeTraitExprClass:
15202   case Expr::ExpressionTraitExprClass:
15203   case Expr::CXXNoexceptExprClass:
15204     return NoDiag();
15205   case Expr::CallExprClass:
15206   case Expr::CXXOperatorCallExprClass: {
15207     // C99 6.6/3 allows function calls within unevaluated subexpressions of
15208     // constant expressions, but they can never be ICEs because an ICE cannot
15209     // contain an operand of (pointer to) function type.
15210     const CallExpr *CE = cast<CallExpr>(E);
15211     if (CE->getBuiltinCallee())
15212       return CheckEvalInICE(E, Ctx);
15213     return ICEDiag(IK_NotICE, E->getBeginLoc());
15214   }
15215   case Expr::CXXRewrittenBinaryOperatorClass:
15216     return CheckICE(cast<CXXRewrittenBinaryOperator>(E)->getSemanticForm(),
15217                     Ctx);
15218   case Expr::DeclRefExprClass: {
15219     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
15220     if (isa<EnumConstantDecl>(D))
15221       return NoDiag();
15222 
15223     // C++ and OpenCL (FIXME: spec reference?) allow reading const-qualified
15224     // integer variables in constant expressions:
15225     //
15226     // C++ 7.1.5.1p2
15227     //   A variable of non-volatile const-qualified integral or enumeration
15228     //   type initialized by an ICE can be used in ICEs.
15229     //
15230     // We sometimes use CheckICE to check the C++98 rules in C++11 mode. In
15231     // that mode, use of reference variables should not be allowed.
15232     const VarDecl *VD = dyn_cast<VarDecl>(D);
15233     if (VD && VD->isUsableInConstantExpressions(Ctx) &&
15234         !VD->getType()->isReferenceType())
15235       return NoDiag();
15236 
15237     return ICEDiag(IK_NotICE, E->getBeginLoc());
15238   }
15239   case Expr::UnaryOperatorClass: {
15240     const UnaryOperator *Exp = cast<UnaryOperator>(E);
15241     switch (Exp->getOpcode()) {
15242     case UO_PostInc:
15243     case UO_PostDec:
15244     case UO_PreInc:
15245     case UO_PreDec:
15246     case UO_AddrOf:
15247     case UO_Deref:
15248     case UO_Coawait:
15249       // C99 6.6/3 allows increment and decrement within unevaluated
15250       // subexpressions of constant expressions, but they can never be ICEs
15251       // because an ICE cannot contain an lvalue operand.
15252       return ICEDiag(IK_NotICE, E->getBeginLoc());
15253     case UO_Extension:
15254     case UO_LNot:
15255     case UO_Plus:
15256     case UO_Minus:
15257     case UO_Not:
15258     case UO_Real:
15259     case UO_Imag:
15260       return CheckICE(Exp->getSubExpr(), Ctx);
15261     }
15262     llvm_unreachable("invalid unary operator class");
15263   }
15264   case Expr::OffsetOfExprClass: {
15265     // Note that per C99, offsetof must be an ICE. And AFAIK, using
15266     // EvaluateAsRValue matches the proposed gcc behavior for cases like
15267     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
15268     // compliance: we should warn earlier for offsetof expressions with
15269     // array subscripts that aren't ICEs, and if the array subscripts
15270     // are ICEs, the value of the offsetof must be an integer constant.
15271     return CheckEvalInICE(E, Ctx);
15272   }
15273   case Expr::UnaryExprOrTypeTraitExprClass: {
15274     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
15275     if ((Exp->getKind() ==  UETT_SizeOf) &&
15276         Exp->getTypeOfArgument()->isVariableArrayType())
15277       return ICEDiag(IK_NotICE, E->getBeginLoc());
15278     return NoDiag();
15279   }
15280   case Expr::BinaryOperatorClass: {
15281     const BinaryOperator *Exp = cast<BinaryOperator>(E);
15282     switch (Exp->getOpcode()) {
15283     case BO_PtrMemD:
15284     case BO_PtrMemI:
15285     case BO_Assign:
15286     case BO_MulAssign:
15287     case BO_DivAssign:
15288     case BO_RemAssign:
15289     case BO_AddAssign:
15290     case BO_SubAssign:
15291     case BO_ShlAssign:
15292     case BO_ShrAssign:
15293     case BO_AndAssign:
15294     case BO_XorAssign:
15295     case BO_OrAssign:
15296       // C99 6.6/3 allows assignments within unevaluated subexpressions of
15297       // constant expressions, but they can never be ICEs because an ICE cannot
15298       // contain an lvalue operand.
15299       return ICEDiag(IK_NotICE, E->getBeginLoc());
15300 
15301     case BO_Mul:
15302     case BO_Div:
15303     case BO_Rem:
15304     case BO_Add:
15305     case BO_Sub:
15306     case BO_Shl:
15307     case BO_Shr:
15308     case BO_LT:
15309     case BO_GT:
15310     case BO_LE:
15311     case BO_GE:
15312     case BO_EQ:
15313     case BO_NE:
15314     case BO_And:
15315     case BO_Xor:
15316     case BO_Or:
15317     case BO_Comma:
15318     case BO_Cmp: {
15319       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15320       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15321       if (Exp->getOpcode() == BO_Div ||
15322           Exp->getOpcode() == BO_Rem) {
15323         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
15324         // we don't evaluate one.
15325         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
15326           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
15327           if (REval == 0)
15328             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15329           if (REval.isSigned() && REval.isAllOnesValue()) {
15330             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
15331             if (LEval.isMinSignedValue())
15332               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15333           }
15334         }
15335       }
15336       if (Exp->getOpcode() == BO_Comma) {
15337         if (Ctx.getLangOpts().C99) {
15338           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
15339           // if it isn't evaluated.
15340           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
15341             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
15342         } else {
15343           // In both C89 and C++, commas in ICEs are illegal.
15344           return ICEDiag(IK_NotICE, E->getBeginLoc());
15345         }
15346       }
15347       return Worst(LHSResult, RHSResult);
15348     }
15349     case BO_LAnd:
15350     case BO_LOr: {
15351       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
15352       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
15353       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
15354         // Rare case where the RHS has a comma "side-effect"; we need
15355         // to actually check the condition to see whether the side
15356         // with the comma is evaluated.
15357         if ((Exp->getOpcode() == BO_LAnd) !=
15358             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
15359           return RHSResult;
15360         return NoDiag();
15361       }
15362 
15363       return Worst(LHSResult, RHSResult);
15364     }
15365     }
15366     llvm_unreachable("invalid binary operator kind");
15367   }
15368   case Expr::ImplicitCastExprClass:
15369   case Expr::CStyleCastExprClass:
15370   case Expr::CXXFunctionalCastExprClass:
15371   case Expr::CXXStaticCastExprClass:
15372   case Expr::CXXReinterpretCastExprClass:
15373   case Expr::CXXConstCastExprClass:
15374   case Expr::ObjCBridgedCastExprClass: {
15375     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
15376     if (isa<ExplicitCastExpr>(E)) {
15377       if (const FloatingLiteral *FL
15378             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
15379         unsigned DestWidth = Ctx.getIntWidth(E->getType());
15380         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
15381         APSInt IgnoredVal(DestWidth, !DestSigned);
15382         bool Ignored;
15383         // If the value does not fit in the destination type, the behavior is
15384         // undefined, so we are not required to treat it as a constant
15385         // expression.
15386         if (FL->getValue().convertToInteger(IgnoredVal,
15387                                             llvm::APFloat::rmTowardZero,
15388                                             &Ignored) & APFloat::opInvalidOp)
15389           return ICEDiag(IK_NotICE, E->getBeginLoc());
15390         return NoDiag();
15391       }
15392     }
15393     switch (cast<CastExpr>(E)->getCastKind()) {
15394     case CK_LValueToRValue:
15395     case CK_AtomicToNonAtomic:
15396     case CK_NonAtomicToAtomic:
15397     case CK_NoOp:
15398     case CK_IntegralToBoolean:
15399     case CK_IntegralCast:
15400       return CheckICE(SubExpr, Ctx);
15401     default:
15402       return ICEDiag(IK_NotICE, E->getBeginLoc());
15403     }
15404   }
15405   case Expr::BinaryConditionalOperatorClass: {
15406     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
15407     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
15408     if (CommonResult.Kind == IK_NotICE) return CommonResult;
15409     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15410     if (FalseResult.Kind == IK_NotICE) return FalseResult;
15411     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
15412     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
15413         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
15414     return FalseResult;
15415   }
15416   case Expr::ConditionalOperatorClass: {
15417     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
15418     // If the condition (ignoring parens) is a __builtin_constant_p call,
15419     // then only the true side is actually considered in an integer constant
15420     // expression, and it is fully evaluated.  This is an important GNU
15421     // extension.  See GCC PR38377 for discussion.
15422     if (const CallExpr *CallCE
15423         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
15424       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
15425         return CheckEvalInICE(E, Ctx);
15426     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
15427     if (CondResult.Kind == IK_NotICE)
15428       return CondResult;
15429 
15430     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
15431     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
15432 
15433     if (TrueResult.Kind == IK_NotICE)
15434       return TrueResult;
15435     if (FalseResult.Kind == IK_NotICE)
15436       return FalseResult;
15437     if (CondResult.Kind == IK_ICEIfUnevaluated)
15438       return CondResult;
15439     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
15440       return NoDiag();
15441     // Rare case where the diagnostics depend on which side is evaluated
15442     // Note that if we get here, CondResult is 0, and at least one of
15443     // TrueResult and FalseResult is non-zero.
15444     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
15445       return FalseResult;
15446     return TrueResult;
15447   }
15448   case Expr::CXXDefaultArgExprClass:
15449     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
15450   case Expr::CXXDefaultInitExprClass:
15451     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
15452   case Expr::ChooseExprClass: {
15453     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
15454   }
15455   case Expr::BuiltinBitCastExprClass: {
15456     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
15457       return ICEDiag(IK_NotICE, E->getBeginLoc());
15458     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
15459   }
15460   }
15461 
15462   llvm_unreachable("Invalid StmtClass!");
15463 }
15464 
15465 /// Evaluate an expression as a C++11 integral constant expression.
15466 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
15467                                                     const Expr *E,
15468                                                     llvm::APSInt *Value,
15469                                                     SourceLocation *Loc) {
15470   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
15471     if (Loc) *Loc = E->getExprLoc();
15472     return false;
15473   }
15474 
15475   APValue Result;
15476   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
15477     return false;
15478 
15479   if (!Result.isInt()) {
15480     if (Loc) *Loc = E->getExprLoc();
15481     return false;
15482   }
15483 
15484   if (Value) *Value = Result.getInt();
15485   return true;
15486 }
15487 
15488 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
15489                                  SourceLocation *Loc) const {
15490   assert(!isValueDependent() &&
15491          "Expression evaluator can't be called on a dependent expression.");
15492 
15493   if (Ctx.getLangOpts().CPlusPlus11)
15494     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
15495 
15496   ICEDiag D = CheckICE(this, Ctx);
15497   if (D.Kind != IK_ICE) {
15498     if (Loc) *Loc = D.Loc;
15499     return false;
15500   }
15501   return true;
15502 }
15503 
15504 Optional<llvm::APSInt> Expr::getIntegerConstantExpr(const ASTContext &Ctx,
15505                                                     SourceLocation *Loc,
15506                                                     bool isEvaluated) const {
15507   assert(!isValueDependent() &&
15508          "Expression evaluator can't be called on a dependent expression.");
15509 
15510   APSInt Value;
15511 
15512   if (Ctx.getLangOpts().CPlusPlus11) {
15513     if (EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc))
15514       return Value;
15515     return None;
15516   }
15517 
15518   if (!isIntegerConstantExpr(Ctx, Loc))
15519     return None;
15520 
15521   // The only possible side-effects here are due to UB discovered in the
15522   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
15523   // required to treat the expression as an ICE, so we produce the folded
15524   // value.
15525   EvalResult ExprResult;
15526   Expr::EvalStatus Status;
15527   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
15528   Info.InConstantContext = true;
15529 
15530   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
15531     llvm_unreachable("ICE cannot be evaluated!");
15532 
15533   return ExprResult.Val.getInt();
15534 }
15535 
15536 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
15537   assert(!isValueDependent() &&
15538          "Expression evaluator can't be called on a dependent expression.");
15539 
15540   return CheckICE(this, Ctx).Kind == IK_ICE;
15541 }
15542 
15543 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
15544                                SourceLocation *Loc) const {
15545   assert(!isValueDependent() &&
15546          "Expression evaluator can't be called on a dependent expression.");
15547 
15548   // We support this checking in C++98 mode in order to diagnose compatibility
15549   // issues.
15550   assert(Ctx.getLangOpts().CPlusPlus);
15551 
15552   // Build evaluation settings.
15553   Expr::EvalStatus Status;
15554   SmallVector<PartialDiagnosticAt, 8> Diags;
15555   Status.Diag = &Diags;
15556   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
15557 
15558   APValue Scratch;
15559   bool IsConstExpr =
15560       ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch) &&
15561       // FIXME: We don't produce a diagnostic for this, but the callers that
15562       // call us on arbitrary full-expressions should generally not care.
15563       Info.discardCleanups() && !Status.HasSideEffects;
15564 
15565   if (!Diags.empty()) {
15566     IsConstExpr = false;
15567     if (Loc) *Loc = Diags[0].first;
15568   } else if (!IsConstExpr) {
15569     // FIXME: This shouldn't happen.
15570     if (Loc) *Loc = getExprLoc();
15571   }
15572 
15573   return IsConstExpr;
15574 }
15575 
15576 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
15577                                     const FunctionDecl *Callee,
15578                                     ArrayRef<const Expr*> Args,
15579                                     const Expr *This) const {
15580   assert(!isValueDependent() &&
15581          "Expression evaluator can't be called on a dependent expression.");
15582 
15583   Expr::EvalStatus Status;
15584   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
15585   Info.InConstantContext = true;
15586 
15587   LValue ThisVal;
15588   const LValue *ThisPtr = nullptr;
15589   if (This) {
15590 #ifndef NDEBUG
15591     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
15592     assert(MD && "Don't provide `this` for non-methods.");
15593     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
15594 #endif
15595     if (!This->isValueDependent() &&
15596         EvaluateObjectArgument(Info, This, ThisVal) &&
15597         !Info.EvalStatus.HasSideEffects)
15598       ThisPtr = &ThisVal;
15599 
15600     // Ignore any side-effects from a failed evaluation. This is safe because
15601     // they can't interfere with any other argument evaluation.
15602     Info.EvalStatus.HasSideEffects = false;
15603   }
15604 
15605   CallRef Call = Info.CurrentCall->createCall(Callee);
15606   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
15607        I != E; ++I) {
15608     unsigned Idx = I - Args.begin();
15609     if (Idx >= Callee->getNumParams())
15610       break;
15611     const ParmVarDecl *PVD = Callee->getParamDecl(Idx);
15612     if ((*I)->isValueDependent() ||
15613         !EvaluateCallArg(PVD, *I, Call, Info) ||
15614         Info.EvalStatus.HasSideEffects) {
15615       // If evaluation fails, throw away the argument entirely.
15616       if (APValue *Slot = Info.getParamSlot(Call, PVD))
15617         *Slot = APValue();
15618     }
15619 
15620     // Ignore any side-effects from a failed evaluation. This is safe because
15621     // they can't interfere with any other argument evaluation.
15622     Info.EvalStatus.HasSideEffects = false;
15623   }
15624 
15625   // Parameter cleanups happen in the caller and are not part of this
15626   // evaluation.
15627   Info.discardCleanups();
15628   Info.EvalStatus.HasSideEffects = false;
15629 
15630   // Build fake call to Callee.
15631   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr, Call);
15632   // FIXME: Missing ExprWithCleanups in enable_if conditions?
15633   FullExpressionRAII Scope(Info);
15634   return Evaluate(Value, Info, this) && Scope.destroy() &&
15635          !Info.EvalStatus.HasSideEffects;
15636 }
15637 
15638 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
15639                                    SmallVectorImpl<
15640                                      PartialDiagnosticAt> &Diags) {
15641   // FIXME: It would be useful to check constexpr function templates, but at the
15642   // moment the constant expression evaluator cannot cope with the non-rigorous
15643   // ASTs which we build for dependent expressions.
15644   if (FD->isDependentContext())
15645     return true;
15646 
15647   Expr::EvalStatus Status;
15648   Status.Diag = &Diags;
15649 
15650   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
15651   Info.InConstantContext = true;
15652   Info.CheckingPotentialConstantExpression = true;
15653 
15654   // The constexpr VM attempts to compile all methods to bytecode here.
15655   if (Info.EnableNewConstInterp) {
15656     Info.Ctx.getInterpContext().isPotentialConstantExpr(Info, FD);
15657     return Diags.empty();
15658   }
15659 
15660   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
15661   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
15662 
15663   // Fabricate an arbitrary expression on the stack and pretend that it
15664   // is a temporary being used as the 'this' pointer.
15665   LValue This;
15666   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
15667   This.set({&VIE, Info.CurrentCall->Index});
15668 
15669   ArrayRef<const Expr*> Args;
15670 
15671   APValue Scratch;
15672   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
15673     // Evaluate the call as a constant initializer, to allow the construction
15674     // of objects of non-literal types.
15675     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
15676     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
15677   } else {
15678     SourceLocation Loc = FD->getLocation();
15679     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
15680                        Args, CallRef(), FD->getBody(), Info, Scratch, nullptr);
15681   }
15682 
15683   return Diags.empty();
15684 }
15685 
15686 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
15687                                               const FunctionDecl *FD,
15688                                               SmallVectorImpl<
15689                                                 PartialDiagnosticAt> &Diags) {
15690   assert(!E->isValueDependent() &&
15691          "Expression evaluator can't be called on a dependent expression.");
15692 
15693   Expr::EvalStatus Status;
15694   Status.Diag = &Diags;
15695 
15696   EvalInfo Info(FD->getASTContext(), Status,
15697                 EvalInfo::EM_ConstantExpressionUnevaluated);
15698   Info.InConstantContext = true;
15699   Info.CheckingPotentialConstantExpression = true;
15700 
15701   // Fabricate a call stack frame to give the arguments a plausible cover story.
15702   CallStackFrame Frame(Info, SourceLocation(), FD, /*This*/ nullptr, CallRef());
15703 
15704   APValue ResultScratch;
15705   Evaluate(ResultScratch, Info, E);
15706   return Diags.empty();
15707 }
15708 
15709 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
15710                                  unsigned Type) const {
15711   if (!getType()->isPointerType())
15712     return false;
15713 
15714   Expr::EvalStatus Status;
15715   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15716   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
15717 }
15718 
15719 static bool EvaluateBuiltinStrLen(const Expr *E, uint64_t &Result,
15720                                   EvalInfo &Info) {
15721   if (!E->getType()->hasPointerRepresentation() || !E->isPRValue())
15722     return false;
15723 
15724   LValue String;
15725 
15726   if (!EvaluatePointer(E, String, Info))
15727     return false;
15728 
15729   QualType CharTy = E->getType()->getPointeeType();
15730 
15731   // Fast path: if it's a string literal, search the string value.
15732   if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
15733           String.getLValueBase().dyn_cast<const Expr *>())) {
15734     StringRef Str = S->getBytes();
15735     int64_t Off = String.Offset.getQuantity();
15736     if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
15737         S->getCharByteWidth() == 1 &&
15738         // FIXME: Add fast-path for wchar_t too.
15739         Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
15740       Str = Str.substr(Off);
15741 
15742       StringRef::size_type Pos = Str.find(0);
15743       if (Pos != StringRef::npos)
15744         Str = Str.substr(0, Pos);
15745 
15746       Result = Str.size();
15747       return true;
15748     }
15749 
15750     // Fall through to slow path.
15751   }
15752 
15753   // Slow path: scan the bytes of the string looking for the terminating 0.
15754   for (uint64_t Strlen = 0; /**/; ++Strlen) {
15755     APValue Char;
15756     if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
15757         !Char.isInt())
15758       return false;
15759     if (!Char.getInt()) {
15760       Result = Strlen;
15761       return true;
15762     }
15763     if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
15764       return false;
15765   }
15766 }
15767 
15768 bool Expr::tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const {
15769   Expr::EvalStatus Status;
15770   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
15771   return EvaluateBuiltinStrLen(this, Result, Info);
15772 }
15773