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 "clang/AST/APValue.h"
36 #include "clang/AST/ASTContext.h"
37 #include "clang/AST/ASTDiagnostic.h"
38 #include "clang/AST/ASTLambda.h"
39 #include "clang/AST/CXXInheritance.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/CurrentSourceLocExprScope.h"
42 #include "clang/AST/Expr.h"
43 #include "clang/AST/OSLog.h"
44 #include "clang/AST/RecordLayout.h"
45 #include "clang/AST/StmtVisitor.h"
46 #include "clang/AST/TypeLoc.h"
47 #include "clang/Basic/Builtins.h"
48 #include "clang/Basic/FixedPoint.h"
49 #include "clang/Basic/TargetInfo.h"
50 #include "llvm/ADT/Optional.h"
51 #include "llvm/ADT/SmallBitVector.h"
52 #include "llvm/Support/SaveAndRestore.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include <cstring>
55 #include <functional>
56 
57 #define DEBUG_TYPE "exprconstant"
58 
59 using namespace clang;
60 using llvm::APInt;
61 using llvm::APSInt;
62 using llvm::APFloat;
63 using llvm::Optional;
64 
65 static bool IsGlobalLValue(APValue::LValueBase B);
66 
67 namespace {
68   struct LValue;
69   struct CallStackFrame;
70   struct EvalInfo;
71 
72   using SourceLocExprScopeGuard =
73       CurrentSourceLocExprScope::SourceLocExprScopeGuard;
74 
75   static QualType getType(APValue::LValueBase B) {
76     if (!B) return QualType();
77     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
78       // FIXME: It's unclear where we're supposed to take the type from, and
79       // this actually matters for arrays of unknown bound. Eg:
80       //
81       // extern int arr[]; void f() { extern int arr[3]; };
82       // constexpr int *p = &arr[1]; // valid?
83       //
84       // For now, we take the array bound from the most recent declaration.
85       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
86            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
87         QualType T = Redecl->getType();
88         if (!T->isIncompleteArrayType())
89           return T;
90       }
91       return D->getType();
92     }
93 
94     if (B.is<TypeInfoLValue>())
95       return B.getTypeInfoType();
96 
97     const Expr *Base = B.get<const Expr*>();
98 
99     // For a materialized temporary, the type of the temporary we materialized
100     // may not be the type of the expression.
101     if (const MaterializeTemporaryExpr *MTE =
102             dyn_cast<MaterializeTemporaryExpr>(Base)) {
103       SmallVector<const Expr *, 2> CommaLHSs;
104       SmallVector<SubobjectAdjustment, 2> Adjustments;
105       const Expr *Temp = MTE->GetTemporaryExpr();
106       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
107                                                                Adjustments);
108       // Keep any cv-qualifiers from the reference if we generated a temporary
109       // for it directly. Otherwise use the type after adjustment.
110       if (!Adjustments.empty())
111         return Inner->getType();
112     }
113 
114     return Base->getType();
115   }
116 
117   /// Get an LValue path entry, which is known to not be an array index, as a
118   /// field declaration.
119   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
120     return dyn_cast_or_null<FieldDecl>(E.getAsBaseOrMember().getPointer());
121   }
122   /// Get an LValue path entry, which is known to not be an array index, as a
123   /// base class declaration.
124   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
125     return dyn_cast_or_null<CXXRecordDecl>(E.getAsBaseOrMember().getPointer());
126   }
127   /// Determine whether this LValue path entry for a base class names a virtual
128   /// base class.
129   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
130     return E.getAsBaseOrMember().getInt();
131   }
132 
133   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
134   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
135     const FunctionDecl *Callee = CE->getDirectCallee();
136     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
137   }
138 
139   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
140   /// This will look through a single cast.
141   ///
142   /// Returns null if we couldn't unwrap a function with alloc_size.
143   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
144     if (!E->getType()->isPointerType())
145       return nullptr;
146 
147     E = E->IgnoreParens();
148     // If we're doing a variable assignment from e.g. malloc(N), there will
149     // probably be a cast of some kind. In exotic cases, we might also see a
150     // top-level ExprWithCleanups. Ignore them either way.
151     if (const auto *FE = dyn_cast<FullExpr>(E))
152       E = FE->getSubExpr()->IgnoreParens();
153 
154     if (const auto *Cast = dyn_cast<CastExpr>(E))
155       E = Cast->getSubExpr()->IgnoreParens();
156 
157     if (const auto *CE = dyn_cast<CallExpr>(E))
158       return getAllocSizeAttr(CE) ? CE : nullptr;
159     return nullptr;
160   }
161 
162   /// Determines whether or not the given Base contains a call to a function
163   /// with the alloc_size attribute.
164   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
165     const auto *E = Base.dyn_cast<const Expr *>();
166     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
167   }
168 
169   /// The bound to claim that an array of unknown bound has.
170   /// The value in MostDerivedArraySize is undefined in this case. So, set it
171   /// to an arbitrary value that's likely to loudly break things if it's used.
172   static const uint64_t AssumedSizeForUnsizedArray =
173       std::numeric_limits<uint64_t>::max() / 2;
174 
175   /// Determines if an LValue with the given LValueBase will have an unsized
176   /// array in its designator.
177   /// Find the path length and type of the most-derived subobject in the given
178   /// path, and find the size of the containing array, if any.
179   static unsigned
180   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
181                            ArrayRef<APValue::LValuePathEntry> Path,
182                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
183                            bool &FirstEntryIsUnsizedArray) {
184     // This only accepts LValueBases from APValues, and APValues don't support
185     // arrays that lack size info.
186     assert(!isBaseAnAllocSizeCall(Base) &&
187            "Unsized arrays shouldn't appear here");
188     unsigned MostDerivedLength = 0;
189     Type = getType(Base);
190 
191     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
192       if (Type->isArrayType()) {
193         const ArrayType *AT = Ctx.getAsArrayType(Type);
194         Type = AT->getElementType();
195         MostDerivedLength = I + 1;
196         IsArray = true;
197 
198         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
199           ArraySize = CAT->getSize().getZExtValue();
200         } else {
201           assert(I == 0 && "unexpected unsized array designator");
202           FirstEntryIsUnsizedArray = true;
203           ArraySize = AssumedSizeForUnsizedArray;
204         }
205       } else if (Type->isAnyComplexType()) {
206         const ComplexType *CT = Type->castAs<ComplexType>();
207         Type = CT->getElementType();
208         ArraySize = 2;
209         MostDerivedLength = I + 1;
210         IsArray = true;
211       } else if (const FieldDecl *FD = getAsField(Path[I])) {
212         Type = FD->getType();
213         ArraySize = 0;
214         MostDerivedLength = I + 1;
215         IsArray = false;
216       } else {
217         // Path[I] describes a base class.
218         ArraySize = 0;
219         IsArray = false;
220       }
221     }
222     return MostDerivedLength;
223   }
224 
225   // The order of this enum is important for diagnostics.
226   enum CheckSubobjectKind {
227     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
228     CSK_Real, CSK_Imag
229   };
230 
231   /// A path from a glvalue to a subobject of that glvalue.
232   struct SubobjectDesignator {
233     /// True if the subobject was named in a manner not supported by C++11. Such
234     /// lvalues can still be folded, but they are not core constant expressions
235     /// and we cannot perform lvalue-to-rvalue conversions on them.
236     unsigned Invalid : 1;
237 
238     /// Is this a pointer one past the end of an object?
239     unsigned IsOnePastTheEnd : 1;
240 
241     /// Indicator of whether the first entry is an unsized array.
242     unsigned FirstEntryIsAnUnsizedArray : 1;
243 
244     /// Indicator of whether the most-derived object is an array element.
245     unsigned MostDerivedIsArrayElement : 1;
246 
247     /// The length of the path to the most-derived object of which this is a
248     /// subobject.
249     unsigned MostDerivedPathLength : 28;
250 
251     /// The size of the array of which the most-derived object is an element.
252     /// This will always be 0 if the most-derived object is not an array
253     /// element. 0 is not an indicator of whether or not the most-derived object
254     /// is an array, however, because 0-length arrays are allowed.
255     ///
256     /// If the current array is an unsized array, the value of this is
257     /// undefined.
258     uint64_t MostDerivedArraySize;
259 
260     /// The type of the most derived object referred to by this address.
261     QualType MostDerivedType;
262 
263     typedef APValue::LValuePathEntry PathEntry;
264 
265     /// The entries on the path from the glvalue to the designated subobject.
266     SmallVector<PathEntry, 8> Entries;
267 
268     SubobjectDesignator() : Invalid(true) {}
269 
270     explicit SubobjectDesignator(QualType T)
271         : Invalid(false), IsOnePastTheEnd(false),
272           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
273           MostDerivedPathLength(0), MostDerivedArraySize(0),
274           MostDerivedType(T) {}
275 
276     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
277         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
278           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
279           MostDerivedPathLength(0), MostDerivedArraySize(0) {
280       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
281       if (!Invalid) {
282         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
283         ArrayRef<PathEntry> VEntries = V.getLValuePath();
284         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
285         if (V.getLValueBase()) {
286           bool IsArray = false;
287           bool FirstIsUnsizedArray = false;
288           MostDerivedPathLength = findMostDerivedSubobject(
289               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
290               MostDerivedType, IsArray, FirstIsUnsizedArray);
291           MostDerivedIsArrayElement = IsArray;
292           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
293         }
294       }
295     }
296 
297     void truncate(ASTContext &Ctx, APValue::LValueBase Base,
298                   unsigned NewLength) {
299       if (Invalid)
300         return;
301 
302       assert(Base && "cannot truncate path for null pointer");
303       assert(NewLength <= Entries.size() && "not a truncation");
304 
305       if (NewLength == Entries.size())
306         return;
307       Entries.resize(NewLength);
308 
309       bool IsArray = false;
310       bool FirstIsUnsizedArray = false;
311       MostDerivedPathLength = findMostDerivedSubobject(
312           Ctx, Base, Entries, MostDerivedArraySize, MostDerivedType, IsArray,
313           FirstIsUnsizedArray);
314       MostDerivedIsArrayElement = IsArray;
315       FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
316     }
317 
318     void setInvalid() {
319       Invalid = true;
320       Entries.clear();
321     }
322 
323     /// Determine whether the most derived subobject is an array without a
324     /// known bound.
325     bool isMostDerivedAnUnsizedArray() const {
326       assert(!Invalid && "Calling this makes no sense on invalid designators");
327       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
328     }
329 
330     /// Determine what the most derived array's size is. Results in an assertion
331     /// failure if the most derived array lacks a size.
332     uint64_t getMostDerivedArraySize() const {
333       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
334       return MostDerivedArraySize;
335     }
336 
337     /// Determine whether this is a one-past-the-end pointer.
338     bool isOnePastTheEnd() const {
339       assert(!Invalid);
340       if (IsOnePastTheEnd)
341         return true;
342       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
343           Entries[MostDerivedPathLength - 1].getAsArrayIndex() ==
344               MostDerivedArraySize)
345         return true;
346       return false;
347     }
348 
349     /// Get the range of valid index adjustments in the form
350     ///   {maximum value that can be subtracted from this pointer,
351     ///    maximum value that can be added to this pointer}
352     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
353       if (Invalid || isMostDerivedAnUnsizedArray())
354         return {0, 0};
355 
356       // [expr.add]p4: For the purposes of these operators, a pointer to a
357       // nonarray object behaves the same as a pointer to the first element of
358       // an array of length one with the type of the object as its element type.
359       bool IsArray = MostDerivedPathLength == Entries.size() &&
360                      MostDerivedIsArrayElement;
361       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
362                                     : (uint64_t)IsOnePastTheEnd;
363       uint64_t ArraySize =
364           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
365       return {ArrayIndex, ArraySize - ArrayIndex};
366     }
367 
368     /// Check that this refers to a valid subobject.
369     bool isValidSubobject() const {
370       if (Invalid)
371         return false;
372       return !isOnePastTheEnd();
373     }
374     /// Check that this refers to a valid subobject, and if not, produce a
375     /// relevant diagnostic and set the designator as invalid.
376     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
377 
378     /// Get the type of the designated object.
379     QualType getType(ASTContext &Ctx) const {
380       assert(!Invalid && "invalid designator has no subobject type");
381       return MostDerivedPathLength == Entries.size()
382                  ? MostDerivedType
383                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
384     }
385 
386     /// Update this designator to refer to the first element within this array.
387     void addArrayUnchecked(const ConstantArrayType *CAT) {
388       Entries.push_back(PathEntry::ArrayIndex(0));
389 
390       // This is a most-derived object.
391       MostDerivedType = CAT->getElementType();
392       MostDerivedIsArrayElement = true;
393       MostDerivedArraySize = CAT->getSize().getZExtValue();
394       MostDerivedPathLength = Entries.size();
395     }
396     /// Update this designator to refer to the first element within the array of
397     /// elements of type T. This is an array of unknown size.
398     void addUnsizedArrayUnchecked(QualType ElemTy) {
399       Entries.push_back(PathEntry::ArrayIndex(0));
400 
401       MostDerivedType = ElemTy;
402       MostDerivedIsArrayElement = true;
403       // The value in MostDerivedArraySize is undefined in this case. So, set it
404       // to an arbitrary value that's likely to loudly break things if it's
405       // used.
406       MostDerivedArraySize = AssumedSizeForUnsizedArray;
407       MostDerivedPathLength = Entries.size();
408     }
409     /// Update this designator to refer to the given base or member of this
410     /// object.
411     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
412       Entries.push_back(APValue::BaseOrMemberType(D, Virtual));
413 
414       // If this isn't a base class, it's a new most-derived object.
415       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
416         MostDerivedType = FD->getType();
417         MostDerivedIsArrayElement = false;
418         MostDerivedArraySize = 0;
419         MostDerivedPathLength = Entries.size();
420       }
421     }
422     /// Update this designator to refer to the given complex component.
423     void addComplexUnchecked(QualType EltTy, bool Imag) {
424       Entries.push_back(PathEntry::ArrayIndex(Imag));
425 
426       // This is technically a most-derived object, though in practice this
427       // is unlikely to matter.
428       MostDerivedType = EltTy;
429       MostDerivedIsArrayElement = true;
430       MostDerivedArraySize = 2;
431       MostDerivedPathLength = Entries.size();
432     }
433     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
434     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
435                                    const APSInt &N);
436     /// Add N to the address of this subobject.
437     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
438       if (Invalid || !N) return;
439       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
440       if (isMostDerivedAnUnsizedArray()) {
441         diagnoseUnsizedArrayPointerArithmetic(Info, E);
442         // Can't verify -- trust that the user is doing the right thing (or if
443         // not, trust that the caller will catch the bad behavior).
444         // FIXME: Should we reject if this overflows, at least?
445         Entries.back() = PathEntry::ArrayIndex(
446             Entries.back().getAsArrayIndex() + TruncatedN);
447         return;
448       }
449 
450       // [expr.add]p4: For the purposes of these operators, a pointer to a
451       // nonarray object behaves the same as a pointer to the first element of
452       // an array of length one with the type of the object as its element type.
453       bool IsArray = MostDerivedPathLength == Entries.size() &&
454                      MostDerivedIsArrayElement;
455       uint64_t ArrayIndex = IsArray ? Entries.back().getAsArrayIndex()
456                                     : (uint64_t)IsOnePastTheEnd;
457       uint64_t ArraySize =
458           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
459 
460       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
461         // Calculate the actual index in a wide enough type, so we can include
462         // it in the note.
463         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
464         (llvm::APInt&)N += ArrayIndex;
465         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
466         diagnosePointerArithmetic(Info, E, N);
467         setInvalid();
468         return;
469       }
470 
471       ArrayIndex += TruncatedN;
472       assert(ArrayIndex <= ArraySize &&
473              "bounds check succeeded for out-of-bounds index");
474 
475       if (IsArray)
476         Entries.back() = PathEntry::ArrayIndex(ArrayIndex);
477       else
478         IsOnePastTheEnd = (ArrayIndex != 0);
479     }
480   };
481 
482   /// A stack frame in the constexpr call stack.
483   struct CallStackFrame {
484     EvalInfo &Info;
485 
486     /// Parent - The caller of this stack frame.
487     CallStackFrame *Caller;
488 
489     /// Callee - The function which was called.
490     const FunctionDecl *Callee;
491 
492     /// This - The binding for the this pointer in this call, if any.
493     const LValue *This;
494 
495     /// Arguments - Parameter bindings for this function call, indexed by
496     /// parameters' function scope indices.
497     APValue *Arguments;
498 
499     /// Source location information about the default argument or default
500     /// initializer expression we're evaluating, if any.
501     CurrentSourceLocExprScope CurSourceLocExprScope;
502 
503     // Note that we intentionally use std::map here so that references to
504     // values are stable.
505     typedef std::pair<const void *, unsigned> MapKeyTy;
506     typedef std::map<MapKeyTy, APValue> MapTy;
507     /// Temporaries - Temporary lvalues materialized within this stack frame.
508     MapTy Temporaries;
509 
510     /// CallLoc - The location of the call expression for this call.
511     SourceLocation CallLoc;
512 
513     /// Index - The call index of this call.
514     unsigned Index;
515 
516     /// The stack of integers for tracking version numbers for temporaries.
517     SmallVector<unsigned, 2> TempVersionStack = {1};
518     unsigned CurTempVersion = TempVersionStack.back();
519 
520     unsigned getTempVersion() const { return TempVersionStack.back(); }
521 
522     void pushTempVersion() {
523       TempVersionStack.push_back(++CurTempVersion);
524     }
525 
526     void popTempVersion() {
527       TempVersionStack.pop_back();
528     }
529 
530     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
531     // on the overall stack usage of deeply-recursing constexpr evaluations.
532     // (We should cache this map rather than recomputing it repeatedly.)
533     // But let's try this and see how it goes; we can look into caching the map
534     // as a later change.
535 
536     /// LambdaCaptureFields - Mapping from captured variables/this to
537     /// corresponding data members in the closure class.
538     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
539     FieldDecl *LambdaThisCaptureField;
540 
541     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
542                    const FunctionDecl *Callee, const LValue *This,
543                    APValue *Arguments);
544     ~CallStackFrame();
545 
546     // Return the temporary for Key whose version number is Version.
547     APValue *getTemporary(const void *Key, unsigned Version) {
548       MapKeyTy KV(Key, Version);
549       auto LB = Temporaries.lower_bound(KV);
550       if (LB != Temporaries.end() && LB->first == KV)
551         return &LB->second;
552       // Pair (Key,Version) wasn't found in the map. Check that no elements
553       // in the map have 'Key' as their key.
554       assert((LB == Temporaries.end() || LB->first.first != Key) &&
555              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
556              "Element with key 'Key' found in map");
557       return nullptr;
558     }
559 
560     // Return the current temporary for Key in the map.
561     APValue *getCurrentTemporary(const void *Key) {
562       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
563       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
564         return &std::prev(UB)->second;
565       return nullptr;
566     }
567 
568     // Return the version number of the current temporary for Key.
569     unsigned getCurrentTemporaryVersion(const void *Key) const {
570       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
571       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
572         return std::prev(UB)->first.second;
573       return 0;
574     }
575 
576     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
577   };
578 
579   /// Temporarily override 'this'.
580   class ThisOverrideRAII {
581   public:
582     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
583         : Frame(Frame), OldThis(Frame.This) {
584       if (Enable)
585         Frame.This = NewThis;
586     }
587     ~ThisOverrideRAII() {
588       Frame.This = OldThis;
589     }
590   private:
591     CallStackFrame &Frame;
592     const LValue *OldThis;
593   };
594 
595   /// A partial diagnostic which we might know in advance that we are not going
596   /// to emit.
597   class OptionalDiagnostic {
598     PartialDiagnostic *Diag;
599 
600   public:
601     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
602       : Diag(Diag) {}
603 
604     template<typename T>
605     OptionalDiagnostic &operator<<(const T &v) {
606       if (Diag)
607         *Diag << v;
608       return *this;
609     }
610 
611     OptionalDiagnostic &operator<<(const APSInt &I) {
612       if (Diag) {
613         SmallVector<char, 32> Buffer;
614         I.toString(Buffer);
615         *Diag << StringRef(Buffer.data(), Buffer.size());
616       }
617       return *this;
618     }
619 
620     OptionalDiagnostic &operator<<(const APFloat &F) {
621       if (Diag) {
622         // FIXME: Force the precision of the source value down so we don't
623         // print digits which are usually useless (we don't really care here if
624         // we truncate a digit by accident in edge cases).  Ideally,
625         // APFloat::toString would automatically print the shortest
626         // representation which rounds to the correct value, but it's a bit
627         // tricky to implement.
628         unsigned precision =
629             llvm::APFloat::semanticsPrecision(F.getSemantics());
630         precision = (precision * 59 + 195) / 196;
631         SmallVector<char, 32> Buffer;
632         F.toString(Buffer, precision);
633         *Diag << StringRef(Buffer.data(), Buffer.size());
634       }
635       return *this;
636     }
637 
638     OptionalDiagnostic &operator<<(const APFixedPoint &FX) {
639       if (Diag) {
640         SmallVector<char, 32> Buffer;
641         FX.toString(Buffer);
642         *Diag << StringRef(Buffer.data(), Buffer.size());
643       }
644       return *this;
645     }
646   };
647 
648   /// A cleanup, and a flag indicating whether it is lifetime-extended.
649   class Cleanup {
650     llvm::PointerIntPair<APValue*, 1, bool> Value;
651 
652   public:
653     Cleanup(APValue *Val, bool IsLifetimeExtended)
654         : Value(Val, IsLifetimeExtended) {}
655 
656     bool isLifetimeExtended() const { return Value.getInt(); }
657     void endLifetime() {
658       *Value.getPointer() = APValue();
659     }
660   };
661 
662   /// A reference to an object whose construction we are currently evaluating.
663   struct ObjectUnderConstruction {
664     APValue::LValueBase Base;
665     ArrayRef<APValue::LValuePathEntry> Path;
666     friend bool operator==(const ObjectUnderConstruction &LHS,
667                            const ObjectUnderConstruction &RHS) {
668       return LHS.Base == RHS.Base && LHS.Path == RHS.Path;
669     }
670     friend llvm::hash_code hash_value(const ObjectUnderConstruction &Obj) {
671       return llvm::hash_combine(Obj.Base, Obj.Path);
672     }
673   };
674   enum class ConstructionPhase { None, Bases, AfterBases };
675 }
676 
677 namespace llvm {
678 template<> struct DenseMapInfo<ObjectUnderConstruction> {
679   using Base = DenseMapInfo<APValue::LValueBase>;
680   static ObjectUnderConstruction getEmptyKey() {
681     return {Base::getEmptyKey(), {}}; }
682   static ObjectUnderConstruction getTombstoneKey() {
683     return {Base::getTombstoneKey(), {}};
684   }
685   static unsigned getHashValue(const ObjectUnderConstruction &Object) {
686     return hash_value(Object);
687   }
688   static bool isEqual(const ObjectUnderConstruction &LHS,
689                       const ObjectUnderConstruction &RHS) {
690     return LHS == RHS;
691   }
692 };
693 }
694 
695 namespace {
696   /// EvalInfo - This is a private struct used by the evaluator to capture
697   /// information about a subexpression as it is folded.  It retains information
698   /// about the AST context, but also maintains information about the folded
699   /// expression.
700   ///
701   /// If an expression could be evaluated, it is still possible it is not a C
702   /// "integer constant expression" or constant expression.  If not, this struct
703   /// captures information about how and why not.
704   ///
705   /// One bit of information passed *into* the request for constant folding
706   /// indicates whether the subexpression is "evaluated" or not according to C
707   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
708   /// evaluate the expression regardless of what the RHS is, but C only allows
709   /// certain things in certain situations.
710   struct EvalInfo {
711     ASTContext &Ctx;
712 
713     /// EvalStatus - Contains information about the evaluation.
714     Expr::EvalStatus &EvalStatus;
715 
716     /// CurrentCall - The top of the constexpr call stack.
717     CallStackFrame *CurrentCall;
718 
719     /// CallStackDepth - The number of calls in the call stack right now.
720     unsigned CallStackDepth;
721 
722     /// NextCallIndex - The next call index to assign.
723     unsigned NextCallIndex;
724 
725     /// StepsLeft - The remaining number of evaluation steps we're permitted
726     /// to perform. This is essentially a limit for the number of statements
727     /// we will evaluate.
728     unsigned StepsLeft;
729 
730     /// BottomFrame - The frame in which evaluation started. This must be
731     /// initialized after CurrentCall and CallStackDepth.
732     CallStackFrame BottomFrame;
733 
734     /// A stack of values whose lifetimes end at the end of some surrounding
735     /// evaluation frame.
736     llvm::SmallVector<Cleanup, 16> CleanupStack;
737 
738     /// EvaluatingDecl - This is the declaration whose initializer is being
739     /// evaluated, if any.
740     APValue::LValueBase EvaluatingDecl;
741 
742     /// EvaluatingDeclValue - This is the value being constructed for the
743     /// declaration whose initializer is being evaluated, if any.
744     APValue *EvaluatingDeclValue;
745 
746     /// Set of objects that are currently being constructed.
747     llvm::DenseMap<ObjectUnderConstruction, ConstructionPhase>
748         ObjectsUnderConstruction;
749 
750     struct EvaluatingConstructorRAII {
751       EvalInfo &EI;
752       ObjectUnderConstruction Object;
753       bool DidInsert;
754       EvaluatingConstructorRAII(EvalInfo &EI, ObjectUnderConstruction Object,
755                                 bool HasBases)
756           : EI(EI), Object(Object) {
757         DidInsert =
758             EI.ObjectsUnderConstruction
759                 .insert({Object, HasBases ? ConstructionPhase::Bases
760                                           : ConstructionPhase::AfterBases})
761                 .second;
762       }
763       void finishedConstructingBases() {
764         EI.ObjectsUnderConstruction[Object] = ConstructionPhase::AfterBases;
765       }
766       ~EvaluatingConstructorRAII() {
767         if (DidInsert) EI.ObjectsUnderConstruction.erase(Object);
768       }
769     };
770 
771     ConstructionPhase
772     isEvaluatingConstructor(APValue::LValueBase Base,
773                             ArrayRef<APValue::LValuePathEntry> Path) {
774       return ObjectsUnderConstruction.lookup({Base, Path});
775     }
776 
777     /// If we're currently speculatively evaluating, the outermost call stack
778     /// depth at which we can mutate state, otherwise 0.
779     unsigned SpeculativeEvaluationDepth = 0;
780 
781     /// The current array initialization index, if we're performing array
782     /// initialization.
783     uint64_t ArrayInitIndex = -1;
784 
785     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
786     /// notes attached to it will also be stored, otherwise they will not be.
787     bool HasActiveDiagnostic;
788 
789     /// Have we emitted a diagnostic explaining why we couldn't constant
790     /// fold (not just why it's not strictly a constant expression)?
791     bool HasFoldFailureDiagnostic;
792 
793     /// Whether or not we're in a context where the front end requires a
794     /// constant value.
795     bool InConstantContext;
796 
797     /// Whether we're checking that an expression is a potential constant
798     /// expression. If so, do not fail on constructs that could become constant
799     /// later on (such as a use of an undefined global).
800     bool CheckingPotentialConstantExpression = false;
801 
802     /// Whether we're checking for an expression that has undefined behavior.
803     /// If so, we will produce warnings if we encounter an operation that is
804     /// always undefined.
805     bool CheckingForUndefinedBehavior = false;
806 
807     enum EvaluationMode {
808       /// Evaluate as a constant expression. Stop if we find that the expression
809       /// is not a constant expression.
810       EM_ConstantExpression,
811 
812       /// Evaluate as a constant expression. Stop if we find that the expression
813       /// is not a constant expression. Some expressions can be retried in the
814       /// optimizer if we don't constant fold them here, but in an unevaluated
815       /// context we try to fold them immediately since the optimizer never
816       /// gets a chance to look at it.
817       EM_ConstantExpressionUnevaluated,
818 
819       /// Fold the expression to a constant. Stop if we hit a side-effect that
820       /// we can't model.
821       EM_ConstantFold,
822 
823       /// Evaluate in any way we know how. Don't worry about side-effects that
824       /// can't be modeled.
825       EM_IgnoreSideEffects,
826     } EvalMode;
827 
828     /// Are we checking whether the expression is a potential constant
829     /// expression?
830     bool checkingPotentialConstantExpression() const {
831       return CheckingPotentialConstantExpression;
832     }
833 
834     /// Are we checking an expression for overflow?
835     // FIXME: We should check for any kind of undefined or suspicious behavior
836     // in such constructs, not just overflow.
837     bool checkingForUndefinedBehavior() { return CheckingForUndefinedBehavior; }
838 
839     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
840       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
841         CallStackDepth(0), NextCallIndex(1),
842         StepsLeft(getLangOpts().ConstexprStepLimit),
843         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
844         EvaluatingDecl((const ValueDecl *)nullptr),
845         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
846         HasFoldFailureDiagnostic(false),
847         InConstantContext(false), EvalMode(Mode) {}
848 
849     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
850       EvaluatingDecl = Base;
851       EvaluatingDeclValue = &Value;
852     }
853 
854     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
855 
856     bool CheckCallLimit(SourceLocation Loc) {
857       // Don't perform any constexpr calls (other than the call we're checking)
858       // when checking a potential constant expression.
859       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
860         return false;
861       if (NextCallIndex == 0) {
862         // NextCallIndex has wrapped around.
863         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
864         return false;
865       }
866       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
867         return true;
868       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
869         << getLangOpts().ConstexprCallDepth;
870       return false;
871     }
872 
873     std::pair<CallStackFrame *, unsigned>
874     getCallFrameAndDepth(unsigned CallIndex) {
875       assert(CallIndex && "no call index in getCallFrameAndDepth");
876       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
877       // be null in this loop.
878       unsigned Depth = CallStackDepth;
879       CallStackFrame *Frame = CurrentCall;
880       while (Frame->Index > CallIndex) {
881         Frame = Frame->Caller;
882         --Depth;
883       }
884       if (Frame->Index == CallIndex)
885         return {Frame, Depth};
886       return {nullptr, 0};
887     }
888 
889     bool nextStep(const Stmt *S) {
890       if (!StepsLeft) {
891         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
892         return false;
893       }
894       --StepsLeft;
895       return true;
896     }
897 
898   private:
899     /// Add a diagnostic to the diagnostics list.
900     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
901       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
902       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
903       return EvalStatus.Diag->back().second;
904     }
905 
906     /// Add notes containing a call stack to the current point of evaluation.
907     void addCallStack(unsigned Limit);
908 
909   private:
910     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
911                             unsigned ExtraNotes, bool IsCCEDiag) {
912 
913       if (EvalStatus.Diag) {
914         // If we have a prior diagnostic, it will be noting that the expression
915         // isn't a constant expression. This diagnostic is more important,
916         // unless we require this evaluation to produce a constant expression.
917         //
918         // FIXME: We might want to show both diagnostics to the user in
919         // EM_ConstantFold mode.
920         if (!EvalStatus.Diag->empty()) {
921           switch (EvalMode) {
922           case EM_ConstantFold:
923           case EM_IgnoreSideEffects:
924             if (!HasFoldFailureDiagnostic)
925               break;
926             // We've already failed to fold something. Keep that diagnostic.
927             LLVM_FALLTHROUGH;
928           case EM_ConstantExpression:
929           case EM_ConstantExpressionUnevaluated:
930             HasActiveDiagnostic = false;
931             return OptionalDiagnostic();
932           }
933         }
934 
935         unsigned CallStackNotes = CallStackDepth - 1;
936         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
937         if (Limit)
938           CallStackNotes = std::min(CallStackNotes, Limit + 1);
939         if (checkingPotentialConstantExpression())
940           CallStackNotes = 0;
941 
942         HasActiveDiagnostic = true;
943         HasFoldFailureDiagnostic = !IsCCEDiag;
944         EvalStatus.Diag->clear();
945         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
946         addDiag(Loc, DiagId);
947         if (!checkingPotentialConstantExpression())
948           addCallStack(Limit);
949         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
950       }
951       HasActiveDiagnostic = false;
952       return OptionalDiagnostic();
953     }
954   public:
955     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
956     OptionalDiagnostic
957     FFDiag(SourceLocation Loc,
958           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
959           unsigned ExtraNotes = 0) {
960       return Diag(Loc, DiagId, ExtraNotes, false);
961     }
962 
963     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
964                               = diag::note_invalid_subexpr_in_const_expr,
965                             unsigned ExtraNotes = 0) {
966       if (EvalStatus.Diag)
967         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
968       HasActiveDiagnostic = false;
969       return OptionalDiagnostic();
970     }
971 
972     /// Diagnose that the evaluation does not produce a C++11 core constant
973     /// expression.
974     ///
975     /// FIXME: Stop evaluating if we're in EM_ConstantExpression mode
976     /// and we produce one of these.
977     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
978                                  = diag::note_invalid_subexpr_in_const_expr,
979                                unsigned ExtraNotes = 0) {
980       // Don't override a previous diagnostic. Don't bother collecting
981       // diagnostics if we're evaluating for overflow.
982       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
983         HasActiveDiagnostic = false;
984         return OptionalDiagnostic();
985       }
986       return Diag(Loc, DiagId, ExtraNotes, true);
987     }
988     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
989                                  = diag::note_invalid_subexpr_in_const_expr,
990                                unsigned ExtraNotes = 0) {
991       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
992     }
993     /// Add a note to a prior diagnostic.
994     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
995       if (!HasActiveDiagnostic)
996         return OptionalDiagnostic();
997       return OptionalDiagnostic(&addDiag(Loc, DiagId));
998     }
999 
1000     /// Add a stack of notes to a prior diagnostic.
1001     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
1002       if (HasActiveDiagnostic) {
1003         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
1004                                 Diags.begin(), Diags.end());
1005       }
1006     }
1007 
1008     /// Should we continue evaluation after encountering a side-effect that we
1009     /// couldn't model?
1010     bool keepEvaluatingAfterSideEffect() {
1011       switch (EvalMode) {
1012       case EM_IgnoreSideEffects:
1013         return true;
1014 
1015       case EM_ConstantExpression:
1016       case EM_ConstantExpressionUnevaluated:
1017       case EM_ConstantFold:
1018         // By default, assume any side effect might be valid in some other
1019         // evaluation of this expression from a different context.
1020         return checkingPotentialConstantExpression() ||
1021                checkingForUndefinedBehavior();
1022       }
1023       llvm_unreachable("Missed EvalMode case");
1024     }
1025 
1026     /// Note that we have had a side-effect, and determine whether we should
1027     /// keep evaluating.
1028     bool noteSideEffect() {
1029       EvalStatus.HasSideEffects = true;
1030       return keepEvaluatingAfterSideEffect();
1031     }
1032 
1033     /// Should we continue evaluation after encountering undefined behavior?
1034     bool keepEvaluatingAfterUndefinedBehavior() {
1035       switch (EvalMode) {
1036       case EM_IgnoreSideEffects:
1037       case EM_ConstantFold:
1038         return true;
1039 
1040       case EM_ConstantExpression:
1041       case EM_ConstantExpressionUnevaluated:
1042         return checkingForUndefinedBehavior();
1043       }
1044       llvm_unreachable("Missed EvalMode case");
1045     }
1046 
1047     /// Note that we hit something that was technically undefined behavior, but
1048     /// that we can evaluate past it (such as signed overflow or floating-point
1049     /// division by zero.)
1050     bool noteUndefinedBehavior() {
1051       EvalStatus.HasUndefinedBehavior = true;
1052       return keepEvaluatingAfterUndefinedBehavior();
1053     }
1054 
1055     /// Should we continue evaluation as much as possible after encountering a
1056     /// construct which can't be reduced to a value?
1057     bool keepEvaluatingAfterFailure() {
1058       if (!StepsLeft)
1059         return false;
1060 
1061       switch (EvalMode) {
1062       case EM_ConstantExpression:
1063       case EM_ConstantExpressionUnevaluated:
1064       case EM_ConstantFold:
1065       case EM_IgnoreSideEffects:
1066         return checkingPotentialConstantExpression() ||
1067                checkingForUndefinedBehavior();
1068       }
1069       llvm_unreachable("Missed EvalMode case");
1070     }
1071 
1072     /// Notes that we failed to evaluate an expression that other expressions
1073     /// directly depend on, and determine if we should keep evaluating. This
1074     /// should only be called if we actually intend to keep evaluating.
1075     ///
1076     /// Call noteSideEffect() instead if we may be able to ignore the value that
1077     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1078     ///
1079     /// (Foo(), 1)      // use noteSideEffect
1080     /// (Foo() || true) // use noteSideEffect
1081     /// Foo() + 1       // use noteFailure
1082     LLVM_NODISCARD bool noteFailure() {
1083       // Failure when evaluating some expression often means there is some
1084       // subexpression whose evaluation was skipped. Therefore, (because we
1085       // don't track whether we skipped an expression when unwinding after an
1086       // evaluation failure) every evaluation failure that bubbles up from a
1087       // subexpression implies that a side-effect has potentially happened. We
1088       // skip setting the HasSideEffects flag to true until we decide to
1089       // continue evaluating after that point, which happens here.
1090       bool KeepGoing = keepEvaluatingAfterFailure();
1091       EvalStatus.HasSideEffects |= KeepGoing;
1092       return KeepGoing;
1093     }
1094 
1095     class ArrayInitLoopIndex {
1096       EvalInfo &Info;
1097       uint64_t OuterIndex;
1098 
1099     public:
1100       ArrayInitLoopIndex(EvalInfo &Info)
1101           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1102         Info.ArrayInitIndex = 0;
1103       }
1104       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1105 
1106       operator uint64_t&() { return Info.ArrayInitIndex; }
1107     };
1108   };
1109 
1110   /// Object used to treat all foldable expressions as constant expressions.
1111   struct FoldConstant {
1112     EvalInfo &Info;
1113     bool Enabled;
1114     bool HadNoPriorDiags;
1115     EvalInfo::EvaluationMode OldMode;
1116 
1117     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1118       : Info(Info),
1119         Enabled(Enabled),
1120         HadNoPriorDiags(Info.EvalStatus.Diag &&
1121                         Info.EvalStatus.Diag->empty() &&
1122                         !Info.EvalStatus.HasSideEffects),
1123         OldMode(Info.EvalMode) {
1124       if (Enabled)
1125         Info.EvalMode = EvalInfo::EM_ConstantFold;
1126     }
1127     void keepDiagnostics() { Enabled = false; }
1128     ~FoldConstant() {
1129       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1130           !Info.EvalStatus.HasSideEffects)
1131         Info.EvalStatus.Diag->clear();
1132       Info.EvalMode = OldMode;
1133     }
1134   };
1135 
1136   /// RAII object used to set the current evaluation mode to ignore
1137   /// side-effects.
1138   struct IgnoreSideEffectsRAII {
1139     EvalInfo &Info;
1140     EvalInfo::EvaluationMode OldMode;
1141     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1142         : Info(Info), OldMode(Info.EvalMode) {
1143       Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1144     }
1145 
1146     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1147   };
1148 
1149   /// RAII object used to optionally suppress diagnostics and side-effects from
1150   /// a speculative evaluation.
1151   class SpeculativeEvaluationRAII {
1152     EvalInfo *Info = nullptr;
1153     Expr::EvalStatus OldStatus;
1154     unsigned OldSpeculativeEvaluationDepth;
1155 
1156     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1157       Info = Other.Info;
1158       OldStatus = Other.OldStatus;
1159       OldSpeculativeEvaluationDepth = Other.OldSpeculativeEvaluationDepth;
1160       Other.Info = nullptr;
1161     }
1162 
1163     void maybeRestoreState() {
1164       if (!Info)
1165         return;
1166 
1167       Info->EvalStatus = OldStatus;
1168       Info->SpeculativeEvaluationDepth = OldSpeculativeEvaluationDepth;
1169     }
1170 
1171   public:
1172     SpeculativeEvaluationRAII() = default;
1173 
1174     SpeculativeEvaluationRAII(
1175         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1176         : Info(&Info), OldStatus(Info.EvalStatus),
1177           OldSpeculativeEvaluationDepth(Info.SpeculativeEvaluationDepth) {
1178       Info.EvalStatus.Diag = NewDiag;
1179       Info.SpeculativeEvaluationDepth = Info.CallStackDepth + 1;
1180     }
1181 
1182     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1183     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1184       moveFromAndCancel(std::move(Other));
1185     }
1186 
1187     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1188       maybeRestoreState();
1189       moveFromAndCancel(std::move(Other));
1190       return *this;
1191     }
1192 
1193     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1194   };
1195 
1196   /// RAII object wrapping a full-expression or block scope, and handling
1197   /// the ending of the lifetime of temporaries created within it.
1198   template<bool IsFullExpression>
1199   class ScopeRAII {
1200     EvalInfo &Info;
1201     unsigned OldStackSize;
1202   public:
1203     ScopeRAII(EvalInfo &Info)
1204         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1205       // Push a new temporary version. This is needed to distinguish between
1206       // temporaries created in different iterations of a loop.
1207       Info.CurrentCall->pushTempVersion();
1208     }
1209     ~ScopeRAII() {
1210       // Body moved to a static method to encourage the compiler to inline away
1211       // instances of this class.
1212       cleanup(Info, OldStackSize);
1213       Info.CurrentCall->popTempVersion();
1214     }
1215   private:
1216     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1217       unsigned NewEnd = OldStackSize;
1218       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1219            I != N; ++I) {
1220         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1221           // Full-expression cleanup of a lifetime-extended temporary: nothing
1222           // to do, just move this cleanup to the right place in the stack.
1223           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1224           ++NewEnd;
1225         } else {
1226           // End the lifetime of the object.
1227           Info.CleanupStack[I].endLifetime();
1228         }
1229       }
1230       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1231                               Info.CleanupStack.end());
1232     }
1233   };
1234   typedef ScopeRAII<false> BlockScopeRAII;
1235   typedef ScopeRAII<true> FullExpressionRAII;
1236 }
1237 
1238 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1239                                          CheckSubobjectKind CSK) {
1240   if (Invalid)
1241     return false;
1242   if (isOnePastTheEnd()) {
1243     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1244       << CSK;
1245     setInvalid();
1246     return false;
1247   }
1248   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1249   // must actually be at least one array element; even a VLA cannot have a
1250   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1251   return true;
1252 }
1253 
1254 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1255                                                                 const Expr *E) {
1256   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1257   // Do not set the designator as invalid: we can represent this situation,
1258   // and correct handling of __builtin_object_size requires us to do so.
1259 }
1260 
1261 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1262                                                     const Expr *E,
1263                                                     const APSInt &N) {
1264   // If we're complaining, we must be able to statically determine the size of
1265   // the most derived array.
1266   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1267     Info.CCEDiag(E, diag::note_constexpr_array_index)
1268       << N << /*array*/ 0
1269       << static_cast<unsigned>(getMostDerivedArraySize());
1270   else
1271     Info.CCEDiag(E, diag::note_constexpr_array_index)
1272       << N << /*non-array*/ 1;
1273   setInvalid();
1274 }
1275 
1276 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1277                                const FunctionDecl *Callee, const LValue *This,
1278                                APValue *Arguments)
1279     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1280       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1281   Info.CurrentCall = this;
1282   ++Info.CallStackDepth;
1283 }
1284 
1285 CallStackFrame::~CallStackFrame() {
1286   assert(Info.CurrentCall == this && "calls retired out of order");
1287   --Info.CallStackDepth;
1288   Info.CurrentCall = Caller;
1289 }
1290 
1291 APValue &CallStackFrame::createTemporary(const void *Key,
1292                                          bool IsLifetimeExtended) {
1293   unsigned Version = Info.CurrentCall->getTempVersion();
1294   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1295   assert(Result.isAbsent() && "temporary created multiple times");
1296   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1297   return Result;
1298 }
1299 
1300 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1301 
1302 void EvalInfo::addCallStack(unsigned Limit) {
1303   // Determine which calls to skip, if any.
1304   unsigned ActiveCalls = CallStackDepth - 1;
1305   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1306   if (Limit && Limit < ActiveCalls) {
1307     SkipStart = Limit / 2 + Limit % 2;
1308     SkipEnd = ActiveCalls - Limit / 2;
1309   }
1310 
1311   // Walk the call stack and add the diagnostics.
1312   unsigned CallIdx = 0;
1313   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1314        Frame = Frame->Caller, ++CallIdx) {
1315     // Skip this call?
1316     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1317       if (CallIdx == SkipStart) {
1318         // Note that we're skipping calls.
1319         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1320           << unsigned(ActiveCalls - Limit);
1321       }
1322       continue;
1323     }
1324 
1325     // Use a different note for an inheriting constructor, because from the
1326     // user's perspective it's not really a function at all.
1327     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1328       if (CD->isInheritingConstructor()) {
1329         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1330           << CD->getParent();
1331         continue;
1332       }
1333     }
1334 
1335     SmallVector<char, 128> Buffer;
1336     llvm::raw_svector_ostream Out(Buffer);
1337     describeCall(Frame, Out);
1338     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1339   }
1340 }
1341 
1342 /// Kinds of access we can perform on an object, for diagnostics. Note that
1343 /// we consider a member function call to be a kind of access, even though
1344 /// it is not formally an access of the object, because it has (largely) the
1345 /// same set of semantic restrictions.
1346 enum AccessKinds {
1347   AK_Read,
1348   AK_Assign,
1349   AK_Increment,
1350   AK_Decrement,
1351   AK_MemberCall,
1352   AK_DynamicCast,
1353   AK_TypeId,
1354 };
1355 
1356 static bool isModification(AccessKinds AK) {
1357   switch (AK) {
1358   case AK_Read:
1359   case AK_MemberCall:
1360   case AK_DynamicCast:
1361   case AK_TypeId:
1362     return false;
1363   case AK_Assign:
1364   case AK_Increment:
1365   case AK_Decrement:
1366     return true;
1367   }
1368   llvm_unreachable("unknown access kind");
1369 }
1370 
1371 /// Is this an access per the C++ definition?
1372 static bool isFormalAccess(AccessKinds AK) {
1373   return AK == AK_Read || isModification(AK);
1374 }
1375 
1376 namespace {
1377   struct ComplexValue {
1378   private:
1379     bool IsInt;
1380 
1381   public:
1382     APSInt IntReal, IntImag;
1383     APFloat FloatReal, FloatImag;
1384 
1385     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1386 
1387     void makeComplexFloat() { IsInt = false; }
1388     bool isComplexFloat() const { return !IsInt; }
1389     APFloat &getComplexFloatReal() { return FloatReal; }
1390     APFloat &getComplexFloatImag() { return FloatImag; }
1391 
1392     void makeComplexInt() { IsInt = true; }
1393     bool isComplexInt() const { return IsInt; }
1394     APSInt &getComplexIntReal() { return IntReal; }
1395     APSInt &getComplexIntImag() { return IntImag; }
1396 
1397     void moveInto(APValue &v) const {
1398       if (isComplexFloat())
1399         v = APValue(FloatReal, FloatImag);
1400       else
1401         v = APValue(IntReal, IntImag);
1402     }
1403     void setFrom(const APValue &v) {
1404       assert(v.isComplexFloat() || v.isComplexInt());
1405       if (v.isComplexFloat()) {
1406         makeComplexFloat();
1407         FloatReal = v.getComplexFloatReal();
1408         FloatImag = v.getComplexFloatImag();
1409       } else {
1410         makeComplexInt();
1411         IntReal = v.getComplexIntReal();
1412         IntImag = v.getComplexIntImag();
1413       }
1414     }
1415   };
1416 
1417   struct LValue {
1418     APValue::LValueBase Base;
1419     CharUnits Offset;
1420     SubobjectDesignator Designator;
1421     bool IsNullPtr : 1;
1422     bool InvalidBase : 1;
1423 
1424     const APValue::LValueBase getLValueBase() const { return Base; }
1425     CharUnits &getLValueOffset() { return Offset; }
1426     const CharUnits &getLValueOffset() const { return Offset; }
1427     SubobjectDesignator &getLValueDesignator() { return Designator; }
1428     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1429     bool isNullPointer() const { return IsNullPtr;}
1430 
1431     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1432     unsigned getLValueVersion() const { return Base.getVersion(); }
1433 
1434     void moveInto(APValue &V) const {
1435       if (Designator.Invalid)
1436         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1437       else {
1438         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1439         V = APValue(Base, Offset, Designator.Entries,
1440                     Designator.IsOnePastTheEnd, IsNullPtr);
1441       }
1442     }
1443     void setFrom(ASTContext &Ctx, const APValue &V) {
1444       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1445       Base = V.getLValueBase();
1446       Offset = V.getLValueOffset();
1447       InvalidBase = false;
1448       Designator = SubobjectDesignator(Ctx, V);
1449       IsNullPtr = V.isNullPointer();
1450     }
1451 
1452     void set(APValue::LValueBase B, bool BInvalid = false) {
1453 #ifndef NDEBUG
1454       // We only allow a few types of invalid bases. Enforce that here.
1455       if (BInvalid) {
1456         const auto *E = B.get<const Expr *>();
1457         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1458                "Unexpected type of invalid base");
1459       }
1460 #endif
1461 
1462       Base = B;
1463       Offset = CharUnits::fromQuantity(0);
1464       InvalidBase = BInvalid;
1465       Designator = SubobjectDesignator(getType(B));
1466       IsNullPtr = false;
1467     }
1468 
1469     void setNull(QualType PointerTy, uint64_t TargetVal) {
1470       Base = (Expr *)nullptr;
1471       Offset = CharUnits::fromQuantity(TargetVal);
1472       InvalidBase = false;
1473       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1474       IsNullPtr = true;
1475     }
1476 
1477     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1478       set(B, true);
1479     }
1480 
1481   private:
1482     // Check that this LValue is not based on a null pointer. If it is, produce
1483     // a diagnostic and mark the designator as invalid.
1484     template <typename GenDiagType>
1485     bool checkNullPointerDiagnosingWith(const GenDiagType &GenDiag) {
1486       if (Designator.Invalid)
1487         return false;
1488       if (IsNullPtr) {
1489         GenDiag();
1490         Designator.setInvalid();
1491         return false;
1492       }
1493       return true;
1494     }
1495 
1496   public:
1497     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1498                           CheckSubobjectKind CSK) {
1499       return checkNullPointerDiagnosingWith([&Info, E, CSK] {
1500         Info.CCEDiag(E, diag::note_constexpr_null_subobject) << CSK;
1501       });
1502     }
1503 
1504     bool checkNullPointerForFoldAccess(EvalInfo &Info, const Expr *E,
1505                                        AccessKinds AK) {
1506       return checkNullPointerDiagnosingWith([&Info, E, AK] {
1507         Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
1508       });
1509     }
1510 
1511     // Check this LValue refers to an object. If not, set the designator to be
1512     // invalid and emit a diagnostic.
1513     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1514       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1515              Designator.checkSubobject(Info, E, CSK);
1516     }
1517 
1518     void addDecl(EvalInfo &Info, const Expr *E,
1519                  const Decl *D, bool Virtual = false) {
1520       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1521         Designator.addDeclUnchecked(D, Virtual);
1522     }
1523     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1524       if (!Designator.Entries.empty()) {
1525         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1526         Designator.setInvalid();
1527         return;
1528       }
1529       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1530         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1531         Designator.FirstEntryIsAnUnsizedArray = true;
1532         Designator.addUnsizedArrayUnchecked(ElemTy);
1533       }
1534     }
1535     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1536       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1537         Designator.addArrayUnchecked(CAT);
1538     }
1539     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1540       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1541         Designator.addComplexUnchecked(EltTy, Imag);
1542     }
1543     void clearIsNullPointer() {
1544       IsNullPtr = false;
1545     }
1546     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1547                               const APSInt &Index, CharUnits ElementSize) {
1548       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1549       // but we're not required to diagnose it and it's valid in C++.)
1550       if (!Index)
1551         return;
1552 
1553       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1554       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1555       // offsets.
1556       uint64_t Offset64 = Offset.getQuantity();
1557       uint64_t ElemSize64 = ElementSize.getQuantity();
1558       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1559       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1560 
1561       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1562         Designator.adjustIndex(Info, E, Index);
1563       clearIsNullPointer();
1564     }
1565     void adjustOffset(CharUnits N) {
1566       Offset += N;
1567       if (N.getQuantity())
1568         clearIsNullPointer();
1569     }
1570   };
1571 
1572   struct MemberPtr {
1573     MemberPtr() {}
1574     explicit MemberPtr(const ValueDecl *Decl) :
1575       DeclAndIsDerivedMember(Decl, false), Path() {}
1576 
1577     /// The member or (direct or indirect) field referred to by this member
1578     /// pointer, or 0 if this is a null member pointer.
1579     const ValueDecl *getDecl() const {
1580       return DeclAndIsDerivedMember.getPointer();
1581     }
1582     /// Is this actually a member of some type derived from the relevant class?
1583     bool isDerivedMember() const {
1584       return DeclAndIsDerivedMember.getInt();
1585     }
1586     /// Get the class which the declaration actually lives in.
1587     const CXXRecordDecl *getContainingRecord() const {
1588       return cast<CXXRecordDecl>(
1589           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1590     }
1591 
1592     void moveInto(APValue &V) const {
1593       V = APValue(getDecl(), isDerivedMember(), Path);
1594     }
1595     void setFrom(const APValue &V) {
1596       assert(V.isMemberPointer());
1597       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1598       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1599       Path.clear();
1600       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1601       Path.insert(Path.end(), P.begin(), P.end());
1602     }
1603 
1604     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1605     /// whether the member is a member of some class derived from the class type
1606     /// of the member pointer.
1607     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1608     /// Path - The path of base/derived classes from the member declaration's
1609     /// class (exclusive) to the class type of the member pointer (inclusive).
1610     SmallVector<const CXXRecordDecl*, 4> Path;
1611 
1612     /// Perform a cast towards the class of the Decl (either up or down the
1613     /// hierarchy).
1614     bool castBack(const CXXRecordDecl *Class) {
1615       assert(!Path.empty());
1616       const CXXRecordDecl *Expected;
1617       if (Path.size() >= 2)
1618         Expected = Path[Path.size() - 2];
1619       else
1620         Expected = getContainingRecord();
1621       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1622         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1623         // if B does not contain the original member and is not a base or
1624         // derived class of the class containing the original member, the result
1625         // of the cast is undefined.
1626         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1627         // (D::*). We consider that to be a language defect.
1628         return false;
1629       }
1630       Path.pop_back();
1631       return true;
1632     }
1633     /// Perform a base-to-derived member pointer cast.
1634     bool castToDerived(const CXXRecordDecl *Derived) {
1635       if (!getDecl())
1636         return true;
1637       if (!isDerivedMember()) {
1638         Path.push_back(Derived);
1639         return true;
1640       }
1641       if (!castBack(Derived))
1642         return false;
1643       if (Path.empty())
1644         DeclAndIsDerivedMember.setInt(false);
1645       return true;
1646     }
1647     /// Perform a derived-to-base member pointer cast.
1648     bool castToBase(const CXXRecordDecl *Base) {
1649       if (!getDecl())
1650         return true;
1651       if (Path.empty())
1652         DeclAndIsDerivedMember.setInt(true);
1653       if (isDerivedMember()) {
1654         Path.push_back(Base);
1655         return true;
1656       }
1657       return castBack(Base);
1658     }
1659   };
1660 
1661   /// Compare two member pointers, which are assumed to be of the same type.
1662   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1663     if (!LHS.getDecl() || !RHS.getDecl())
1664       return !LHS.getDecl() && !RHS.getDecl();
1665     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1666       return false;
1667     return LHS.Path == RHS.Path;
1668   }
1669 }
1670 
1671 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1672 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1673                             const LValue &This, const Expr *E,
1674                             bool AllowNonLiteralTypes = false);
1675 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1676                            bool InvalidBaseOK = false);
1677 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1678                             bool InvalidBaseOK = false);
1679 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1680                                   EvalInfo &Info);
1681 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1682 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1683 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1684                                     EvalInfo &Info);
1685 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1686 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1687 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1688                            EvalInfo &Info);
1689 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1690 
1691 /// Evaluate an integer or fixed point expression into an APResult.
1692 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
1693                                         EvalInfo &Info);
1694 
1695 /// Evaluate only a fixed point expression into an APResult.
1696 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
1697                                EvalInfo &Info);
1698 
1699 //===----------------------------------------------------------------------===//
1700 // Misc utilities
1701 //===----------------------------------------------------------------------===//
1702 
1703 /// A helper function to create a temporary and set an LValue.
1704 template <class KeyTy>
1705 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1706                                 LValue &LV, CallStackFrame &Frame) {
1707   LV.set({Key, Frame.Info.CurrentCall->Index,
1708           Frame.Info.CurrentCall->getTempVersion()});
1709   return Frame.createTemporary(Key, IsLifetimeExtended);
1710 }
1711 
1712 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1713 /// preserving its value (by extending by up to one bit as needed).
1714 static void negateAsSigned(APSInt &Int) {
1715   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1716     Int = Int.extend(Int.getBitWidth() + 1);
1717     Int.setIsSigned(true);
1718   }
1719   Int = -Int;
1720 }
1721 
1722 /// Produce a string describing the given constexpr call.
1723 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1724   unsigned ArgIndex = 0;
1725   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1726                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1727                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1728 
1729   if (!IsMemberCall)
1730     Out << *Frame->Callee << '(';
1731 
1732   if (Frame->This && IsMemberCall) {
1733     APValue Val;
1734     Frame->This->moveInto(Val);
1735     Val.printPretty(Out, Frame->Info.Ctx,
1736                     Frame->This->Designator.MostDerivedType);
1737     // FIXME: Add parens around Val if needed.
1738     Out << "->" << *Frame->Callee << '(';
1739     IsMemberCall = false;
1740   }
1741 
1742   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1743        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1744     if (ArgIndex > (unsigned)IsMemberCall)
1745       Out << ", ";
1746 
1747     const ParmVarDecl *Param = *I;
1748     const APValue &Arg = Frame->Arguments[ArgIndex];
1749     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1750 
1751     if (ArgIndex == 0 && IsMemberCall)
1752       Out << "->" << *Frame->Callee << '(';
1753   }
1754 
1755   Out << ')';
1756 }
1757 
1758 /// Evaluate an expression to see if it had side-effects, and discard its
1759 /// result.
1760 /// \return \c true if the caller should keep evaluating.
1761 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1762   APValue Scratch;
1763   if (!Evaluate(Scratch, Info, E))
1764     // We don't need the value, but we might have skipped a side effect here.
1765     return Info.noteSideEffect();
1766   return true;
1767 }
1768 
1769 /// Should this call expression be treated as a string literal?
1770 static bool IsStringLiteralCall(const CallExpr *E) {
1771   unsigned Builtin = E->getBuiltinCallee();
1772   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1773           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1774 }
1775 
1776 static bool IsGlobalLValue(APValue::LValueBase B) {
1777   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1778   // constant expression of pointer type that evaluates to...
1779 
1780   // ... a null pointer value, or a prvalue core constant expression of type
1781   // std::nullptr_t.
1782   if (!B) return true;
1783 
1784   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1785     // ... the address of an object with static storage duration,
1786     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1787       return VD->hasGlobalStorage();
1788     // ... the address of a function,
1789     return isa<FunctionDecl>(D);
1790   }
1791 
1792   if (B.is<TypeInfoLValue>())
1793     return true;
1794 
1795   const Expr *E = B.get<const Expr*>();
1796   switch (E->getStmtClass()) {
1797   default:
1798     return false;
1799   case Expr::CompoundLiteralExprClass: {
1800     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1801     return CLE->isFileScope() && CLE->isLValue();
1802   }
1803   case Expr::MaterializeTemporaryExprClass:
1804     // A materialized temporary might have been lifetime-extended to static
1805     // storage duration.
1806     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1807   // A string literal has static storage duration.
1808   case Expr::StringLiteralClass:
1809   case Expr::PredefinedExprClass:
1810   case Expr::ObjCStringLiteralClass:
1811   case Expr::ObjCEncodeExprClass:
1812   case Expr::CXXUuidofExprClass:
1813     return true;
1814   case Expr::ObjCBoxedExprClass:
1815     return cast<ObjCBoxedExpr>(E)->isExpressibleAsConstantInitializer();
1816   case Expr::CallExprClass:
1817     return IsStringLiteralCall(cast<CallExpr>(E));
1818   // For GCC compatibility, &&label has static storage duration.
1819   case Expr::AddrLabelExprClass:
1820     return true;
1821   // A Block literal expression may be used as the initialization value for
1822   // Block variables at global or local static scope.
1823   case Expr::BlockExprClass:
1824     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1825   case Expr::ImplicitValueInitExprClass:
1826     // FIXME:
1827     // We can never form an lvalue with an implicit value initialization as its
1828     // base through expression evaluation, so these only appear in one case: the
1829     // implicit variable declaration we invent when checking whether a constexpr
1830     // constructor can produce a constant expression. We must assume that such
1831     // an expression might be a global lvalue.
1832     return true;
1833   }
1834 }
1835 
1836 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1837   return LVal.Base.dyn_cast<const ValueDecl*>();
1838 }
1839 
1840 static bool IsLiteralLValue(const LValue &Value) {
1841   if (Value.getLValueCallIndex())
1842     return false;
1843   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1844   return E && !isa<MaterializeTemporaryExpr>(E);
1845 }
1846 
1847 static bool IsWeakLValue(const LValue &Value) {
1848   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1849   return Decl && Decl->isWeak();
1850 }
1851 
1852 static bool isZeroSized(const LValue &Value) {
1853   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1854   if (Decl && isa<VarDecl>(Decl)) {
1855     QualType Ty = Decl->getType();
1856     if (Ty->isArrayType())
1857       return Ty->isIncompleteType() ||
1858              Decl->getASTContext().getTypeSize(Ty) == 0;
1859   }
1860   return false;
1861 }
1862 
1863 static bool HasSameBase(const LValue &A, const LValue &B) {
1864   if (!A.getLValueBase())
1865     return !B.getLValueBase();
1866   if (!B.getLValueBase())
1867     return false;
1868 
1869   if (A.getLValueBase().getOpaqueValue() !=
1870       B.getLValueBase().getOpaqueValue()) {
1871     const Decl *ADecl = GetLValueBaseDecl(A);
1872     if (!ADecl)
1873       return false;
1874     const Decl *BDecl = GetLValueBaseDecl(B);
1875     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1876       return false;
1877   }
1878 
1879   return IsGlobalLValue(A.getLValueBase()) ||
1880          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1881           A.getLValueVersion() == B.getLValueVersion());
1882 }
1883 
1884 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1885   assert(Base && "no location for a null lvalue");
1886   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1887   if (VD)
1888     Info.Note(VD->getLocation(), diag::note_declared_at);
1889   else if (const Expr *E = Base.dyn_cast<const Expr*>())
1890     Info.Note(E->getExprLoc(), diag::note_constexpr_temporary_here);
1891   // We have no information to show for a typeid(T) object.
1892 }
1893 
1894 /// Check that this reference or pointer core constant expression is a valid
1895 /// value for an address or reference constant expression. Return true if we
1896 /// can fold this expression, whether or not it's a constant expression.
1897 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1898                                           QualType Type, const LValue &LVal,
1899                                           Expr::ConstExprUsage Usage) {
1900   bool IsReferenceType = Type->isReferenceType();
1901 
1902   APValue::LValueBase Base = LVal.getLValueBase();
1903   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1904 
1905   // Check that the object is a global. Note that the fake 'this' object we
1906   // manufacture when checking potential constant expressions is conservatively
1907   // assumed to be global here.
1908   if (!IsGlobalLValue(Base)) {
1909     if (Info.getLangOpts().CPlusPlus11) {
1910       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1911       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1912         << IsReferenceType << !Designator.Entries.empty()
1913         << !!VD << VD;
1914       NoteLValueLocation(Info, Base);
1915     } else {
1916       Info.FFDiag(Loc);
1917     }
1918     // Don't allow references to temporaries to escape.
1919     return false;
1920   }
1921   assert((Info.checkingPotentialConstantExpression() ||
1922           LVal.getLValueCallIndex() == 0) &&
1923          "have call index for global lvalue");
1924 
1925   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1926     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1927       // Check if this is a thread-local variable.
1928       if (Var->getTLSKind())
1929         return false;
1930 
1931       // A dllimport variable never acts like a constant.
1932       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1933         return false;
1934     }
1935     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1936       // __declspec(dllimport) must be handled very carefully:
1937       // We must never initialize an expression with the thunk in C++.
1938       // Doing otherwise would allow the same id-expression to yield
1939       // different addresses for the same function in different translation
1940       // units.  However, this means that we must dynamically initialize the
1941       // expression with the contents of the import address table at runtime.
1942       //
1943       // The C language has no notion of ODR; furthermore, it has no notion of
1944       // dynamic initialization.  This means that we are permitted to
1945       // perform initialization with the address of the thunk.
1946       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1947           FD->hasAttr<DLLImportAttr>())
1948         return false;
1949     }
1950   }
1951 
1952   // Allow address constant expressions to be past-the-end pointers. This is
1953   // an extension: the standard requires them to point to an object.
1954   if (!IsReferenceType)
1955     return true;
1956 
1957   // A reference constant expression must refer to an object.
1958   if (!Base) {
1959     // FIXME: diagnostic
1960     Info.CCEDiag(Loc);
1961     return true;
1962   }
1963 
1964   // Does this refer one past the end of some object?
1965   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1966     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1967     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1968       << !Designator.Entries.empty() << !!VD << VD;
1969     NoteLValueLocation(Info, Base);
1970   }
1971 
1972   return true;
1973 }
1974 
1975 /// Member pointers are constant expressions unless they point to a
1976 /// non-virtual dllimport member function.
1977 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1978                                                  SourceLocation Loc,
1979                                                  QualType Type,
1980                                                  const APValue &Value,
1981                                                  Expr::ConstExprUsage Usage) {
1982   const ValueDecl *Member = Value.getMemberPointerDecl();
1983   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1984   if (!FD)
1985     return true;
1986   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1987          !FD->hasAttr<DLLImportAttr>();
1988 }
1989 
1990 /// Check that this core constant expression is of literal type, and if not,
1991 /// produce an appropriate diagnostic.
1992 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1993                              const LValue *This = nullptr) {
1994   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1995     return true;
1996 
1997   // C++1y: A constant initializer for an object o [...] may also invoke
1998   // constexpr constructors for o and its subobjects even if those objects
1999   // are of non-literal class types.
2000   //
2001   // C++11 missed this detail for aggregates, so classes like this:
2002   //   struct foo_t { union { int i; volatile int j; } u; };
2003   // are not (obviously) initializable like so:
2004   //   __attribute__((__require_constant_initialization__))
2005   //   static const foo_t x = {{0}};
2006   // because "i" is a subobject with non-literal initialization (due to the
2007   // volatile member of the union). See:
2008   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
2009   // Therefore, we use the C++1y behavior.
2010   if (This && Info.EvaluatingDecl == This->getLValueBase())
2011     return true;
2012 
2013   // Prvalue constant expressions must be of literal types.
2014   if (Info.getLangOpts().CPlusPlus11)
2015     Info.FFDiag(E, diag::note_constexpr_nonliteral)
2016       << E->getType();
2017   else
2018     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2019   return false;
2020 }
2021 
2022 /// Check that this core constant expression value is a valid value for a
2023 /// constant expression. If not, report an appropriate diagnostic. Does not
2024 /// check that the expression is of literal type.
2025 static bool
2026 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
2027                         const APValue &Value,
2028                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen,
2029                         SourceLocation SubobjectLoc = SourceLocation()) {
2030   if (!Value.hasValue()) {
2031     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
2032       << true << Type;
2033     if (SubobjectLoc.isValid())
2034       Info.Note(SubobjectLoc, diag::note_constexpr_subobject_declared_here);
2035     return false;
2036   }
2037 
2038   // We allow _Atomic(T) to be initialized from anything that T can be
2039   // initialized from.
2040   if (const AtomicType *AT = Type->getAs<AtomicType>())
2041     Type = AT->getValueType();
2042 
2043   // Core issue 1454: For a literal constant expression of array or class type,
2044   // each subobject of its value shall have been initialized by a constant
2045   // expression.
2046   if (Value.isArray()) {
2047     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
2048     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
2049       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
2050                                    Value.getArrayInitializedElt(I), Usage,
2051                                    SubobjectLoc))
2052         return false;
2053     }
2054     if (!Value.hasArrayFiller())
2055       return true;
2056     return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
2057                                    Usage, SubobjectLoc);
2058   }
2059   if (Value.isUnion() && Value.getUnionField()) {
2060     return CheckConstantExpression(Info, DiagLoc,
2061                                    Value.getUnionField()->getType(),
2062                                    Value.getUnionValue(), Usage,
2063                                    Value.getUnionField()->getLocation());
2064   }
2065   if (Value.isStruct()) {
2066     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
2067     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
2068       unsigned BaseIndex = 0;
2069       for (const CXXBaseSpecifier &BS : CD->bases()) {
2070         if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
2071                                      Value.getStructBase(BaseIndex), Usage,
2072                                      BS.getBeginLoc()))
2073           return false;
2074         ++BaseIndex;
2075       }
2076     }
2077     for (const auto *I : RD->fields()) {
2078       if (I->isUnnamedBitfield())
2079         continue;
2080 
2081       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
2082                                    Value.getStructField(I->getFieldIndex()),
2083                                    Usage, I->getLocation()))
2084         return false;
2085     }
2086   }
2087 
2088   if (Value.isLValue()) {
2089     LValue LVal;
2090     LVal.setFrom(Info.Ctx, Value);
2091     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
2092   }
2093 
2094   if (Value.isMemberPointer())
2095     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
2096 
2097   // Everything else is fine.
2098   return true;
2099 }
2100 
2101 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
2102   // A null base expression indicates a null pointer.  These are always
2103   // evaluatable, and they are false unless the offset is zero.
2104   if (!Value.getLValueBase()) {
2105     Result = !Value.getLValueOffset().isZero();
2106     return true;
2107   }
2108 
2109   // We have a non-null base.  These are generally known to be true, but if it's
2110   // a weak declaration it can be null at runtime.
2111   Result = true;
2112   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
2113   return !Decl || !Decl->isWeak();
2114 }
2115 
2116 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
2117   switch (Val.getKind()) {
2118   case APValue::None:
2119   case APValue::Indeterminate:
2120     return false;
2121   case APValue::Int:
2122     Result = Val.getInt().getBoolValue();
2123     return true;
2124   case APValue::FixedPoint:
2125     Result = Val.getFixedPoint().getBoolValue();
2126     return true;
2127   case APValue::Float:
2128     Result = !Val.getFloat().isZero();
2129     return true;
2130   case APValue::ComplexInt:
2131     Result = Val.getComplexIntReal().getBoolValue() ||
2132              Val.getComplexIntImag().getBoolValue();
2133     return true;
2134   case APValue::ComplexFloat:
2135     Result = !Val.getComplexFloatReal().isZero() ||
2136              !Val.getComplexFloatImag().isZero();
2137     return true;
2138   case APValue::LValue:
2139     return EvalPointerValueAsBool(Val, Result);
2140   case APValue::MemberPointer:
2141     Result = Val.getMemberPointerDecl();
2142     return true;
2143   case APValue::Vector:
2144   case APValue::Array:
2145   case APValue::Struct:
2146   case APValue::Union:
2147   case APValue::AddrLabelDiff:
2148     return false;
2149   }
2150 
2151   llvm_unreachable("unknown APValue kind");
2152 }
2153 
2154 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2155                                        EvalInfo &Info) {
2156   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2157   APValue Val;
2158   if (!Evaluate(Val, Info, E))
2159     return false;
2160   return HandleConversionToBool(Val, Result);
2161 }
2162 
2163 template<typename T>
2164 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2165                            const T &SrcValue, QualType DestType) {
2166   Info.CCEDiag(E, diag::note_constexpr_overflow)
2167     << SrcValue << DestType;
2168   return Info.noteUndefinedBehavior();
2169 }
2170 
2171 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2172                                  QualType SrcType, const APFloat &Value,
2173                                  QualType DestType, APSInt &Result) {
2174   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2175   // Determine whether we are converting to unsigned or signed.
2176   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2177 
2178   Result = APSInt(DestWidth, !DestSigned);
2179   bool ignored;
2180   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2181       & APFloat::opInvalidOp)
2182     return HandleOverflow(Info, E, Value, DestType);
2183   return true;
2184 }
2185 
2186 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2187                                    QualType SrcType, QualType DestType,
2188                                    APFloat &Result) {
2189   APFloat Value = Result;
2190   bool ignored;
2191   Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2192                  APFloat::rmNearestTiesToEven, &ignored);
2193   return true;
2194 }
2195 
2196 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2197                                  QualType DestType, QualType SrcType,
2198                                  const APSInt &Value) {
2199   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2200   // Figure out if this is a truncate, extend or noop cast.
2201   // If the input is signed, do a sign extend, noop, or truncate.
2202   APSInt Result = Value.extOrTrunc(DestWidth);
2203   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2204   if (DestType->isBooleanType())
2205     Result = Value.getBoolValue();
2206   return Result;
2207 }
2208 
2209 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2210                                  QualType SrcType, const APSInt &Value,
2211                                  QualType DestType, APFloat &Result) {
2212   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2213   Result.convertFromAPInt(Value, Value.isSigned(),
2214                           APFloat::rmNearestTiesToEven);
2215   return true;
2216 }
2217 
2218 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2219                                   APValue &Value, const FieldDecl *FD) {
2220   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2221 
2222   if (!Value.isInt()) {
2223     // Trying to store a pointer-cast-to-integer into a bitfield.
2224     // FIXME: In this case, we should provide the diagnostic for casting
2225     // a pointer to an integer.
2226     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2227     Info.FFDiag(E);
2228     return false;
2229   }
2230 
2231   APSInt &Int = Value.getInt();
2232   unsigned OldBitWidth = Int.getBitWidth();
2233   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2234   if (NewBitWidth < OldBitWidth)
2235     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2236   return true;
2237 }
2238 
2239 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2240                                   llvm::APInt &Res) {
2241   APValue SVal;
2242   if (!Evaluate(SVal, Info, E))
2243     return false;
2244   if (SVal.isInt()) {
2245     Res = SVal.getInt();
2246     return true;
2247   }
2248   if (SVal.isFloat()) {
2249     Res = SVal.getFloat().bitcastToAPInt();
2250     return true;
2251   }
2252   if (SVal.isVector()) {
2253     QualType VecTy = E->getType();
2254     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2255     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2256     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2257     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2258     Res = llvm::APInt::getNullValue(VecSize);
2259     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2260       APValue &Elt = SVal.getVectorElt(i);
2261       llvm::APInt EltAsInt;
2262       if (Elt.isInt()) {
2263         EltAsInt = Elt.getInt();
2264       } else if (Elt.isFloat()) {
2265         EltAsInt = Elt.getFloat().bitcastToAPInt();
2266       } else {
2267         // Don't try to handle vectors of anything other than int or float
2268         // (not sure if it's possible to hit this case).
2269         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2270         return false;
2271       }
2272       unsigned BaseEltSize = EltAsInt.getBitWidth();
2273       if (BigEndian)
2274         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2275       else
2276         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2277     }
2278     return true;
2279   }
2280   // Give up if the input isn't an int, float, or vector.  For example, we
2281   // reject "(v4i16)(intptr_t)&a".
2282   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2283   return false;
2284 }
2285 
2286 /// Perform the given integer operation, which is known to need at most BitWidth
2287 /// bits, and check for overflow in the original type (if that type was not an
2288 /// unsigned type).
2289 template<typename Operation>
2290 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2291                                  const APSInt &LHS, const APSInt &RHS,
2292                                  unsigned BitWidth, Operation Op,
2293                                  APSInt &Result) {
2294   if (LHS.isUnsigned()) {
2295     Result = Op(LHS, RHS);
2296     return true;
2297   }
2298 
2299   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2300   Result = Value.trunc(LHS.getBitWidth());
2301   if (Result.extend(BitWidth) != Value) {
2302     if (Info.checkingForUndefinedBehavior())
2303       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2304                                        diag::warn_integer_constant_overflow)
2305           << Result.toString(10) << E->getType();
2306     else
2307       return HandleOverflow(Info, E, Value, E->getType());
2308   }
2309   return true;
2310 }
2311 
2312 /// Perform the given binary integer operation.
2313 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2314                               BinaryOperatorKind Opcode, APSInt RHS,
2315                               APSInt &Result) {
2316   switch (Opcode) {
2317   default:
2318     Info.FFDiag(E);
2319     return false;
2320   case BO_Mul:
2321     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2322                                 std::multiplies<APSInt>(), Result);
2323   case BO_Add:
2324     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2325                                 std::plus<APSInt>(), Result);
2326   case BO_Sub:
2327     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2328                                 std::minus<APSInt>(), Result);
2329   case BO_And: Result = LHS & RHS; return true;
2330   case BO_Xor: Result = LHS ^ RHS; return true;
2331   case BO_Or:  Result = LHS | RHS; return true;
2332   case BO_Div:
2333   case BO_Rem:
2334     if (RHS == 0) {
2335       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2336       return false;
2337     }
2338     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2339     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2340     // this operation and gives the two's complement result.
2341     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2342         LHS.isSigned() && LHS.isMinSignedValue())
2343       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2344                             E->getType());
2345     return true;
2346   case BO_Shl: {
2347     if (Info.getLangOpts().OpenCL)
2348       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2349       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2350                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2351                     RHS.isUnsigned());
2352     else if (RHS.isSigned() && RHS.isNegative()) {
2353       // During constant-folding, a negative shift is an opposite shift. Such
2354       // a shift is not a constant expression.
2355       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2356       RHS = -RHS;
2357       goto shift_right;
2358     }
2359   shift_left:
2360     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2361     // the shifted type.
2362     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2363     if (SA != RHS) {
2364       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2365         << RHS << E->getType() << LHS.getBitWidth();
2366     } else if (LHS.isSigned() && !Info.getLangOpts().CPlusPlus2a) {
2367       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2368       // operand, and must not overflow the corresponding unsigned type.
2369       // C++2a [expr.shift]p2: E1 << E2 is the unique value congruent to
2370       // E1 x 2^E2 module 2^N.
2371       if (LHS.isNegative())
2372         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2373       else if (LHS.countLeadingZeros() < SA)
2374         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2375     }
2376     Result = LHS << SA;
2377     return true;
2378   }
2379   case BO_Shr: {
2380     if (Info.getLangOpts().OpenCL)
2381       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2382       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2383                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2384                     RHS.isUnsigned());
2385     else if (RHS.isSigned() && RHS.isNegative()) {
2386       // During constant-folding, a negative shift is an opposite shift. Such a
2387       // shift is not a constant expression.
2388       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2389       RHS = -RHS;
2390       goto shift_left;
2391     }
2392   shift_right:
2393     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2394     // shifted type.
2395     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2396     if (SA != RHS)
2397       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2398         << RHS << E->getType() << LHS.getBitWidth();
2399     Result = LHS >> SA;
2400     return true;
2401   }
2402 
2403   case BO_LT: Result = LHS < RHS; return true;
2404   case BO_GT: Result = LHS > RHS; return true;
2405   case BO_LE: Result = LHS <= RHS; return true;
2406   case BO_GE: Result = LHS >= RHS; return true;
2407   case BO_EQ: Result = LHS == RHS; return true;
2408   case BO_NE: Result = LHS != RHS; return true;
2409   case BO_Cmp:
2410     llvm_unreachable("BO_Cmp should be handled elsewhere");
2411   }
2412 }
2413 
2414 /// Perform the given binary floating-point operation, in-place, on LHS.
2415 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2416                                   APFloat &LHS, BinaryOperatorKind Opcode,
2417                                   const APFloat &RHS) {
2418   switch (Opcode) {
2419   default:
2420     Info.FFDiag(E);
2421     return false;
2422   case BO_Mul:
2423     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2424     break;
2425   case BO_Add:
2426     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2427     break;
2428   case BO_Sub:
2429     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2430     break;
2431   case BO_Div:
2432     // [expr.mul]p4:
2433     //   If the second operand of / or % is zero the behavior is undefined.
2434     if (RHS.isZero())
2435       Info.CCEDiag(E, diag::note_expr_divide_by_zero);
2436     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2437     break;
2438   }
2439 
2440   // [expr.pre]p4:
2441   //   If during the evaluation of an expression, the result is not
2442   //   mathematically defined [...], the behavior is undefined.
2443   // FIXME: C++ rules require us to not conform to IEEE 754 here.
2444   if (LHS.isNaN()) {
2445     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2446     return Info.noteUndefinedBehavior();
2447   }
2448   return true;
2449 }
2450 
2451 /// Cast an lvalue referring to a base subobject to a derived class, by
2452 /// truncating the lvalue's path to the given length.
2453 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2454                                const RecordDecl *TruncatedType,
2455                                unsigned TruncatedElements) {
2456   SubobjectDesignator &D = Result.Designator;
2457 
2458   // Check we actually point to a derived class object.
2459   if (TruncatedElements == D.Entries.size())
2460     return true;
2461   assert(TruncatedElements >= D.MostDerivedPathLength &&
2462          "not casting to a derived class");
2463   if (!Result.checkSubobject(Info, E, CSK_Derived))
2464     return false;
2465 
2466   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2467   const RecordDecl *RD = TruncatedType;
2468   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2469     if (RD->isInvalidDecl()) return false;
2470     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2471     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2472     if (isVirtualBaseClass(D.Entries[I]))
2473       Result.Offset -= Layout.getVBaseClassOffset(Base);
2474     else
2475       Result.Offset -= Layout.getBaseClassOffset(Base);
2476     RD = Base;
2477   }
2478   D.Entries.resize(TruncatedElements);
2479   return true;
2480 }
2481 
2482 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2483                                    const CXXRecordDecl *Derived,
2484                                    const CXXRecordDecl *Base,
2485                                    const ASTRecordLayout *RL = nullptr) {
2486   if (!RL) {
2487     if (Derived->isInvalidDecl()) return false;
2488     RL = &Info.Ctx.getASTRecordLayout(Derived);
2489   }
2490 
2491   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2492   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2493   return true;
2494 }
2495 
2496 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2497                              const CXXRecordDecl *DerivedDecl,
2498                              const CXXBaseSpecifier *Base) {
2499   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2500 
2501   if (!Base->isVirtual())
2502     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2503 
2504   SubobjectDesignator &D = Obj.Designator;
2505   if (D.Invalid)
2506     return false;
2507 
2508   // Extract most-derived object and corresponding type.
2509   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2510   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2511     return false;
2512 
2513   // Find the virtual base class.
2514   if (DerivedDecl->isInvalidDecl()) return false;
2515   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2516   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2517   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2518   return true;
2519 }
2520 
2521 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2522                                  QualType Type, LValue &Result) {
2523   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2524                                      PathE = E->path_end();
2525        PathI != PathE; ++PathI) {
2526     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2527                           *PathI))
2528       return false;
2529     Type = (*PathI)->getType();
2530   }
2531   return true;
2532 }
2533 
2534 /// Cast an lvalue referring to a derived class to a known base subobject.
2535 static bool CastToBaseClass(EvalInfo &Info, const Expr *E, LValue &Result,
2536                             const CXXRecordDecl *DerivedRD,
2537                             const CXXRecordDecl *BaseRD) {
2538   CXXBasePaths Paths(/*FindAmbiguities=*/false,
2539                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
2540   if (!DerivedRD->isDerivedFrom(BaseRD, Paths))
2541     llvm_unreachable("Class must be derived from the passed in base class!");
2542 
2543   for (CXXBasePathElement &Elem : Paths.front())
2544     if (!HandleLValueBase(Info, E, Result, Elem.Class, Elem.Base))
2545       return false;
2546   return true;
2547 }
2548 
2549 /// Update LVal to refer to the given field, which must be a member of the type
2550 /// currently described by LVal.
2551 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2552                                const FieldDecl *FD,
2553                                const ASTRecordLayout *RL = nullptr) {
2554   if (!RL) {
2555     if (FD->getParent()->isInvalidDecl()) return false;
2556     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2557   }
2558 
2559   unsigned I = FD->getFieldIndex();
2560   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2561   LVal.addDecl(Info, E, FD);
2562   return true;
2563 }
2564 
2565 /// Update LVal to refer to the given indirect field.
2566 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2567                                        LValue &LVal,
2568                                        const IndirectFieldDecl *IFD) {
2569   for (const auto *C : IFD->chain())
2570     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2571       return false;
2572   return true;
2573 }
2574 
2575 /// Get the size of the given type in char units.
2576 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2577                          QualType Type, CharUnits &Size) {
2578   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2579   // extension.
2580   if (Type->isVoidType() || Type->isFunctionType()) {
2581     Size = CharUnits::One();
2582     return true;
2583   }
2584 
2585   if (Type->isDependentType()) {
2586     Info.FFDiag(Loc);
2587     return false;
2588   }
2589 
2590   if (!Type->isConstantSizeType()) {
2591     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2592     // FIXME: Better diagnostic.
2593     Info.FFDiag(Loc);
2594     return false;
2595   }
2596 
2597   Size = Info.Ctx.getTypeSizeInChars(Type);
2598   return true;
2599 }
2600 
2601 /// Update a pointer value to model pointer arithmetic.
2602 /// \param Info - Information about the ongoing evaluation.
2603 /// \param E - The expression being evaluated, for diagnostic purposes.
2604 /// \param LVal - The pointer value to be updated.
2605 /// \param EltTy - The pointee type represented by LVal.
2606 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2607 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2608                                         LValue &LVal, QualType EltTy,
2609                                         APSInt Adjustment) {
2610   CharUnits SizeOfPointee;
2611   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2612     return false;
2613 
2614   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2615   return true;
2616 }
2617 
2618 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2619                                         LValue &LVal, QualType EltTy,
2620                                         int64_t Adjustment) {
2621   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2622                                      APSInt::get(Adjustment));
2623 }
2624 
2625 /// Update an lvalue to refer to a component of a complex number.
2626 /// \param Info - Information about the ongoing evaluation.
2627 /// \param LVal - The lvalue to be updated.
2628 /// \param EltTy - The complex number's component type.
2629 /// \param Imag - False for the real component, true for the imaginary.
2630 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2631                                        LValue &LVal, QualType EltTy,
2632                                        bool Imag) {
2633   if (Imag) {
2634     CharUnits SizeOfComponent;
2635     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2636       return false;
2637     LVal.Offset += SizeOfComponent;
2638   }
2639   LVal.addComplex(Info, E, EltTy, Imag);
2640   return true;
2641 }
2642 
2643 /// Try to evaluate the initializer for a variable declaration.
2644 ///
2645 /// \param Info   Information about the ongoing evaluation.
2646 /// \param E      An expression to be used when printing diagnostics.
2647 /// \param VD     The variable whose initializer should be obtained.
2648 /// \param Frame  The frame in which the variable was created. Must be null
2649 ///               if this variable is not local to the evaluation.
2650 /// \param Result Filled in with a pointer to the value of the variable.
2651 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2652                                 const VarDecl *VD, CallStackFrame *Frame,
2653                                 APValue *&Result, const LValue *LVal) {
2654 
2655   // If this is a parameter to an active constexpr function call, perform
2656   // argument substitution.
2657   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2658     // Assume arguments of a potential constant expression are unknown
2659     // constant expressions.
2660     if (Info.checkingPotentialConstantExpression())
2661       return false;
2662     if (!Frame || !Frame->Arguments) {
2663       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2664       return false;
2665     }
2666     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2667     return true;
2668   }
2669 
2670   // If this is a local variable, dig out its value.
2671   if (Frame) {
2672     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2673                   : Frame->getCurrentTemporary(VD);
2674     if (!Result) {
2675       // Assume variables referenced within a lambda's call operator that were
2676       // not declared within the call operator are captures and during checking
2677       // of a potential constant expression, assume they are unknown constant
2678       // expressions.
2679       assert(isLambdaCallOperator(Frame->Callee) &&
2680              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2681              "missing value for local variable");
2682       if (Info.checkingPotentialConstantExpression())
2683         return false;
2684       // FIXME: implement capture evaluation during constant expr evaluation.
2685       Info.FFDiag(E->getBeginLoc(),
2686                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2687           << "captures not currently allowed";
2688       return false;
2689     }
2690     return true;
2691   }
2692 
2693   // Dig out the initializer, and use the declaration which it's attached to.
2694   const Expr *Init = VD->getAnyInitializer(VD);
2695   if (!Init || Init->isValueDependent()) {
2696     // If we're checking a potential constant expression, the variable could be
2697     // initialized later.
2698     if (!Info.checkingPotentialConstantExpression())
2699       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2700     return false;
2701   }
2702 
2703   // If we're currently evaluating the initializer of this declaration, use that
2704   // in-flight value.
2705   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2706     Result = Info.EvaluatingDeclValue;
2707     return true;
2708   }
2709 
2710   // Never evaluate the initializer of a weak variable. We can't be sure that
2711   // this is the definition which will be used.
2712   if (VD->isWeak()) {
2713     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2714     return false;
2715   }
2716 
2717   // Check that we can fold the initializer. In C++, we will have already done
2718   // this in the cases where it matters for conformance.
2719   SmallVector<PartialDiagnosticAt, 8> Notes;
2720   if (!VD->evaluateValue(Notes)) {
2721     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2722               Notes.size() + 1) << VD;
2723     Info.Note(VD->getLocation(), diag::note_declared_at);
2724     Info.addNotes(Notes);
2725     return false;
2726   } else if (!VD->checkInitIsICE()) {
2727     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2728                  Notes.size() + 1) << VD;
2729     Info.Note(VD->getLocation(), diag::note_declared_at);
2730     Info.addNotes(Notes);
2731   }
2732 
2733   Result = VD->getEvaluatedValue();
2734   return true;
2735 }
2736 
2737 static bool IsConstNonVolatile(QualType T) {
2738   Qualifiers Quals = T.getQualifiers();
2739   return Quals.hasConst() && !Quals.hasVolatile();
2740 }
2741 
2742 /// Get the base index of the given base class within an APValue representing
2743 /// the given derived class.
2744 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2745                              const CXXRecordDecl *Base) {
2746   Base = Base->getCanonicalDecl();
2747   unsigned Index = 0;
2748   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2749          E = Derived->bases_end(); I != E; ++I, ++Index) {
2750     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2751       return Index;
2752   }
2753 
2754   llvm_unreachable("base class missing from derived class's bases list");
2755 }
2756 
2757 /// Extract the value of a character from a string literal.
2758 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2759                                             uint64_t Index) {
2760   assert(!isa<SourceLocExpr>(Lit) &&
2761          "SourceLocExpr should have already been converted to a StringLiteral");
2762 
2763   // FIXME: Support MakeStringConstant
2764   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2765     std::string Str;
2766     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2767     assert(Index <= Str.size() && "Index too large");
2768     return APSInt::getUnsigned(Str.c_str()[Index]);
2769   }
2770 
2771   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2772     Lit = PE->getFunctionName();
2773   const StringLiteral *S = cast<StringLiteral>(Lit);
2774   const ConstantArrayType *CAT =
2775       Info.Ctx.getAsConstantArrayType(S->getType());
2776   assert(CAT && "string literal isn't an array");
2777   QualType CharType = CAT->getElementType();
2778   assert(CharType->isIntegerType() && "unexpected character type");
2779 
2780   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2781                CharType->isUnsignedIntegerType());
2782   if (Index < S->getLength())
2783     Value = S->getCodeUnit(Index);
2784   return Value;
2785 }
2786 
2787 // Expand a string literal into an array of characters.
2788 //
2789 // FIXME: This is inefficient; we should probably introduce something similar
2790 // to the LLVM ConstantDataArray to make this cheaper.
2791 static void expandStringLiteral(EvalInfo &Info, const StringLiteral *S,
2792                                 APValue &Result) {
2793   const ConstantArrayType *CAT =
2794       Info.Ctx.getAsConstantArrayType(S->getType());
2795   assert(CAT && "string literal isn't an array");
2796   QualType CharType = CAT->getElementType();
2797   assert(CharType->isIntegerType() && "unexpected character type");
2798 
2799   unsigned Elts = CAT->getSize().getZExtValue();
2800   Result = APValue(APValue::UninitArray(),
2801                    std::min(S->getLength(), Elts), Elts);
2802   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2803                CharType->isUnsignedIntegerType());
2804   if (Result.hasArrayFiller())
2805     Result.getArrayFiller() = APValue(Value);
2806   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2807     Value = S->getCodeUnit(I);
2808     Result.getArrayInitializedElt(I) = APValue(Value);
2809   }
2810 }
2811 
2812 // Expand an array so that it has more than Index filled elements.
2813 static void expandArray(APValue &Array, unsigned Index) {
2814   unsigned Size = Array.getArraySize();
2815   assert(Index < Size);
2816 
2817   // Always at least double the number of elements for which we store a value.
2818   unsigned OldElts = Array.getArrayInitializedElts();
2819   unsigned NewElts = std::max(Index+1, OldElts * 2);
2820   NewElts = std::min(Size, std::max(NewElts, 8u));
2821 
2822   // Copy the data across.
2823   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2824   for (unsigned I = 0; I != OldElts; ++I)
2825     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2826   for (unsigned I = OldElts; I != NewElts; ++I)
2827     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2828   if (NewValue.hasArrayFiller())
2829     NewValue.getArrayFiller() = Array.getArrayFiller();
2830   Array.swap(NewValue);
2831 }
2832 
2833 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2834 /// conversion. If it's of class type, we may assume that the copy operation
2835 /// is trivial. Note that this is never true for a union type with fields
2836 /// (because the copy always "reads" the active member) and always true for
2837 /// a non-class type.
2838 static bool isReadByLvalueToRvalueConversion(QualType T) {
2839   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2840   if (!RD || (RD->isUnion() && !RD->field_empty()))
2841     return true;
2842   if (RD->isEmpty())
2843     return false;
2844 
2845   for (auto *Field : RD->fields())
2846     if (isReadByLvalueToRvalueConversion(Field->getType()))
2847       return true;
2848 
2849   for (auto &BaseSpec : RD->bases())
2850     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2851       return true;
2852 
2853   return false;
2854 }
2855 
2856 /// Diagnose an attempt to read from any unreadable field within the specified
2857 /// type, which might be a class type.
2858 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2859                                      QualType T) {
2860   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2861   if (!RD)
2862     return false;
2863 
2864   if (!RD->hasMutableFields())
2865     return false;
2866 
2867   for (auto *Field : RD->fields()) {
2868     // If we're actually going to read this field in some way, then it can't
2869     // be mutable. If we're in a union, then assigning to a mutable field
2870     // (even an empty one) can change the active member, so that's not OK.
2871     // FIXME: Add core issue number for the union case.
2872     if (Field->isMutable() &&
2873         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2874       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2875       Info.Note(Field->getLocation(), diag::note_declared_at);
2876       return true;
2877     }
2878 
2879     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2880       return true;
2881   }
2882 
2883   for (auto &BaseSpec : RD->bases())
2884     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2885       return true;
2886 
2887   // All mutable fields were empty, and thus not actually read.
2888   return false;
2889 }
2890 
2891 static bool lifetimeStartedInEvaluation(EvalInfo &Info,
2892                                         APValue::LValueBase Base) {
2893   // A temporary we created.
2894   if (Base.getCallIndex())
2895     return true;
2896 
2897   auto *Evaluating = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2898   if (!Evaluating)
2899     return false;
2900 
2901   // The variable whose initializer we're evaluating.
2902   if (auto *BaseD = Base.dyn_cast<const ValueDecl*>())
2903     if (declaresSameEntity(Evaluating, BaseD))
2904       return true;
2905 
2906   // A temporary lifetime-extended by the variable whose initializer we're
2907   // evaluating.
2908   if (auto *BaseE = Base.dyn_cast<const Expr *>())
2909     if (auto *BaseMTE = dyn_cast<MaterializeTemporaryExpr>(BaseE))
2910       if (declaresSameEntity(BaseMTE->getExtendingDecl(), Evaluating))
2911         return true;
2912 
2913   return false;
2914 }
2915 
2916 namespace {
2917 /// A handle to a complete object (an object that is not a subobject of
2918 /// another object).
2919 struct CompleteObject {
2920   /// The identity of the object.
2921   APValue::LValueBase Base;
2922   /// The value of the complete object.
2923   APValue *Value;
2924   /// The type of the complete object.
2925   QualType Type;
2926 
2927   CompleteObject() : Value(nullptr) {}
2928   CompleteObject(APValue::LValueBase Base, APValue *Value, QualType Type)
2929       : Base(Base), Value(Value), Type(Type) {}
2930 
2931   bool mayReadMutableMembers(EvalInfo &Info) const {
2932     // In C++14 onwards, it is permitted to read a mutable member whose
2933     // lifetime began within the evaluation.
2934     // FIXME: Should we also allow this in C++11?
2935     if (!Info.getLangOpts().CPlusPlus14)
2936       return false;
2937     return lifetimeStartedInEvaluation(Info, Base);
2938   }
2939 
2940   explicit operator bool() const { return !Type.isNull(); }
2941 };
2942 } // end anonymous namespace
2943 
2944 static QualType getSubobjectType(QualType ObjType, QualType SubobjType,
2945                                  bool IsMutable = false) {
2946   // C++ [basic.type.qualifier]p1:
2947   // - A const object is an object of type const T or a non-mutable subobject
2948   //   of a const object.
2949   if (ObjType.isConstQualified() && !IsMutable)
2950     SubobjType.addConst();
2951   // - A volatile object is an object of type const T or a subobject of a
2952   //   volatile object.
2953   if (ObjType.isVolatileQualified())
2954     SubobjType.addVolatile();
2955   return SubobjType;
2956 }
2957 
2958 /// Find the designated sub-object of an rvalue.
2959 template<typename SubobjectHandler>
2960 typename SubobjectHandler::result_type
2961 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2962               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2963   if (Sub.Invalid)
2964     // A diagnostic will have already been produced.
2965     return handler.failed();
2966   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2967     if (Info.getLangOpts().CPlusPlus11)
2968       Info.FFDiag(E, Sub.isOnePastTheEnd()
2969                          ? diag::note_constexpr_access_past_end
2970                          : diag::note_constexpr_access_unsized_array)
2971           << handler.AccessKind;
2972     else
2973       Info.FFDiag(E);
2974     return handler.failed();
2975   }
2976 
2977   APValue *O = Obj.Value;
2978   QualType ObjType = Obj.Type;
2979   const FieldDecl *LastField = nullptr;
2980   const FieldDecl *VolatileField = nullptr;
2981 
2982   // Walk the designator's path to find the subobject.
2983   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2984     // Reading an indeterminate value is undefined, but assigning over one is OK.
2985     if (O->isAbsent() || (O->isIndeterminate() && handler.AccessKind != AK_Assign)) {
2986       if (!Info.checkingPotentialConstantExpression())
2987         Info.FFDiag(E, diag::note_constexpr_access_uninit)
2988             << handler.AccessKind << O->isIndeterminate();
2989       return handler.failed();
2990     }
2991 
2992     // C++ [class.ctor]p5:
2993     //    const and volatile semantics are not applied on an object under
2994     //    construction.
2995     if ((ObjType.isConstQualified() || ObjType.isVolatileQualified()) &&
2996         ObjType->isRecordType() &&
2997         Info.isEvaluatingConstructor(
2998             Obj.Base, llvm::makeArrayRef(Sub.Entries.begin(),
2999                                          Sub.Entries.begin() + I)) !=
3000                           ConstructionPhase::None) {
3001       ObjType = Info.Ctx.getCanonicalType(ObjType);
3002       ObjType.removeLocalConst();
3003       ObjType.removeLocalVolatile();
3004     }
3005 
3006     // If this is our last pass, check that the final object type is OK.
3007     if (I == N || (I == N - 1 && ObjType->isAnyComplexType())) {
3008       // Accesses to volatile objects are prohibited.
3009       if (ObjType.isVolatileQualified() && isFormalAccess(handler.AccessKind)) {
3010         if (Info.getLangOpts().CPlusPlus) {
3011           int DiagKind;
3012           SourceLocation Loc;
3013           const NamedDecl *Decl = nullptr;
3014           if (VolatileField) {
3015             DiagKind = 2;
3016             Loc = VolatileField->getLocation();
3017             Decl = VolatileField;
3018           } else if (auto *VD = Obj.Base.dyn_cast<const ValueDecl*>()) {
3019             DiagKind = 1;
3020             Loc = VD->getLocation();
3021             Decl = VD;
3022           } else {
3023             DiagKind = 0;
3024             if (auto *E = Obj.Base.dyn_cast<const Expr *>())
3025               Loc = E->getExprLoc();
3026           }
3027           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3028               << handler.AccessKind << DiagKind << Decl;
3029           Info.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
3030         } else {
3031           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
3032         }
3033         return handler.failed();
3034       }
3035 
3036       // If we are reading an object of class type, there may still be more
3037       // things we need to check: if there are any mutable subobjects, we
3038       // cannot perform this read. (This only happens when performing a trivial
3039       // copy or assignment.)
3040       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
3041           !Obj.mayReadMutableMembers(Info) &&
3042           diagnoseUnreadableFields(Info, E, ObjType))
3043         return handler.failed();
3044     }
3045 
3046     if (I == N) {
3047       if (!handler.found(*O, ObjType))
3048         return false;
3049 
3050       // If we modified a bit-field, truncate it to the right width.
3051       if (isModification(handler.AccessKind) &&
3052           LastField && LastField->isBitField() &&
3053           !truncateBitfieldValue(Info, E, *O, LastField))
3054         return false;
3055 
3056       return true;
3057     }
3058 
3059     LastField = nullptr;
3060     if (ObjType->isArrayType()) {
3061       // Next subobject is an array element.
3062       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
3063       assert(CAT && "vla in literal type?");
3064       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3065       if (CAT->getSize().ule(Index)) {
3066         // Note, it should not be possible to form a pointer with a valid
3067         // designator which points more than one past the end of the array.
3068         if (Info.getLangOpts().CPlusPlus11)
3069           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3070             << handler.AccessKind;
3071         else
3072           Info.FFDiag(E);
3073         return handler.failed();
3074       }
3075 
3076       ObjType = CAT->getElementType();
3077 
3078       if (O->getArrayInitializedElts() > Index)
3079         O = &O->getArrayInitializedElt(Index);
3080       else if (handler.AccessKind != AK_Read) {
3081         expandArray(*O, Index);
3082         O = &O->getArrayInitializedElt(Index);
3083       } else
3084         O = &O->getArrayFiller();
3085     } else if (ObjType->isAnyComplexType()) {
3086       // Next subobject is a complex number.
3087       uint64_t Index = Sub.Entries[I].getAsArrayIndex();
3088       if (Index > 1) {
3089         if (Info.getLangOpts().CPlusPlus11)
3090           Info.FFDiag(E, diag::note_constexpr_access_past_end)
3091             << handler.AccessKind;
3092         else
3093           Info.FFDiag(E);
3094         return handler.failed();
3095       }
3096 
3097       ObjType = getSubobjectType(
3098           ObjType, ObjType->castAs<ComplexType>()->getElementType());
3099 
3100       assert(I == N - 1 && "extracting subobject of scalar?");
3101       if (O->isComplexInt()) {
3102         return handler.found(Index ? O->getComplexIntImag()
3103                                    : O->getComplexIntReal(), ObjType);
3104       } else {
3105         assert(O->isComplexFloat());
3106         return handler.found(Index ? O->getComplexFloatImag()
3107                                    : O->getComplexFloatReal(), ObjType);
3108       }
3109     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
3110       if (Field->isMutable() && handler.AccessKind == AK_Read &&
3111           !Obj.mayReadMutableMembers(Info)) {
3112         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
3113           << Field;
3114         Info.Note(Field->getLocation(), diag::note_declared_at);
3115         return handler.failed();
3116       }
3117 
3118       // Next subobject is a class, struct or union field.
3119       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
3120       if (RD->isUnion()) {
3121         const FieldDecl *UnionField = O->getUnionField();
3122         if (!UnionField ||
3123             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
3124           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
3125             << handler.AccessKind << Field << !UnionField << UnionField;
3126           return handler.failed();
3127         }
3128         O = &O->getUnionValue();
3129       } else
3130         O = &O->getStructField(Field->getFieldIndex());
3131 
3132       ObjType = getSubobjectType(ObjType, Field->getType(), Field->isMutable());
3133       LastField = Field;
3134       if (Field->getType().isVolatileQualified())
3135         VolatileField = Field;
3136     } else {
3137       // Next subobject is a base class.
3138       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
3139       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
3140       O = &O->getStructBase(getBaseIndex(Derived, Base));
3141 
3142       ObjType = getSubobjectType(ObjType, Info.Ctx.getRecordType(Base));
3143     }
3144   }
3145 }
3146 
3147 namespace {
3148 struct ExtractSubobjectHandler {
3149   EvalInfo &Info;
3150   APValue &Result;
3151 
3152   static const AccessKinds AccessKind = AK_Read;
3153 
3154   typedef bool result_type;
3155   bool failed() { return false; }
3156   bool found(APValue &Subobj, QualType SubobjType) {
3157     Result = Subobj;
3158     return true;
3159   }
3160   bool found(APSInt &Value, QualType SubobjType) {
3161     Result = APValue(Value);
3162     return true;
3163   }
3164   bool found(APFloat &Value, QualType SubobjType) {
3165     Result = APValue(Value);
3166     return true;
3167   }
3168 };
3169 } // end anonymous namespace
3170 
3171 const AccessKinds ExtractSubobjectHandler::AccessKind;
3172 
3173 /// Extract the designated sub-object of an rvalue.
3174 static bool extractSubobject(EvalInfo &Info, const Expr *E,
3175                              const CompleteObject &Obj,
3176                              const SubobjectDesignator &Sub,
3177                              APValue &Result) {
3178   ExtractSubobjectHandler Handler = { Info, Result };
3179   return findSubobject(Info, E, Obj, Sub, Handler);
3180 }
3181 
3182 namespace {
3183 struct ModifySubobjectHandler {
3184   EvalInfo &Info;
3185   APValue &NewVal;
3186   const Expr *E;
3187 
3188   typedef bool result_type;
3189   static const AccessKinds AccessKind = AK_Assign;
3190 
3191   bool checkConst(QualType QT) {
3192     // Assigning to a const object has undefined behavior.
3193     if (QT.isConstQualified()) {
3194       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3195       return false;
3196     }
3197     return true;
3198   }
3199 
3200   bool failed() { return false; }
3201   bool found(APValue &Subobj, QualType SubobjType) {
3202     if (!checkConst(SubobjType))
3203       return false;
3204     // We've been given ownership of NewVal, so just swap it in.
3205     Subobj.swap(NewVal);
3206     return true;
3207   }
3208   bool found(APSInt &Value, QualType SubobjType) {
3209     if (!checkConst(SubobjType))
3210       return false;
3211     if (!NewVal.isInt()) {
3212       // Maybe trying to write a cast pointer value into a complex?
3213       Info.FFDiag(E);
3214       return false;
3215     }
3216     Value = NewVal.getInt();
3217     return true;
3218   }
3219   bool found(APFloat &Value, QualType SubobjType) {
3220     if (!checkConst(SubobjType))
3221       return false;
3222     Value = NewVal.getFloat();
3223     return true;
3224   }
3225 };
3226 } // end anonymous namespace
3227 
3228 const AccessKinds ModifySubobjectHandler::AccessKind;
3229 
3230 /// Update the designated sub-object of an rvalue to the given value.
3231 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3232                             const CompleteObject &Obj,
3233                             const SubobjectDesignator &Sub,
3234                             APValue &NewVal) {
3235   ModifySubobjectHandler Handler = { Info, NewVal, E };
3236   return findSubobject(Info, E, Obj, Sub, Handler);
3237 }
3238 
3239 /// Find the position where two subobject designators diverge, or equivalently
3240 /// the length of the common initial subsequence.
3241 static unsigned FindDesignatorMismatch(QualType ObjType,
3242                                        const SubobjectDesignator &A,
3243                                        const SubobjectDesignator &B,
3244                                        bool &WasArrayIndex) {
3245   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3246   for (/**/; I != N; ++I) {
3247     if (!ObjType.isNull() &&
3248         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3249       // Next subobject is an array element.
3250       if (A.Entries[I].getAsArrayIndex() != B.Entries[I].getAsArrayIndex()) {
3251         WasArrayIndex = true;
3252         return I;
3253       }
3254       if (ObjType->isAnyComplexType())
3255         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3256       else
3257         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3258     } else {
3259       if (A.Entries[I].getAsBaseOrMember() !=
3260           B.Entries[I].getAsBaseOrMember()) {
3261         WasArrayIndex = false;
3262         return I;
3263       }
3264       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3265         // Next subobject is a field.
3266         ObjType = FD->getType();
3267       else
3268         // Next subobject is a base class.
3269         ObjType = QualType();
3270     }
3271   }
3272   WasArrayIndex = false;
3273   return I;
3274 }
3275 
3276 /// Determine whether the given subobject designators refer to elements of the
3277 /// same array object.
3278 static bool AreElementsOfSameArray(QualType ObjType,
3279                                    const SubobjectDesignator &A,
3280                                    const SubobjectDesignator &B) {
3281   if (A.Entries.size() != B.Entries.size())
3282     return false;
3283 
3284   bool IsArray = A.MostDerivedIsArrayElement;
3285   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3286     // A is a subobject of the array element.
3287     return false;
3288 
3289   // If A (and B) designates an array element, the last entry will be the array
3290   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3291   // of length 1' case, and the entire path must match.
3292   bool WasArrayIndex;
3293   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3294   return CommonLength >= A.Entries.size() - IsArray;
3295 }
3296 
3297 /// Find the complete object to which an LValue refers.
3298 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3299                                          AccessKinds AK, const LValue &LVal,
3300                                          QualType LValType) {
3301   if (LVal.InvalidBase) {
3302     Info.FFDiag(E);
3303     return CompleteObject();
3304   }
3305 
3306   if (!LVal.Base) {
3307     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3308     return CompleteObject();
3309   }
3310 
3311   CallStackFrame *Frame = nullptr;
3312   unsigned Depth = 0;
3313   if (LVal.getLValueCallIndex()) {
3314     std::tie(Frame, Depth) =
3315         Info.getCallFrameAndDepth(LVal.getLValueCallIndex());
3316     if (!Frame) {
3317       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3318         << AK << LVal.Base.is<const ValueDecl*>();
3319       NoteLValueLocation(Info, LVal.Base);
3320       return CompleteObject();
3321     }
3322   }
3323 
3324   bool IsAccess = isFormalAccess(AK);
3325 
3326   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3327   // is not a constant expression (even if the object is non-volatile). We also
3328   // apply this rule to C++98, in order to conform to the expected 'volatile'
3329   // semantics.
3330   if (IsAccess && LValType.isVolatileQualified()) {
3331     if (Info.getLangOpts().CPlusPlus)
3332       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3333         << AK << LValType;
3334     else
3335       Info.FFDiag(E);
3336     return CompleteObject();
3337   }
3338 
3339   // Compute value storage location and type of base object.
3340   APValue *BaseVal = nullptr;
3341   QualType BaseType = getType(LVal.Base);
3342 
3343   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3344     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3345     // In C++11, constexpr, non-volatile variables initialized with constant
3346     // expressions are constant expressions too. Inside constexpr functions,
3347     // parameters are constant expressions even if they're non-const.
3348     // In C++1y, objects local to a constant expression (those with a Frame) are
3349     // both readable and writable inside constant expressions.
3350     // In C, such things can also be folded, although they are not ICEs.
3351     const VarDecl *VD = dyn_cast<VarDecl>(D);
3352     if (VD) {
3353       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3354         VD = VDef;
3355     }
3356     if (!VD || VD->isInvalidDecl()) {
3357       Info.FFDiag(E);
3358       return CompleteObject();
3359     }
3360 
3361     // Unless we're looking at a local variable or argument in a constexpr call,
3362     // the variable we're reading must be const.
3363     if (!Frame) {
3364       if (Info.getLangOpts().CPlusPlus14 &&
3365           declaresSameEntity(
3366               VD, Info.EvaluatingDecl.dyn_cast<const ValueDecl *>())) {
3367         // OK, we can read and modify an object if we're in the process of
3368         // evaluating its initializer, because its lifetime began in this
3369         // evaluation.
3370       } else if (isModification(AK)) {
3371         // All the remaining cases do not permit modification of the object.
3372         Info.FFDiag(E, diag::note_constexpr_modify_global);
3373         return CompleteObject();
3374       } else if (VD->isConstexpr()) {
3375         // OK, we can read this variable.
3376       } else if (BaseType->isIntegralOrEnumerationType()) {
3377         // In OpenCL if a variable is in constant address space it is a const
3378         // value.
3379         if (!(BaseType.isConstQualified() ||
3380               (Info.getLangOpts().OpenCL &&
3381                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3382           if (!IsAccess)
3383             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3384           if (Info.getLangOpts().CPlusPlus) {
3385             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3386             Info.Note(VD->getLocation(), diag::note_declared_at);
3387           } else {
3388             Info.FFDiag(E);
3389           }
3390           return CompleteObject();
3391         }
3392       } else if (!IsAccess) {
3393         return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3394       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3395         // We support folding of const floating-point types, in order to make
3396         // static const data members of such types (supported as an extension)
3397         // more useful.
3398         if (Info.getLangOpts().CPlusPlus11) {
3399           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3400           Info.Note(VD->getLocation(), diag::note_declared_at);
3401         } else {
3402           Info.CCEDiag(E);
3403         }
3404       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3405         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3406         // Keep evaluating to see what we can do.
3407       } else {
3408         // FIXME: Allow folding of values of any literal type in all languages.
3409         if (Info.checkingPotentialConstantExpression() &&
3410             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3411           // The definition of this variable could be constexpr. We can't
3412           // access it right now, but may be able to in future.
3413         } else if (Info.getLangOpts().CPlusPlus11) {
3414           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3415           Info.Note(VD->getLocation(), diag::note_declared_at);
3416         } else {
3417           Info.FFDiag(E);
3418         }
3419         return CompleteObject();
3420       }
3421     }
3422 
3423     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3424       return CompleteObject();
3425   } else {
3426     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3427 
3428     if (!Frame) {
3429       if (const MaterializeTemporaryExpr *MTE =
3430               dyn_cast_or_null<MaterializeTemporaryExpr>(Base)) {
3431         assert(MTE->getStorageDuration() == SD_Static &&
3432                "should have a frame for a non-global materialized temporary");
3433 
3434         // Per C++1y [expr.const]p2:
3435         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3436         //   - a [...] glvalue of integral or enumeration type that refers to
3437         //     a non-volatile const object [...]
3438         //   [...]
3439         //   - a [...] glvalue of literal type that refers to a non-volatile
3440         //     object whose lifetime began within the evaluation of e.
3441         //
3442         // C++11 misses the 'began within the evaluation of e' check and
3443         // instead allows all temporaries, including things like:
3444         //   int &&r = 1;
3445         //   int x = ++r;
3446         //   constexpr int k = r;
3447         // Therefore we use the C++14 rules in C++11 too.
3448         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3449         const ValueDecl *ED = MTE->getExtendingDecl();
3450         if (!(BaseType.isConstQualified() &&
3451               BaseType->isIntegralOrEnumerationType()) &&
3452             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3453           if (!IsAccess)
3454             return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3455           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3456           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3457           return CompleteObject();
3458         }
3459 
3460         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3461         assert(BaseVal && "got reference to unevaluated temporary");
3462       } else {
3463         if (!IsAccess)
3464           return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
3465         APValue Val;
3466         LVal.moveInto(Val);
3467         Info.FFDiag(E, diag::note_constexpr_access_unreadable_object)
3468             << AK
3469             << Val.getAsString(Info.Ctx,
3470                                Info.Ctx.getLValueReferenceType(LValType));
3471         NoteLValueLocation(Info, LVal.Base);
3472         return CompleteObject();
3473       }
3474     } else {
3475       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3476       assert(BaseVal && "missing value for temporary");
3477     }
3478   }
3479 
3480   // In C++14, we can't safely access any mutable state when we might be
3481   // evaluating after an unmodeled side effect.
3482   //
3483   // FIXME: Not all local state is mutable. Allow local constant subobjects
3484   // to be read here (but take care with 'mutable' fields).
3485   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3486        Info.EvalStatus.HasSideEffects) ||
3487       (isModification(AK) && Depth < Info.SpeculativeEvaluationDepth))
3488     return CompleteObject();
3489 
3490   return CompleteObject(LVal.getLValueBase(), BaseVal, BaseType);
3491 }
3492 
3493 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3494 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3495 /// glvalue referred to by an entity of reference type.
3496 ///
3497 /// \param Info - Information about the ongoing evaluation.
3498 /// \param Conv - The expression for which we are performing the conversion.
3499 ///               Used for diagnostics.
3500 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3501 ///               case of a non-class type).
3502 /// \param LVal - The glvalue on which we are attempting to perform this action.
3503 /// \param RVal - The produced value will be placed here.
3504 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3505                                            QualType Type,
3506                                            const LValue &LVal, APValue &RVal) {
3507   if (LVal.Designator.Invalid)
3508     return false;
3509 
3510   // Check for special cases where there is no existing APValue to look at.
3511   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3512 
3513   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3514     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3515       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3516       // initializer until now for such expressions. Such an expression can't be
3517       // an ICE in C, so this only matters for fold.
3518       if (Type.isVolatileQualified()) {
3519         Info.FFDiag(Conv);
3520         return false;
3521       }
3522       APValue Lit;
3523       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3524         return false;
3525       CompleteObject LitObj(LVal.Base, &Lit, Base->getType());
3526       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3527     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3528       // Special-case character extraction so we don't have to construct an
3529       // APValue for the whole string.
3530       assert(LVal.Designator.Entries.size() <= 1 &&
3531              "Can only read characters from string literals");
3532       if (LVal.Designator.Entries.empty()) {
3533         // Fail for now for LValue to RValue conversion of an array.
3534         // (This shouldn't show up in C/C++, but it could be triggered by a
3535         // weird EvaluateAsRValue call from a tool.)
3536         Info.FFDiag(Conv);
3537         return false;
3538       }
3539       if (LVal.Designator.isOnePastTheEnd()) {
3540         if (Info.getLangOpts().CPlusPlus11)
3541           Info.FFDiag(Conv, diag::note_constexpr_access_past_end) << AK_Read;
3542         else
3543           Info.FFDiag(Conv);
3544         return false;
3545       }
3546       uint64_t CharIndex = LVal.Designator.Entries[0].getAsArrayIndex();
3547       RVal = APValue(extractStringLiteralCharacter(Info, Base, CharIndex));
3548       return true;
3549     }
3550   }
3551 
3552   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3553   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3554 }
3555 
3556 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3557 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3558                              QualType LValType, APValue &Val) {
3559   if (LVal.Designator.Invalid)
3560     return false;
3561 
3562   if (!Info.getLangOpts().CPlusPlus14) {
3563     Info.FFDiag(E);
3564     return false;
3565   }
3566 
3567   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3568   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3569 }
3570 
3571 namespace {
3572 struct CompoundAssignSubobjectHandler {
3573   EvalInfo &Info;
3574   const Expr *E;
3575   QualType PromotedLHSType;
3576   BinaryOperatorKind Opcode;
3577   const APValue &RHS;
3578 
3579   static const AccessKinds AccessKind = AK_Assign;
3580 
3581   typedef bool result_type;
3582 
3583   bool checkConst(QualType QT) {
3584     // Assigning to a const object has undefined behavior.
3585     if (QT.isConstQualified()) {
3586       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3587       return false;
3588     }
3589     return true;
3590   }
3591 
3592   bool failed() { return false; }
3593   bool found(APValue &Subobj, QualType SubobjType) {
3594     switch (Subobj.getKind()) {
3595     case APValue::Int:
3596       return found(Subobj.getInt(), SubobjType);
3597     case APValue::Float:
3598       return found(Subobj.getFloat(), SubobjType);
3599     case APValue::ComplexInt:
3600     case APValue::ComplexFloat:
3601       // FIXME: Implement complex compound assignment.
3602       Info.FFDiag(E);
3603       return false;
3604     case APValue::LValue:
3605       return foundPointer(Subobj, SubobjType);
3606     default:
3607       // FIXME: can this happen?
3608       Info.FFDiag(E);
3609       return false;
3610     }
3611   }
3612   bool found(APSInt &Value, QualType SubobjType) {
3613     if (!checkConst(SubobjType))
3614       return false;
3615 
3616     if (!SubobjType->isIntegerType()) {
3617       // We don't support compound assignment on integer-cast-to-pointer
3618       // values.
3619       Info.FFDiag(E);
3620       return false;
3621     }
3622 
3623     if (RHS.isInt()) {
3624       APSInt LHS =
3625           HandleIntToIntCast(Info, E, PromotedLHSType, SubobjType, Value);
3626       if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3627         return false;
3628       Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3629       return true;
3630     } else if (RHS.isFloat()) {
3631       APFloat FValue(0.0);
3632       return HandleIntToFloatCast(Info, E, SubobjType, Value, PromotedLHSType,
3633                                   FValue) &&
3634              handleFloatFloatBinOp(Info, E, FValue, Opcode, RHS.getFloat()) &&
3635              HandleFloatToIntCast(Info, E, PromotedLHSType, FValue, SubobjType,
3636                                   Value);
3637     }
3638 
3639     Info.FFDiag(E);
3640     return false;
3641   }
3642   bool found(APFloat &Value, QualType SubobjType) {
3643     return checkConst(SubobjType) &&
3644            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3645                                   Value) &&
3646            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3647            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3648   }
3649   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3650     if (!checkConst(SubobjType))
3651       return false;
3652 
3653     QualType PointeeType;
3654     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3655       PointeeType = PT->getPointeeType();
3656 
3657     if (PointeeType.isNull() || !RHS.isInt() ||
3658         (Opcode != BO_Add && Opcode != BO_Sub)) {
3659       Info.FFDiag(E);
3660       return false;
3661     }
3662 
3663     APSInt Offset = RHS.getInt();
3664     if (Opcode == BO_Sub)
3665       negateAsSigned(Offset);
3666 
3667     LValue LVal;
3668     LVal.setFrom(Info.Ctx, Subobj);
3669     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3670       return false;
3671     LVal.moveInto(Subobj);
3672     return true;
3673   }
3674 };
3675 } // end anonymous namespace
3676 
3677 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3678 
3679 /// Perform a compound assignment of LVal <op>= RVal.
3680 static bool handleCompoundAssignment(
3681     EvalInfo &Info, const Expr *E,
3682     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3683     BinaryOperatorKind Opcode, const APValue &RVal) {
3684   if (LVal.Designator.Invalid)
3685     return false;
3686 
3687   if (!Info.getLangOpts().CPlusPlus14) {
3688     Info.FFDiag(E);
3689     return false;
3690   }
3691 
3692   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3693   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3694                                              RVal };
3695   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3696 }
3697 
3698 namespace {
3699 struct IncDecSubobjectHandler {
3700   EvalInfo &Info;
3701   const UnaryOperator *E;
3702   AccessKinds AccessKind;
3703   APValue *Old;
3704 
3705   typedef bool result_type;
3706 
3707   bool checkConst(QualType QT) {
3708     // Assigning to a const object has undefined behavior.
3709     if (QT.isConstQualified()) {
3710       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3711       return false;
3712     }
3713     return true;
3714   }
3715 
3716   bool failed() { return false; }
3717   bool found(APValue &Subobj, QualType SubobjType) {
3718     // Stash the old value. Also clear Old, so we don't clobber it later
3719     // if we're post-incrementing a complex.
3720     if (Old) {
3721       *Old = Subobj;
3722       Old = nullptr;
3723     }
3724 
3725     switch (Subobj.getKind()) {
3726     case APValue::Int:
3727       return found(Subobj.getInt(), SubobjType);
3728     case APValue::Float:
3729       return found(Subobj.getFloat(), SubobjType);
3730     case APValue::ComplexInt:
3731       return found(Subobj.getComplexIntReal(),
3732                    SubobjType->castAs<ComplexType>()->getElementType()
3733                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3734     case APValue::ComplexFloat:
3735       return found(Subobj.getComplexFloatReal(),
3736                    SubobjType->castAs<ComplexType>()->getElementType()
3737                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3738     case APValue::LValue:
3739       return foundPointer(Subobj, SubobjType);
3740     default:
3741       // FIXME: can this happen?
3742       Info.FFDiag(E);
3743       return false;
3744     }
3745   }
3746   bool found(APSInt &Value, QualType SubobjType) {
3747     if (!checkConst(SubobjType))
3748       return false;
3749 
3750     if (!SubobjType->isIntegerType()) {
3751       // We don't support increment / decrement on integer-cast-to-pointer
3752       // values.
3753       Info.FFDiag(E);
3754       return false;
3755     }
3756 
3757     if (Old) *Old = APValue(Value);
3758 
3759     // bool arithmetic promotes to int, and the conversion back to bool
3760     // doesn't reduce mod 2^n, so special-case it.
3761     if (SubobjType->isBooleanType()) {
3762       if (AccessKind == AK_Increment)
3763         Value = 1;
3764       else
3765         Value = !Value;
3766       return true;
3767     }
3768 
3769     bool WasNegative = Value.isNegative();
3770     if (AccessKind == AK_Increment) {
3771       ++Value;
3772 
3773       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3774         APSInt ActualValue(Value, /*IsUnsigned*/true);
3775         return HandleOverflow(Info, E, ActualValue, SubobjType);
3776       }
3777     } else {
3778       --Value;
3779 
3780       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3781         unsigned BitWidth = Value.getBitWidth();
3782         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3783         ActualValue.setBit(BitWidth);
3784         return HandleOverflow(Info, E, ActualValue, SubobjType);
3785       }
3786     }
3787     return true;
3788   }
3789   bool found(APFloat &Value, QualType SubobjType) {
3790     if (!checkConst(SubobjType))
3791       return false;
3792 
3793     if (Old) *Old = APValue(Value);
3794 
3795     APFloat One(Value.getSemantics(), 1);
3796     if (AccessKind == AK_Increment)
3797       Value.add(One, APFloat::rmNearestTiesToEven);
3798     else
3799       Value.subtract(One, APFloat::rmNearestTiesToEven);
3800     return true;
3801   }
3802   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3803     if (!checkConst(SubobjType))
3804       return false;
3805 
3806     QualType PointeeType;
3807     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3808       PointeeType = PT->getPointeeType();
3809     else {
3810       Info.FFDiag(E);
3811       return false;
3812     }
3813 
3814     LValue LVal;
3815     LVal.setFrom(Info.Ctx, Subobj);
3816     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3817                                      AccessKind == AK_Increment ? 1 : -1))
3818       return false;
3819     LVal.moveInto(Subobj);
3820     return true;
3821   }
3822 };
3823 } // end anonymous namespace
3824 
3825 /// Perform an increment or decrement on LVal.
3826 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3827                          QualType LValType, bool IsIncrement, APValue *Old) {
3828   if (LVal.Designator.Invalid)
3829     return false;
3830 
3831   if (!Info.getLangOpts().CPlusPlus14) {
3832     Info.FFDiag(E);
3833     return false;
3834   }
3835 
3836   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3837   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3838   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3839   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3840 }
3841 
3842 /// Build an lvalue for the object argument of a member function call.
3843 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3844                                    LValue &This) {
3845   if (Object->getType()->isPointerType())
3846     return EvaluatePointer(Object, This, Info);
3847 
3848   if (Object->isGLValue())
3849     return EvaluateLValue(Object, This, Info);
3850 
3851   if (Object->getType()->isLiteralType(Info.Ctx))
3852     return EvaluateTemporary(Object, This, Info);
3853 
3854   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3855   return false;
3856 }
3857 
3858 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3859 /// lvalue referring to the result.
3860 ///
3861 /// \param Info - Information about the ongoing evaluation.
3862 /// \param LV - An lvalue referring to the base of the member pointer.
3863 /// \param RHS - The member pointer expression.
3864 /// \param IncludeMember - Specifies whether the member itself is included in
3865 ///        the resulting LValue subobject designator. This is not possible when
3866 ///        creating a bound member function.
3867 /// \return The field or method declaration to which the member pointer refers,
3868 ///         or 0 if evaluation fails.
3869 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3870                                                   QualType LVType,
3871                                                   LValue &LV,
3872                                                   const Expr *RHS,
3873                                                   bool IncludeMember = true) {
3874   MemberPtr MemPtr;
3875   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3876     return nullptr;
3877 
3878   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3879   // member value, the behavior is undefined.
3880   if (!MemPtr.getDecl()) {
3881     // FIXME: Specific diagnostic.
3882     Info.FFDiag(RHS);
3883     return nullptr;
3884   }
3885 
3886   if (MemPtr.isDerivedMember()) {
3887     // This is a member of some derived class. Truncate LV appropriately.
3888     // The end of the derived-to-base path for the base object must match the
3889     // derived-to-base path for the member pointer.
3890     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3891         LV.Designator.Entries.size()) {
3892       Info.FFDiag(RHS);
3893       return nullptr;
3894     }
3895     unsigned PathLengthToMember =
3896         LV.Designator.Entries.size() - MemPtr.Path.size();
3897     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3898       const CXXRecordDecl *LVDecl = getAsBaseClass(
3899           LV.Designator.Entries[PathLengthToMember + I]);
3900       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3901       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3902         Info.FFDiag(RHS);
3903         return nullptr;
3904       }
3905     }
3906 
3907     // Truncate the lvalue to the appropriate derived class.
3908     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3909                             PathLengthToMember))
3910       return nullptr;
3911   } else if (!MemPtr.Path.empty()) {
3912     // Extend the LValue path with the member pointer's path.
3913     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3914                                   MemPtr.Path.size() + IncludeMember);
3915 
3916     // Walk down to the appropriate base class.
3917     if (const PointerType *PT = LVType->getAs<PointerType>())
3918       LVType = PT->getPointeeType();
3919     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3920     assert(RD && "member pointer access on non-class-type expression");
3921     // The first class in the path is that of the lvalue.
3922     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3923       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3924       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3925         return nullptr;
3926       RD = Base;
3927     }
3928     // Finally cast to the class containing the member.
3929     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3930                                 MemPtr.getContainingRecord()))
3931       return nullptr;
3932   }
3933 
3934   // Add the member. Note that we cannot build bound member functions here.
3935   if (IncludeMember) {
3936     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3937       if (!HandleLValueMember(Info, RHS, LV, FD))
3938         return nullptr;
3939     } else if (const IndirectFieldDecl *IFD =
3940                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3941       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3942         return nullptr;
3943     } else {
3944       llvm_unreachable("can't construct reference to bound member function");
3945     }
3946   }
3947 
3948   return MemPtr.getDecl();
3949 }
3950 
3951 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3952                                                   const BinaryOperator *BO,
3953                                                   LValue &LV,
3954                                                   bool IncludeMember = true) {
3955   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3956 
3957   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3958     if (Info.noteFailure()) {
3959       MemberPtr MemPtr;
3960       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3961     }
3962     return nullptr;
3963   }
3964 
3965   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3966                                    BO->getRHS(), IncludeMember);
3967 }
3968 
3969 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3970 /// the provided lvalue, which currently refers to the base object.
3971 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3972                                     LValue &Result) {
3973   SubobjectDesignator &D = Result.Designator;
3974   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3975     return false;
3976 
3977   QualType TargetQT = E->getType();
3978   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3979     TargetQT = PT->getPointeeType();
3980 
3981   // Check this cast lands within the final derived-to-base subobject path.
3982   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3983     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3984       << D.MostDerivedType << TargetQT;
3985     return false;
3986   }
3987 
3988   // Check the type of the final cast. We don't need to check the path,
3989   // since a cast can only be formed if the path is unique.
3990   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3991   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3992   const CXXRecordDecl *FinalType;
3993   if (NewEntriesSize == D.MostDerivedPathLength)
3994     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3995   else
3996     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3997   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3998     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3999       << D.MostDerivedType << TargetQT;
4000     return false;
4001   }
4002 
4003   // Truncate the lvalue to the appropriate derived class.
4004   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
4005 }
4006 
4007 namespace {
4008 enum EvalStmtResult {
4009   /// Evaluation failed.
4010   ESR_Failed,
4011   /// Hit a 'return' statement.
4012   ESR_Returned,
4013   /// Evaluation succeeded.
4014   ESR_Succeeded,
4015   /// Hit a 'continue' statement.
4016   ESR_Continue,
4017   /// Hit a 'break' statement.
4018   ESR_Break,
4019   /// Still scanning for 'case' or 'default' statement.
4020   ESR_CaseNotFound
4021 };
4022 }
4023 
4024 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
4025   // We don't need to evaluate the initializer for a static local.
4026   if (!VD->hasLocalStorage())
4027     return true;
4028 
4029   LValue Result;
4030   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
4031 
4032   const Expr *InitE = VD->getInit();
4033   if (!InitE) {
4034     Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
4035         << false << VD->getType();
4036     Val = APValue();
4037     return false;
4038   }
4039 
4040   if (InitE->isValueDependent())
4041     return false;
4042 
4043   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
4044     // Wipe out any partially-computed value, to allow tracking that this
4045     // evaluation failed.
4046     Val = APValue();
4047     return false;
4048   }
4049 
4050   return true;
4051 }
4052 
4053 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
4054   bool OK = true;
4055 
4056   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
4057     OK &= EvaluateVarDecl(Info, VD);
4058 
4059   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
4060     for (auto *BD : DD->bindings())
4061       if (auto *VD = BD->getHoldingVar())
4062         OK &= EvaluateDecl(Info, VD);
4063 
4064   return OK;
4065 }
4066 
4067 
4068 /// Evaluate a condition (either a variable declaration or an expression).
4069 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
4070                          const Expr *Cond, bool &Result) {
4071   FullExpressionRAII Scope(Info);
4072   if (CondDecl && !EvaluateDecl(Info, CondDecl))
4073     return false;
4074   return EvaluateAsBooleanCondition(Cond, Result, Info);
4075 }
4076 
4077 namespace {
4078 /// A location where the result (returned value) of evaluating a
4079 /// statement should be stored.
4080 struct StmtResult {
4081   /// The APValue that should be filled in with the returned value.
4082   APValue &Value;
4083   /// The location containing the result, if any (used to support RVO).
4084   const LValue *Slot;
4085 };
4086 
4087 struct TempVersionRAII {
4088   CallStackFrame &Frame;
4089 
4090   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
4091     Frame.pushTempVersion();
4092   }
4093 
4094   ~TempVersionRAII() {
4095     Frame.popTempVersion();
4096   }
4097 };
4098 
4099 }
4100 
4101 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4102                                    const Stmt *S,
4103                                    const SwitchCase *SC = nullptr);
4104 
4105 /// Evaluate the body of a loop, and translate the result as appropriate.
4106 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
4107                                        const Stmt *Body,
4108                                        const SwitchCase *Case = nullptr) {
4109   BlockScopeRAII Scope(Info);
4110   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
4111   case ESR_Break:
4112     return ESR_Succeeded;
4113   case ESR_Succeeded:
4114   case ESR_Continue:
4115     return ESR_Continue;
4116   case ESR_Failed:
4117   case ESR_Returned:
4118   case ESR_CaseNotFound:
4119     return ESR;
4120   }
4121   llvm_unreachable("Invalid EvalStmtResult!");
4122 }
4123 
4124 /// Evaluate a switch statement.
4125 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
4126                                      const SwitchStmt *SS) {
4127   BlockScopeRAII Scope(Info);
4128 
4129   // Evaluate the switch condition.
4130   APSInt Value;
4131   {
4132     FullExpressionRAII Scope(Info);
4133     if (const Stmt *Init = SS->getInit()) {
4134       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4135       if (ESR != ESR_Succeeded)
4136         return ESR;
4137     }
4138     if (SS->getConditionVariable() &&
4139         !EvaluateDecl(Info, SS->getConditionVariable()))
4140       return ESR_Failed;
4141     if (!EvaluateInteger(SS->getCond(), Value, Info))
4142       return ESR_Failed;
4143   }
4144 
4145   // Find the switch case corresponding to the value of the condition.
4146   // FIXME: Cache this lookup.
4147   const SwitchCase *Found = nullptr;
4148   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
4149        SC = SC->getNextSwitchCase()) {
4150     if (isa<DefaultStmt>(SC)) {
4151       Found = SC;
4152       continue;
4153     }
4154 
4155     const CaseStmt *CS = cast<CaseStmt>(SC);
4156     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
4157     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
4158                               : LHS;
4159     if (LHS <= Value && Value <= RHS) {
4160       Found = SC;
4161       break;
4162     }
4163   }
4164 
4165   if (!Found)
4166     return ESR_Succeeded;
4167 
4168   // Search the switch body for the switch case and evaluate it from there.
4169   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
4170   case ESR_Break:
4171     return ESR_Succeeded;
4172   case ESR_Succeeded:
4173   case ESR_Continue:
4174   case ESR_Failed:
4175   case ESR_Returned:
4176     return ESR;
4177   case ESR_CaseNotFound:
4178     // This can only happen if the switch case is nested within a statement
4179     // expression. We have no intention of supporting that.
4180     Info.FFDiag(Found->getBeginLoc(),
4181                 diag::note_constexpr_stmt_expr_unsupported);
4182     return ESR_Failed;
4183   }
4184   llvm_unreachable("Invalid EvalStmtResult!");
4185 }
4186 
4187 // Evaluate a statement.
4188 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
4189                                    const Stmt *S, const SwitchCase *Case) {
4190   if (!Info.nextStep(S))
4191     return ESR_Failed;
4192 
4193   // If we're hunting down a 'case' or 'default' label, recurse through
4194   // substatements until we hit the label.
4195   if (Case) {
4196     // FIXME: We don't start the lifetime of objects whose initialization we
4197     // jump over. However, such objects must be of class type with a trivial
4198     // default constructor that initialize all subobjects, so must be empty,
4199     // so this almost never matters.
4200     switch (S->getStmtClass()) {
4201     case Stmt::CompoundStmtClass:
4202       // FIXME: Precompute which substatement of a compound statement we
4203       // would jump to, and go straight there rather than performing a
4204       // linear scan each time.
4205     case Stmt::LabelStmtClass:
4206     case Stmt::AttributedStmtClass:
4207     case Stmt::DoStmtClass:
4208       break;
4209 
4210     case Stmt::CaseStmtClass:
4211     case Stmt::DefaultStmtClass:
4212       if (Case == S)
4213         Case = nullptr;
4214       break;
4215 
4216     case Stmt::IfStmtClass: {
4217       // FIXME: Precompute which side of an 'if' we would jump to, and go
4218       // straight there rather than scanning both sides.
4219       const IfStmt *IS = cast<IfStmt>(S);
4220 
4221       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4222       // preceded by our switch label.
4223       BlockScopeRAII Scope(Info);
4224 
4225       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4226       if (ESR != ESR_CaseNotFound || !IS->getElse())
4227         return ESR;
4228       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4229     }
4230 
4231     case Stmt::WhileStmtClass: {
4232       EvalStmtResult ESR =
4233           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4234       if (ESR != ESR_Continue)
4235         return ESR;
4236       break;
4237     }
4238 
4239     case Stmt::ForStmtClass: {
4240       const ForStmt *FS = cast<ForStmt>(S);
4241       EvalStmtResult ESR =
4242           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4243       if (ESR != ESR_Continue)
4244         return ESR;
4245       if (FS->getInc()) {
4246         FullExpressionRAII IncScope(Info);
4247         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4248           return ESR_Failed;
4249       }
4250       break;
4251     }
4252 
4253     case Stmt::DeclStmtClass:
4254       // FIXME: If the variable has initialization that can't be jumped over,
4255       // bail out of any immediately-surrounding compound-statement too.
4256     default:
4257       return ESR_CaseNotFound;
4258     }
4259   }
4260 
4261   switch (S->getStmtClass()) {
4262   default:
4263     if (const Expr *E = dyn_cast<Expr>(S)) {
4264       // Don't bother evaluating beyond an expression-statement which couldn't
4265       // be evaluated.
4266       FullExpressionRAII Scope(Info);
4267       if (!EvaluateIgnoredValue(Info, E))
4268         return ESR_Failed;
4269       return ESR_Succeeded;
4270     }
4271 
4272     Info.FFDiag(S->getBeginLoc());
4273     return ESR_Failed;
4274 
4275   case Stmt::NullStmtClass:
4276     return ESR_Succeeded;
4277 
4278   case Stmt::DeclStmtClass: {
4279     const DeclStmt *DS = cast<DeclStmt>(S);
4280     for (const auto *DclIt : DS->decls()) {
4281       // Each declaration initialization is its own full-expression.
4282       // FIXME: This isn't quite right; if we're performing aggregate
4283       // initialization, each braced subexpression is its own full-expression.
4284       FullExpressionRAII Scope(Info);
4285       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4286         return ESR_Failed;
4287     }
4288     return ESR_Succeeded;
4289   }
4290 
4291   case Stmt::ReturnStmtClass: {
4292     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4293     FullExpressionRAII Scope(Info);
4294     if (RetExpr &&
4295         !(Result.Slot
4296               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4297               : Evaluate(Result.Value, Info, RetExpr)))
4298       return ESR_Failed;
4299     return ESR_Returned;
4300   }
4301 
4302   case Stmt::CompoundStmtClass: {
4303     BlockScopeRAII Scope(Info);
4304 
4305     const CompoundStmt *CS = cast<CompoundStmt>(S);
4306     for (const auto *BI : CS->body()) {
4307       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4308       if (ESR == ESR_Succeeded)
4309         Case = nullptr;
4310       else if (ESR != ESR_CaseNotFound)
4311         return ESR;
4312     }
4313     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4314   }
4315 
4316   case Stmt::IfStmtClass: {
4317     const IfStmt *IS = cast<IfStmt>(S);
4318 
4319     // Evaluate the condition, as either a var decl or as an expression.
4320     BlockScopeRAII Scope(Info);
4321     if (const Stmt *Init = IS->getInit()) {
4322       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4323       if (ESR != ESR_Succeeded)
4324         return ESR;
4325     }
4326     bool Cond;
4327     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4328       return ESR_Failed;
4329 
4330     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4331       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4332       if (ESR != ESR_Succeeded)
4333         return ESR;
4334     }
4335     return ESR_Succeeded;
4336   }
4337 
4338   case Stmt::WhileStmtClass: {
4339     const WhileStmt *WS = cast<WhileStmt>(S);
4340     while (true) {
4341       BlockScopeRAII Scope(Info);
4342       bool Continue;
4343       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4344                         Continue))
4345         return ESR_Failed;
4346       if (!Continue)
4347         break;
4348 
4349       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4350       if (ESR != ESR_Continue)
4351         return ESR;
4352     }
4353     return ESR_Succeeded;
4354   }
4355 
4356   case Stmt::DoStmtClass: {
4357     const DoStmt *DS = cast<DoStmt>(S);
4358     bool Continue;
4359     do {
4360       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4361       if (ESR != ESR_Continue)
4362         return ESR;
4363       Case = nullptr;
4364 
4365       FullExpressionRAII CondScope(Info);
4366       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4367         return ESR_Failed;
4368     } while (Continue);
4369     return ESR_Succeeded;
4370   }
4371 
4372   case Stmt::ForStmtClass: {
4373     const ForStmt *FS = cast<ForStmt>(S);
4374     BlockScopeRAII Scope(Info);
4375     if (FS->getInit()) {
4376       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4377       if (ESR != ESR_Succeeded)
4378         return ESR;
4379     }
4380     while (true) {
4381       BlockScopeRAII Scope(Info);
4382       bool Continue = true;
4383       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4384                                          FS->getCond(), Continue))
4385         return ESR_Failed;
4386       if (!Continue)
4387         break;
4388 
4389       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4390       if (ESR != ESR_Continue)
4391         return ESR;
4392 
4393       if (FS->getInc()) {
4394         FullExpressionRAII IncScope(Info);
4395         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4396           return ESR_Failed;
4397       }
4398     }
4399     return ESR_Succeeded;
4400   }
4401 
4402   case Stmt::CXXForRangeStmtClass: {
4403     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4404     BlockScopeRAII Scope(Info);
4405 
4406     // Evaluate the init-statement if present.
4407     if (FS->getInit()) {
4408       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4409       if (ESR != ESR_Succeeded)
4410         return ESR;
4411     }
4412 
4413     // Initialize the __range variable.
4414     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4415     if (ESR != ESR_Succeeded)
4416       return ESR;
4417 
4418     // Create the __begin and __end iterators.
4419     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4420     if (ESR != ESR_Succeeded)
4421       return ESR;
4422     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4423     if (ESR != ESR_Succeeded)
4424       return ESR;
4425 
4426     while (true) {
4427       // Condition: __begin != __end.
4428       {
4429         bool Continue = true;
4430         FullExpressionRAII CondExpr(Info);
4431         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4432           return ESR_Failed;
4433         if (!Continue)
4434           break;
4435       }
4436 
4437       // User's variable declaration, initialized by *__begin.
4438       BlockScopeRAII InnerScope(Info);
4439       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4440       if (ESR != ESR_Succeeded)
4441         return ESR;
4442 
4443       // Loop body.
4444       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4445       if (ESR != ESR_Continue)
4446         return ESR;
4447 
4448       // Increment: ++__begin
4449       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4450         return ESR_Failed;
4451     }
4452 
4453     return ESR_Succeeded;
4454   }
4455 
4456   case Stmt::SwitchStmtClass:
4457     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4458 
4459   case Stmt::ContinueStmtClass:
4460     return ESR_Continue;
4461 
4462   case Stmt::BreakStmtClass:
4463     return ESR_Break;
4464 
4465   case Stmt::LabelStmtClass:
4466     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4467 
4468   case Stmt::AttributedStmtClass:
4469     // As a general principle, C++11 attributes can be ignored without
4470     // any semantic impact.
4471     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4472                         Case);
4473 
4474   case Stmt::CaseStmtClass:
4475   case Stmt::DefaultStmtClass:
4476     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4477   case Stmt::CXXTryStmtClass:
4478     // Evaluate try blocks by evaluating all sub statements.
4479     return EvaluateStmt(Result, Info, cast<CXXTryStmt>(S)->getTryBlock(), Case);
4480   }
4481 }
4482 
4483 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4484 /// default constructor. If so, we'll fold it whether or not it's marked as
4485 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4486 /// so we need special handling.
4487 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4488                                            const CXXConstructorDecl *CD,
4489                                            bool IsValueInitialization) {
4490   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4491     return false;
4492 
4493   // Value-initialization does not call a trivial default constructor, so such a
4494   // call is a core constant expression whether or not the constructor is
4495   // constexpr.
4496   if (!CD->isConstexpr() && !IsValueInitialization) {
4497     if (Info.getLangOpts().CPlusPlus11) {
4498       // FIXME: If DiagDecl is an implicitly-declared special member function,
4499       // we should be much more explicit about why it's not constexpr.
4500       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4501         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4502       Info.Note(CD->getLocation(), diag::note_declared_at);
4503     } else {
4504       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4505     }
4506   }
4507   return true;
4508 }
4509 
4510 /// CheckConstexprFunction - Check that a function can be called in a constant
4511 /// expression.
4512 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4513                                    const FunctionDecl *Declaration,
4514                                    const FunctionDecl *Definition,
4515                                    const Stmt *Body) {
4516   // Potential constant expressions can contain calls to declared, but not yet
4517   // defined, constexpr functions.
4518   if (Info.checkingPotentialConstantExpression() && !Definition &&
4519       Declaration->isConstexpr())
4520     return false;
4521 
4522   // Bail out if the function declaration itself is invalid.  We will
4523   // have produced a relevant diagnostic while parsing it, so just
4524   // note the problematic sub-expression.
4525   if (Declaration->isInvalidDecl()) {
4526     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4527     return false;
4528   }
4529 
4530   // DR1872: An instantiated virtual constexpr function can't be called in a
4531   // constant expression (prior to C++20). We can still constant-fold such a
4532   // call.
4533   if (!Info.Ctx.getLangOpts().CPlusPlus2a && isa<CXXMethodDecl>(Declaration) &&
4534       cast<CXXMethodDecl>(Declaration)->isVirtual())
4535     Info.CCEDiag(CallLoc, diag::note_constexpr_virtual_call);
4536 
4537   if (Definition && Definition->isInvalidDecl()) {
4538     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4539     return false;
4540   }
4541 
4542   // Can we evaluate this function call?
4543   if (Definition && Definition->isConstexpr() && Body)
4544     return true;
4545 
4546   if (Info.getLangOpts().CPlusPlus11) {
4547     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4548 
4549     // If this function is not constexpr because it is an inherited
4550     // non-constexpr constructor, diagnose that directly.
4551     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4552     if (CD && CD->isInheritingConstructor()) {
4553       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4554       if (!Inherited->isConstexpr())
4555         DiagDecl = CD = Inherited;
4556     }
4557 
4558     // FIXME: If DiagDecl is an implicitly-declared special member function
4559     // or an inheriting constructor, we should be much more explicit about why
4560     // it's not constexpr.
4561     if (CD && CD->isInheritingConstructor())
4562       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4563         << CD->getInheritedConstructor().getConstructor()->getParent();
4564     else
4565       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4566         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4567     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4568   } else {
4569     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4570   }
4571   return false;
4572 }
4573 
4574 namespace {
4575 struct CheckDynamicTypeHandler {
4576   AccessKinds AccessKind;
4577   typedef bool result_type;
4578   bool failed() { return false; }
4579   bool found(APValue &Subobj, QualType SubobjType) { return true; }
4580   bool found(APSInt &Value, QualType SubobjType) { return true; }
4581   bool found(APFloat &Value, QualType SubobjType) { return true; }
4582 };
4583 } // end anonymous namespace
4584 
4585 /// Check that we can access the notional vptr of an object / determine its
4586 /// dynamic type.
4587 static bool checkDynamicType(EvalInfo &Info, const Expr *E, const LValue &This,
4588                              AccessKinds AK, bool Polymorphic) {
4589   if (This.Designator.Invalid)
4590     return false;
4591 
4592   CompleteObject Obj = findCompleteObject(Info, E, AK, This, QualType());
4593 
4594   if (!Obj)
4595     return false;
4596 
4597   if (!Obj.Value) {
4598     // The object is not usable in constant expressions, so we can't inspect
4599     // its value to see if it's in-lifetime or what the active union members
4600     // are. We can still check for a one-past-the-end lvalue.
4601     if (This.Designator.isOnePastTheEnd() ||
4602         This.Designator.isMostDerivedAnUnsizedArray()) {
4603       Info.FFDiag(E, This.Designator.isOnePastTheEnd()
4604                          ? diag::note_constexpr_access_past_end
4605                          : diag::note_constexpr_access_unsized_array)
4606           << AK;
4607       return false;
4608     } else if (Polymorphic) {
4609       // Conservatively refuse to perform a polymorphic operation if we would
4610       // not be able to read a notional 'vptr' value.
4611       APValue Val;
4612       This.moveInto(Val);
4613       QualType StarThisType =
4614           Info.Ctx.getLValueReferenceType(This.Designator.getType(Info.Ctx));
4615       Info.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
4616           << AK << Val.getAsString(Info.Ctx, StarThisType);
4617       return false;
4618     }
4619     return true;
4620   }
4621 
4622   CheckDynamicTypeHandler Handler{AK};
4623   return Obj && findSubobject(Info, E, Obj, This.Designator, Handler);
4624 }
4625 
4626 /// Check that the pointee of the 'this' pointer in a member function call is
4627 /// either within its lifetime or in its period of construction or destruction.
4628 static bool checkNonVirtualMemberCallThisPointer(EvalInfo &Info, const Expr *E,
4629                                                  const LValue &This) {
4630   return checkDynamicType(Info, E, This, AK_MemberCall, false);
4631 }
4632 
4633 struct DynamicType {
4634   /// The dynamic class type of the object.
4635   const CXXRecordDecl *Type;
4636   /// The corresponding path length in the lvalue.
4637   unsigned PathLength;
4638 };
4639 
4640 static const CXXRecordDecl *getBaseClassType(SubobjectDesignator &Designator,
4641                                              unsigned PathLength) {
4642   assert(PathLength >= Designator.MostDerivedPathLength && PathLength <=
4643       Designator.Entries.size() && "invalid path length");
4644   return (PathLength == Designator.MostDerivedPathLength)
4645              ? Designator.MostDerivedType->getAsCXXRecordDecl()
4646              : getAsBaseClass(Designator.Entries[PathLength - 1]);
4647 }
4648 
4649 /// Determine the dynamic type of an object.
4650 static Optional<DynamicType> ComputeDynamicType(EvalInfo &Info, const Expr *E,
4651                                                 LValue &This, AccessKinds AK) {
4652   // If we don't have an lvalue denoting an object of class type, there is no
4653   // meaningful dynamic type. (We consider objects of non-class type to have no
4654   // dynamic type.)
4655   if (!checkDynamicType(Info, E, This, AK, true))
4656     return None;
4657 
4658   // Refuse to compute a dynamic type in the presence of virtual bases. This
4659   // shouldn't happen other than in constant-folding situations, since literal
4660   // types can't have virtual bases.
4661   //
4662   // Note that consumers of DynamicType assume that the type has no virtual
4663   // bases, and will need modifications if this restriction is relaxed.
4664   const CXXRecordDecl *Class =
4665       This.Designator.MostDerivedType->getAsCXXRecordDecl();
4666   if (!Class || Class->getNumVBases()) {
4667     Info.FFDiag(E);
4668     return None;
4669   }
4670 
4671   // FIXME: For very deep class hierarchies, it might be beneficial to use a
4672   // binary search here instead. But the overwhelmingly common case is that
4673   // we're not in the middle of a constructor, so it probably doesn't matter
4674   // in practice.
4675   ArrayRef<APValue::LValuePathEntry> Path = This.Designator.Entries;
4676   for (unsigned PathLength = This.Designator.MostDerivedPathLength;
4677        PathLength <= Path.size(); ++PathLength) {
4678     switch (Info.isEvaluatingConstructor(This.getLValueBase(),
4679                                          Path.slice(0, PathLength))) {
4680     case ConstructionPhase::Bases:
4681       // We're constructing a base class. This is not the dynamic type.
4682       break;
4683 
4684     case ConstructionPhase::None:
4685     case ConstructionPhase::AfterBases:
4686       // We've finished constructing the base classes, so this is the dynamic
4687       // type.
4688       return DynamicType{getBaseClassType(This.Designator, PathLength),
4689                          PathLength};
4690     }
4691   }
4692 
4693   // CWG issue 1517: we're constructing a base class of the object described by
4694   // 'This', so that object has not yet begun its period of construction and
4695   // any polymorphic operation on it results in undefined behavior.
4696   Info.FFDiag(E);
4697   return None;
4698 }
4699 
4700 /// Perform virtual dispatch.
4701 static const CXXMethodDecl *HandleVirtualDispatch(
4702     EvalInfo &Info, const Expr *E, LValue &This, const CXXMethodDecl *Found,
4703     llvm::SmallVectorImpl<QualType> &CovariantAdjustmentPath) {
4704   Optional<DynamicType> DynType =
4705       ComputeDynamicType(Info, E, This, AK_MemberCall);
4706   if (!DynType)
4707     return nullptr;
4708 
4709   // Find the final overrider. It must be declared in one of the classes on the
4710   // path from the dynamic type to the static type.
4711   // FIXME: If we ever allow literal types to have virtual base classes, that
4712   // won't be true.
4713   const CXXMethodDecl *Callee = Found;
4714   unsigned PathLength = DynType->PathLength;
4715   for (/**/; PathLength <= This.Designator.Entries.size(); ++PathLength) {
4716     const CXXRecordDecl *Class = getBaseClassType(This.Designator, PathLength);
4717     const CXXMethodDecl *Overrider =
4718         Found->getCorrespondingMethodDeclaredInClass(Class, false);
4719     if (Overrider) {
4720       Callee = Overrider;
4721       break;
4722     }
4723   }
4724 
4725   // C++2a [class.abstract]p6:
4726   //   the effect of making a virtual call to a pure virtual function [...] is
4727   //   undefined
4728   if (Callee->isPure()) {
4729     Info.FFDiag(E, diag::note_constexpr_pure_virtual_call, 1) << Callee;
4730     Info.Note(Callee->getLocation(), diag::note_declared_at);
4731     return nullptr;
4732   }
4733 
4734   // If necessary, walk the rest of the path to determine the sequence of
4735   // covariant adjustment steps to apply.
4736   if (!Info.Ctx.hasSameUnqualifiedType(Callee->getReturnType(),
4737                                        Found->getReturnType())) {
4738     CovariantAdjustmentPath.push_back(Callee->getReturnType());
4739     for (unsigned CovariantPathLength = PathLength + 1;
4740          CovariantPathLength != This.Designator.Entries.size();
4741          ++CovariantPathLength) {
4742       const CXXRecordDecl *NextClass =
4743           getBaseClassType(This.Designator, CovariantPathLength);
4744       const CXXMethodDecl *Next =
4745           Found->getCorrespondingMethodDeclaredInClass(NextClass, false);
4746       if (Next && !Info.Ctx.hasSameUnqualifiedType(
4747                       Next->getReturnType(), CovariantAdjustmentPath.back()))
4748         CovariantAdjustmentPath.push_back(Next->getReturnType());
4749     }
4750     if (!Info.Ctx.hasSameUnqualifiedType(Found->getReturnType(),
4751                                          CovariantAdjustmentPath.back()))
4752       CovariantAdjustmentPath.push_back(Found->getReturnType());
4753   }
4754 
4755   // Perform 'this' adjustment.
4756   if (!CastToDerivedClass(Info, E, This, Callee->getParent(), PathLength))
4757     return nullptr;
4758 
4759   return Callee;
4760 }
4761 
4762 /// Perform the adjustment from a value returned by a virtual function to
4763 /// a value of the statically expected type, which may be a pointer or
4764 /// reference to a base class of the returned type.
4765 static bool HandleCovariantReturnAdjustment(EvalInfo &Info, const Expr *E,
4766                                             APValue &Result,
4767                                             ArrayRef<QualType> Path) {
4768   assert(Result.isLValue() &&
4769          "unexpected kind of APValue for covariant return");
4770   if (Result.isNullPointer())
4771     return true;
4772 
4773   LValue LVal;
4774   LVal.setFrom(Info.Ctx, Result);
4775 
4776   const CXXRecordDecl *OldClass = Path[0]->getPointeeCXXRecordDecl();
4777   for (unsigned I = 1; I != Path.size(); ++I) {
4778     const CXXRecordDecl *NewClass = Path[I]->getPointeeCXXRecordDecl();
4779     assert(OldClass && NewClass && "unexpected kind of covariant return");
4780     if (OldClass != NewClass &&
4781         !CastToBaseClass(Info, E, LVal, OldClass, NewClass))
4782       return false;
4783     OldClass = NewClass;
4784   }
4785 
4786   LVal.moveInto(Result);
4787   return true;
4788 }
4789 
4790 /// Determine whether \p Base, which is known to be a direct base class of
4791 /// \p Derived, is a public base class.
4792 static bool isBaseClassPublic(const CXXRecordDecl *Derived,
4793                               const CXXRecordDecl *Base) {
4794   for (const CXXBaseSpecifier &BaseSpec : Derived->bases()) {
4795     auto *BaseClass = BaseSpec.getType()->getAsCXXRecordDecl();
4796     if (BaseClass && declaresSameEntity(BaseClass, Base))
4797       return BaseSpec.getAccessSpecifier() == AS_public;
4798   }
4799   llvm_unreachable("Base is not a direct base of Derived");
4800 }
4801 
4802 /// Apply the given dynamic cast operation on the provided lvalue.
4803 ///
4804 /// This implements the hard case of dynamic_cast, requiring a "runtime check"
4805 /// to find a suitable target subobject.
4806 static bool HandleDynamicCast(EvalInfo &Info, const ExplicitCastExpr *E,
4807                               LValue &Ptr) {
4808   // We can't do anything with a non-symbolic pointer value.
4809   SubobjectDesignator &D = Ptr.Designator;
4810   if (D.Invalid)
4811     return false;
4812 
4813   // C++ [expr.dynamic.cast]p6:
4814   //   If v is a null pointer value, the result is a null pointer value.
4815   if (Ptr.isNullPointer() && !E->isGLValue())
4816     return true;
4817 
4818   // For all the other cases, we need the pointer to point to an object within
4819   // its lifetime / period of construction / destruction, and we need to know
4820   // its dynamic type.
4821   Optional<DynamicType> DynType =
4822       ComputeDynamicType(Info, E, Ptr, AK_DynamicCast);
4823   if (!DynType)
4824     return false;
4825 
4826   // C++ [expr.dynamic.cast]p7:
4827   //   If T is "pointer to cv void", then the result is a pointer to the most
4828   //   derived object
4829   if (E->getType()->isVoidPointerType())
4830     return CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength);
4831 
4832   const CXXRecordDecl *C = E->getTypeAsWritten()->getPointeeCXXRecordDecl();
4833   assert(C && "dynamic_cast target is not void pointer nor class");
4834   CanQualType CQT = Info.Ctx.getCanonicalType(Info.Ctx.getRecordType(C));
4835 
4836   auto RuntimeCheckFailed = [&] (CXXBasePaths *Paths) {
4837     // C++ [expr.dynamic.cast]p9:
4838     if (!E->isGLValue()) {
4839       //   The value of a failed cast to pointer type is the null pointer value
4840       //   of the required result type.
4841       auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
4842       Ptr.setNull(E->getType(), TargetVal);
4843       return true;
4844     }
4845 
4846     //   A failed cast to reference type throws [...] std::bad_cast.
4847     unsigned DiagKind;
4848     if (!Paths && (declaresSameEntity(DynType->Type, C) ||
4849                    DynType->Type->isDerivedFrom(C)))
4850       DiagKind = 0;
4851     else if (!Paths || Paths->begin() == Paths->end())
4852       DiagKind = 1;
4853     else if (Paths->isAmbiguous(CQT))
4854       DiagKind = 2;
4855     else {
4856       assert(Paths->front().Access != AS_public && "why did the cast fail?");
4857       DiagKind = 3;
4858     }
4859     Info.FFDiag(E, diag::note_constexpr_dynamic_cast_to_reference_failed)
4860         << DiagKind << Ptr.Designator.getType(Info.Ctx)
4861         << Info.Ctx.getRecordType(DynType->Type)
4862         << E->getType().getUnqualifiedType();
4863     return false;
4864   };
4865 
4866   // Runtime check, phase 1:
4867   //   Walk from the base subobject towards the derived object looking for the
4868   //   target type.
4869   for (int PathLength = Ptr.Designator.Entries.size();
4870        PathLength >= (int)DynType->PathLength; --PathLength) {
4871     const CXXRecordDecl *Class = getBaseClassType(Ptr.Designator, PathLength);
4872     if (declaresSameEntity(Class, C))
4873       return CastToDerivedClass(Info, E, Ptr, Class, PathLength);
4874     // We can only walk across public inheritance edges.
4875     if (PathLength > (int)DynType->PathLength &&
4876         !isBaseClassPublic(getBaseClassType(Ptr.Designator, PathLength - 1),
4877                            Class))
4878       return RuntimeCheckFailed(nullptr);
4879   }
4880 
4881   // Runtime check, phase 2:
4882   //   Search the dynamic type for an unambiguous public base of type C.
4883   CXXBasePaths Paths(/*FindAmbiguities=*/true,
4884                      /*RecordPaths=*/true, /*DetectVirtual=*/false);
4885   if (DynType->Type->isDerivedFrom(C, Paths) && !Paths.isAmbiguous(CQT) &&
4886       Paths.front().Access == AS_public) {
4887     // Downcast to the dynamic type...
4888     if (!CastToDerivedClass(Info, E, Ptr, DynType->Type, DynType->PathLength))
4889       return false;
4890     // ... then upcast to the chosen base class subobject.
4891     for (CXXBasePathElement &Elem : Paths.front())
4892       if (!HandleLValueBase(Info, E, Ptr, Elem.Class, Elem.Base))
4893         return false;
4894     return true;
4895   }
4896 
4897   // Otherwise, the runtime check fails.
4898   return RuntimeCheckFailed(&Paths);
4899 }
4900 
4901 namespace {
4902 struct StartLifetimeOfUnionMemberHandler {
4903   const FieldDecl *Field;
4904 
4905   static const AccessKinds AccessKind = AK_Assign;
4906 
4907   APValue getDefaultInitValue(QualType SubobjType) {
4908     if (auto *RD = SubobjType->getAsCXXRecordDecl()) {
4909       if (RD->isUnion())
4910         return APValue((const FieldDecl*)nullptr);
4911 
4912       APValue Struct(APValue::UninitStruct(), RD->getNumBases(),
4913                      std::distance(RD->field_begin(), RD->field_end()));
4914 
4915       unsigned Index = 0;
4916       for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4917              End = RD->bases_end(); I != End; ++I, ++Index)
4918         Struct.getStructBase(Index) = getDefaultInitValue(I->getType());
4919 
4920       for (const auto *I : RD->fields()) {
4921         if (I->isUnnamedBitfield())
4922           continue;
4923         Struct.getStructField(I->getFieldIndex()) =
4924             getDefaultInitValue(I->getType());
4925       }
4926       return Struct;
4927     }
4928 
4929     if (auto *AT = dyn_cast_or_null<ConstantArrayType>(
4930             SubobjType->getAsArrayTypeUnsafe())) {
4931       APValue Array(APValue::UninitArray(), 0, AT->getSize().getZExtValue());
4932       if (Array.hasArrayFiller())
4933         Array.getArrayFiller() = getDefaultInitValue(AT->getElementType());
4934       return Array;
4935     }
4936 
4937     return APValue::IndeterminateValue();
4938   }
4939 
4940   typedef bool result_type;
4941   bool failed() { return false; }
4942   bool found(APValue &Subobj, QualType SubobjType) {
4943     // We are supposed to perform no initialization but begin the lifetime of
4944     // the object. We interpret that as meaning to do what default
4945     // initialization of the object would do if all constructors involved were
4946     // trivial:
4947     //  * All base, non-variant member, and array element subobjects' lifetimes
4948     //    begin
4949     //  * No variant members' lifetimes begin
4950     //  * All scalar subobjects whose lifetimes begin have indeterminate values
4951     assert(SubobjType->isUnionType());
4952     if (!declaresSameEntity(Subobj.getUnionField(), Field))
4953       Subobj.setUnion(Field, getDefaultInitValue(Field->getType()));
4954     return true;
4955   }
4956   bool found(APSInt &Value, QualType SubobjType) {
4957     llvm_unreachable("wrong value kind for union object");
4958   }
4959   bool found(APFloat &Value, QualType SubobjType) {
4960     llvm_unreachable("wrong value kind for union object");
4961   }
4962 };
4963 } // end anonymous namespace
4964 
4965 const AccessKinds StartLifetimeOfUnionMemberHandler::AccessKind;
4966 
4967 /// Handle a builtin simple-assignment or a call to a trivial assignment
4968 /// operator whose left-hand side might involve a union member access. If it
4969 /// does, implicitly start the lifetime of any accessed union elements per
4970 /// C++20 [class.union]5.
4971 static bool HandleUnionActiveMemberChange(EvalInfo &Info, const Expr *LHSExpr,
4972                                           const LValue &LHS) {
4973   if (LHS.InvalidBase || LHS.Designator.Invalid)
4974     return false;
4975 
4976   llvm::SmallVector<std::pair<unsigned, const FieldDecl*>, 4> UnionPathLengths;
4977   // C++ [class.union]p5:
4978   //   define the set S(E) of subexpressions of E as follows:
4979   unsigned PathLength = LHS.Designator.Entries.size();
4980   for (const Expr *E = LHSExpr; E != nullptr;) {
4981     //   -- If E is of the form A.B, S(E) contains the elements of S(A)...
4982     if (auto *ME = dyn_cast<MemberExpr>(E)) {
4983       auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
4984       if (!FD)
4985         break;
4986 
4987       //    ... and also contains A.B if B names a union member
4988       if (FD->getParent()->isUnion())
4989         UnionPathLengths.push_back({PathLength - 1, FD});
4990 
4991       E = ME->getBase();
4992       --PathLength;
4993       assert(declaresSameEntity(FD,
4994                                 LHS.Designator.Entries[PathLength]
4995                                     .getAsBaseOrMember().getPointer()));
4996 
4997       //   -- If E is of the form A[B] and is interpreted as a built-in array
4998       //      subscripting operator, S(E) is [S(the array operand, if any)].
4999     } else if (auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
5000       // Step over an ArrayToPointerDecay implicit cast.
5001       auto *Base = ASE->getBase()->IgnoreImplicit();
5002       if (!Base->getType()->isArrayType())
5003         break;
5004 
5005       E = Base;
5006       --PathLength;
5007 
5008     } else if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5009       // Step over a derived-to-base conversion.
5010       E = ICE->getSubExpr();
5011       if (ICE->getCastKind() == CK_NoOp)
5012         continue;
5013       if (ICE->getCastKind() != CK_DerivedToBase &&
5014           ICE->getCastKind() != CK_UncheckedDerivedToBase)
5015         break;
5016       // Walk path backwards as we walk up from the base to the derived class.
5017       for (const CXXBaseSpecifier *Elt : llvm::reverse(ICE->path())) {
5018         --PathLength;
5019         (void)Elt;
5020         assert(declaresSameEntity(Elt->getType()->getAsCXXRecordDecl(),
5021                                   LHS.Designator.Entries[PathLength]
5022                                       .getAsBaseOrMember().getPointer()));
5023       }
5024 
5025     //   -- Otherwise, S(E) is empty.
5026     } else {
5027       break;
5028     }
5029   }
5030 
5031   // Common case: no unions' lifetimes are started.
5032   if (UnionPathLengths.empty())
5033     return true;
5034 
5035   //   if modification of X [would access an inactive union member], an object
5036   //   of the type of X is implicitly created
5037   CompleteObject Obj =
5038       findCompleteObject(Info, LHSExpr, AK_Assign, LHS, LHSExpr->getType());
5039   if (!Obj)
5040     return false;
5041   for (std::pair<unsigned, const FieldDecl *> LengthAndField :
5042            llvm::reverse(UnionPathLengths)) {
5043     // Form a designator for the union object.
5044     SubobjectDesignator D = LHS.Designator;
5045     D.truncate(Info.Ctx, LHS.Base, LengthAndField.first);
5046 
5047     StartLifetimeOfUnionMemberHandler StartLifetime{LengthAndField.second};
5048     if (!findSubobject(Info, LHSExpr, Obj, D, StartLifetime))
5049       return false;
5050   }
5051 
5052   return true;
5053 }
5054 
5055 /// Determine if a class has any fields that might need to be copied by a
5056 /// trivial copy or move operation.
5057 static bool hasFields(const CXXRecordDecl *RD) {
5058   if (!RD || RD->isEmpty())
5059     return false;
5060   for (auto *FD : RD->fields()) {
5061     if (FD->isUnnamedBitfield())
5062       continue;
5063     return true;
5064   }
5065   for (auto &Base : RD->bases())
5066     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
5067       return true;
5068   return false;
5069 }
5070 
5071 namespace {
5072 typedef SmallVector<APValue, 8> ArgVector;
5073 }
5074 
5075 /// EvaluateArgs - Evaluate the arguments to a function call.
5076 static bool EvaluateArgs(ArrayRef<const Expr *> Args, ArgVector &ArgValues,
5077                          EvalInfo &Info, const FunctionDecl *Callee) {
5078   bool Success = true;
5079   llvm::SmallBitVector ForbiddenNullArgs;
5080   if (Callee->hasAttr<NonNullAttr>()) {
5081     ForbiddenNullArgs.resize(Args.size());
5082     for (const auto *Attr : Callee->specific_attrs<NonNullAttr>()) {
5083       if (!Attr->args_size()) {
5084         ForbiddenNullArgs.set();
5085         break;
5086       } else
5087         for (auto Idx : Attr->args()) {
5088           unsigned ASTIdx = Idx.getASTIndex();
5089           if (ASTIdx >= Args.size())
5090             continue;
5091           ForbiddenNullArgs[ASTIdx] = 1;
5092         }
5093     }
5094   }
5095   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
5096        I != E; ++I) {
5097     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
5098       // If we're checking for a potential constant expression, evaluate all
5099       // initializers even if some of them fail.
5100       if (!Info.noteFailure())
5101         return false;
5102       Success = false;
5103     } else if (!ForbiddenNullArgs.empty() &&
5104                ForbiddenNullArgs[I - Args.begin()] &&
5105                ArgValues[I - Args.begin()].isNullPointer()) {
5106       Info.CCEDiag(*I, diag::note_non_null_attribute_failed);
5107       if (!Info.noteFailure())
5108         return false;
5109       Success = false;
5110     }
5111   }
5112   return Success;
5113 }
5114 
5115 /// Evaluate a function call.
5116 static bool HandleFunctionCall(SourceLocation CallLoc,
5117                                const FunctionDecl *Callee, const LValue *This,
5118                                ArrayRef<const Expr*> Args, const Stmt *Body,
5119                                EvalInfo &Info, APValue &Result,
5120                                const LValue *ResultSlot) {
5121   ArgVector ArgValues(Args.size());
5122   if (!EvaluateArgs(Args, ArgValues, Info, Callee))
5123     return false;
5124 
5125   if (!Info.CheckCallLimit(CallLoc))
5126     return false;
5127 
5128   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
5129 
5130   // For a trivial copy or move assignment, perform an APValue copy. This is
5131   // essential for unions, where the operations performed by the assignment
5132   // operator cannot be represented as statements.
5133   //
5134   // Skip this for non-union classes with no fields; in that case, the defaulted
5135   // copy/move does not actually read the object.
5136   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
5137   if (MD && MD->isDefaulted() &&
5138       (MD->getParent()->isUnion() ||
5139        (MD->isTrivial() && hasFields(MD->getParent())))) {
5140     assert(This &&
5141            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
5142     LValue RHS;
5143     RHS.setFrom(Info.Ctx, ArgValues[0]);
5144     APValue RHSValue;
5145     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
5146                                         RHS, RHSValue))
5147       return false;
5148     if (Info.getLangOpts().CPlusPlus2a && MD->isTrivial() &&
5149         !HandleUnionActiveMemberChange(Info, Args[0], *This))
5150       return false;
5151     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(),
5152                           RHSValue))
5153       return false;
5154     This->moveInto(Result);
5155     return true;
5156   } else if (MD && isLambdaCallOperator(MD)) {
5157     // We're in a lambda; determine the lambda capture field maps unless we're
5158     // just constexpr checking a lambda's call operator. constexpr checking is
5159     // done before the captures have been added to the closure object (unless
5160     // we're inferring constexpr-ness), so we don't have access to them in this
5161     // case. But since we don't need the captures to constexpr check, we can
5162     // just ignore them.
5163     if (!Info.checkingPotentialConstantExpression())
5164       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
5165                                         Frame.LambdaThisCaptureField);
5166   }
5167 
5168   StmtResult Ret = {Result, ResultSlot};
5169   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
5170   if (ESR == ESR_Succeeded) {
5171     if (Callee->getReturnType()->isVoidType())
5172       return true;
5173     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
5174   }
5175   return ESR == ESR_Returned;
5176 }
5177 
5178 /// Evaluate a constructor call.
5179 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5180                                   APValue *ArgValues,
5181                                   const CXXConstructorDecl *Definition,
5182                                   EvalInfo &Info, APValue &Result) {
5183   SourceLocation CallLoc = E->getExprLoc();
5184   if (!Info.CheckCallLimit(CallLoc))
5185     return false;
5186 
5187   const CXXRecordDecl *RD = Definition->getParent();
5188   if (RD->getNumVBases()) {
5189     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
5190     return false;
5191   }
5192 
5193   EvalInfo::EvaluatingConstructorRAII EvalObj(
5194       Info,
5195       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
5196       RD->getNumBases());
5197   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
5198 
5199   // FIXME: Creating an APValue just to hold a nonexistent return value is
5200   // wasteful.
5201   APValue RetVal;
5202   StmtResult Ret = {RetVal, nullptr};
5203 
5204   // If it's a delegating constructor, delegate.
5205   if (Definition->isDelegatingConstructor()) {
5206     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
5207     {
5208       FullExpressionRAII InitScope(Info);
5209       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
5210         return false;
5211     }
5212     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5213   }
5214 
5215   // For a trivial copy or move constructor, perform an APValue copy. This is
5216   // essential for unions (or classes with anonymous union members), where the
5217   // operations performed by the constructor cannot be represented by
5218   // ctor-initializers.
5219   //
5220   // Skip this for empty non-union classes; we should not perform an
5221   // lvalue-to-rvalue conversion on them because their copy constructor does not
5222   // actually read them.
5223   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
5224       (Definition->getParent()->isUnion() ||
5225        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
5226     LValue RHS;
5227     RHS.setFrom(Info.Ctx, ArgValues[0]);
5228     return handleLValueToRValueConversion(
5229         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
5230         RHS, Result);
5231   }
5232 
5233   // Reserve space for the struct members.
5234   if (!RD->isUnion() && !Result.hasValue())
5235     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
5236                      std::distance(RD->field_begin(), RD->field_end()));
5237 
5238   if (RD->isInvalidDecl()) return false;
5239   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5240 
5241   // A scope for temporaries lifetime-extended by reference members.
5242   BlockScopeRAII LifetimeExtendedScope(Info);
5243 
5244   bool Success = true;
5245   unsigned BasesSeen = 0;
5246 #ifndef NDEBUG
5247   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
5248 #endif
5249   for (const auto *I : Definition->inits()) {
5250     LValue Subobject = This;
5251     LValue SubobjectParent = This;
5252     APValue *Value = &Result;
5253 
5254     // Determine the subobject to initialize.
5255     FieldDecl *FD = nullptr;
5256     if (I->isBaseInitializer()) {
5257       QualType BaseType(I->getBaseClass(), 0);
5258 #ifndef NDEBUG
5259       // Non-virtual base classes are initialized in the order in the class
5260       // definition. We have already checked for virtual base classes.
5261       assert(!BaseIt->isVirtual() && "virtual base for literal type");
5262       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
5263              "base class initializers not in expected order");
5264       ++BaseIt;
5265 #endif
5266       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
5267                                   BaseType->getAsCXXRecordDecl(), &Layout))
5268         return false;
5269       Value = &Result.getStructBase(BasesSeen++);
5270     } else if ((FD = I->getMember())) {
5271       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
5272         return false;
5273       if (RD->isUnion()) {
5274         Result = APValue(FD);
5275         Value = &Result.getUnionValue();
5276       } else {
5277         Value = &Result.getStructField(FD->getFieldIndex());
5278       }
5279     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
5280       // Walk the indirect field decl's chain to find the object to initialize,
5281       // and make sure we've initialized every step along it.
5282       auto IndirectFieldChain = IFD->chain();
5283       for (auto *C : IndirectFieldChain) {
5284         FD = cast<FieldDecl>(C);
5285         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
5286         // Switch the union field if it differs. This happens if we had
5287         // preceding zero-initialization, and we're now initializing a union
5288         // subobject other than the first.
5289         // FIXME: In this case, the values of the other subobjects are
5290         // specified, since zero-initialization sets all padding bits to zero.
5291         if (!Value->hasValue() ||
5292             (Value->isUnion() && Value->getUnionField() != FD)) {
5293           if (CD->isUnion())
5294             *Value = APValue(FD);
5295           else
5296             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
5297                              std::distance(CD->field_begin(), CD->field_end()));
5298         }
5299         // Store Subobject as its parent before updating it for the last element
5300         // in the chain.
5301         if (C == IndirectFieldChain.back())
5302           SubobjectParent = Subobject;
5303         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
5304           return false;
5305         if (CD->isUnion())
5306           Value = &Value->getUnionValue();
5307         else
5308           Value = &Value->getStructField(FD->getFieldIndex());
5309       }
5310     } else {
5311       llvm_unreachable("unknown base initializer kind");
5312     }
5313 
5314     // Need to override This for implicit field initializers as in this case
5315     // This refers to innermost anonymous struct/union containing initializer,
5316     // not to currently constructed class.
5317     const Expr *Init = I->getInit();
5318     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
5319                                   isa<CXXDefaultInitExpr>(Init));
5320     FullExpressionRAII InitScope(Info);
5321     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
5322         (FD && FD->isBitField() &&
5323          !truncateBitfieldValue(Info, Init, *Value, FD))) {
5324       // If we're checking for a potential constant expression, evaluate all
5325       // initializers even if some of them fail.
5326       if (!Info.noteFailure())
5327         return false;
5328       Success = false;
5329     }
5330 
5331     // This is the point at which the dynamic type of the object becomes this
5332     // class type.
5333     if (I->isBaseInitializer() && BasesSeen == RD->getNumBases())
5334       EvalObj.finishedConstructingBases();
5335   }
5336 
5337   return Success &&
5338          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
5339 }
5340 
5341 static bool HandleConstructorCall(const Expr *E, const LValue &This,
5342                                   ArrayRef<const Expr*> Args,
5343                                   const CXXConstructorDecl *Definition,
5344                                   EvalInfo &Info, APValue &Result) {
5345   ArgVector ArgValues(Args.size());
5346   if (!EvaluateArgs(Args, ArgValues, Info, Definition))
5347     return false;
5348 
5349   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
5350                                Info, Result);
5351 }
5352 
5353 //===----------------------------------------------------------------------===//
5354 // Generic Evaluation
5355 //===----------------------------------------------------------------------===//
5356 namespace {
5357 
5358 class BitCastBuffer {
5359   // FIXME: We're going to need bit-level granularity when we support
5360   // bit-fields.
5361   // FIXME: Its possible under the C++ standard for 'char' to not be 8 bits, but
5362   // we don't support a host or target where that is the case. Still, we should
5363   // use a more generic type in case we ever do.
5364   SmallVector<Optional<unsigned char>, 32> Bytes;
5365 
5366   static_assert(std::numeric_limits<unsigned char>::digits >= 8,
5367                 "Need at least 8 bit unsigned char");
5368 
5369   bool TargetIsLittleEndian;
5370 
5371 public:
5372   BitCastBuffer(CharUnits Width, bool TargetIsLittleEndian)
5373       : Bytes(Width.getQuantity()),
5374         TargetIsLittleEndian(TargetIsLittleEndian) {}
5375 
5376   LLVM_NODISCARD
5377   bool readObject(CharUnits Offset, CharUnits Width,
5378                   SmallVectorImpl<unsigned char> &Output) const {
5379     for (CharUnits I = Offset, E = Offset + Width; I != E; ++I) {
5380       // If a byte of an integer is uninitialized, then the whole integer is
5381       // uninitalized.
5382       if (!Bytes[I.getQuantity()])
5383         return false;
5384       Output.push_back(*Bytes[I.getQuantity()]);
5385     }
5386     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5387       std::reverse(Output.begin(), Output.end());
5388     return true;
5389   }
5390 
5391   void writeObject(CharUnits Offset, SmallVectorImpl<unsigned char> &Input) {
5392     if (llvm::sys::IsLittleEndianHost != TargetIsLittleEndian)
5393       std::reverse(Input.begin(), Input.end());
5394 
5395     size_t Index = 0;
5396     for (unsigned char Byte : Input) {
5397       assert(!Bytes[Offset.getQuantity() + Index] && "overwriting a byte?");
5398       Bytes[Offset.getQuantity() + Index] = Byte;
5399       ++Index;
5400     }
5401   }
5402 
5403   size_t size() { return Bytes.size(); }
5404 };
5405 
5406 /// Traverse an APValue to produce an BitCastBuffer, emulating how the current
5407 /// target would represent the value at runtime.
5408 class APValueToBufferConverter {
5409   EvalInfo &Info;
5410   BitCastBuffer Buffer;
5411   const CastExpr *BCE;
5412 
5413   APValueToBufferConverter(EvalInfo &Info, CharUnits ObjectWidth,
5414                            const CastExpr *BCE)
5415       : Info(Info),
5416         Buffer(ObjectWidth, Info.Ctx.getTargetInfo().isLittleEndian()),
5417         BCE(BCE) {}
5418 
5419   bool visit(const APValue &Val, QualType Ty) {
5420     return visit(Val, Ty, CharUnits::fromQuantity(0));
5421   }
5422 
5423   // Write out Val with type Ty into Buffer starting at Offset.
5424   bool visit(const APValue &Val, QualType Ty, CharUnits Offset) {
5425     assert((size_t)Offset.getQuantity() <= Buffer.size());
5426 
5427     // As a special case, nullptr_t has an indeterminate value.
5428     if (Ty->isNullPtrType())
5429       return true;
5430 
5431     // Dig through Src to find the byte at SrcOffset.
5432     switch (Val.getKind()) {
5433     case APValue::Indeterminate:
5434     case APValue::None:
5435       return true;
5436 
5437     case APValue::Int:
5438       return visitInt(Val.getInt(), Ty, Offset);
5439     case APValue::Float:
5440       return visitFloat(Val.getFloat(), Ty, Offset);
5441     case APValue::Array:
5442       return visitArray(Val, Ty, Offset);
5443     case APValue::Struct:
5444       return visitRecord(Val, Ty, Offset);
5445 
5446     case APValue::ComplexInt:
5447     case APValue::ComplexFloat:
5448     case APValue::Vector:
5449     case APValue::FixedPoint:
5450       // FIXME: We should support these.
5451 
5452     case APValue::Union:
5453     case APValue::MemberPointer:
5454     case APValue::AddrLabelDiff: {
5455       Info.FFDiag(BCE->getBeginLoc(),
5456                   diag::note_constexpr_bit_cast_unsupported_type)
5457           << Ty;
5458       return false;
5459     }
5460 
5461     case APValue::LValue:
5462       llvm_unreachable("LValue subobject in bit_cast?");
5463     }
5464     llvm_unreachable("Unhandled APValue::ValueKind");
5465   }
5466 
5467   bool visitRecord(const APValue &Val, QualType Ty, CharUnits Offset) {
5468     const RecordDecl *RD = Ty->getAsRecordDecl();
5469     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5470 
5471     // Visit the base classes.
5472     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5473       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5474         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5475         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5476 
5477         if (!visitRecord(Val.getStructBase(I), BS.getType(),
5478                          Layout.getBaseClassOffset(BaseDecl) + Offset))
5479           return false;
5480       }
5481     }
5482 
5483     // Visit the fields.
5484     unsigned FieldIdx = 0;
5485     for (FieldDecl *FD : RD->fields()) {
5486       if (FD->isBitField()) {
5487         Info.FFDiag(BCE->getBeginLoc(),
5488                     diag::note_constexpr_bit_cast_unsupported_bitfield);
5489         return false;
5490       }
5491 
5492       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5493 
5494       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0 &&
5495              "only bit-fields can have sub-char alignment");
5496       CharUnits FieldOffset =
5497           Info.Ctx.toCharUnitsFromBits(FieldOffsetBits) + Offset;
5498       QualType FieldTy = FD->getType();
5499       if (!visit(Val.getStructField(FieldIdx), FieldTy, FieldOffset))
5500         return false;
5501       ++FieldIdx;
5502     }
5503 
5504     return true;
5505   }
5506 
5507   bool visitArray(const APValue &Val, QualType Ty, CharUnits Offset) {
5508     const auto *CAT =
5509         dyn_cast_or_null<ConstantArrayType>(Ty->getAsArrayTypeUnsafe());
5510     if (!CAT)
5511       return false;
5512 
5513     CharUnits ElemWidth = Info.Ctx.getTypeSizeInChars(CAT->getElementType());
5514     unsigned NumInitializedElts = Val.getArrayInitializedElts();
5515     unsigned ArraySize = Val.getArraySize();
5516     // First, initialize the initialized elements.
5517     for (unsigned I = 0; I != NumInitializedElts; ++I) {
5518       const APValue &SubObj = Val.getArrayInitializedElt(I);
5519       if (!visit(SubObj, CAT->getElementType(), Offset + I * ElemWidth))
5520         return false;
5521     }
5522 
5523     // Next, initialize the rest of the array using the filler.
5524     if (Val.hasArrayFiller()) {
5525       const APValue &Filler = Val.getArrayFiller();
5526       for (unsigned I = NumInitializedElts; I != ArraySize; ++I) {
5527         if (!visit(Filler, CAT->getElementType(), Offset + I * ElemWidth))
5528           return false;
5529       }
5530     }
5531 
5532     return true;
5533   }
5534 
5535   bool visitInt(const APSInt &Val, QualType Ty, CharUnits Offset) {
5536     CharUnits Width = Info.Ctx.getTypeSizeInChars(Ty);
5537     SmallVector<unsigned char, 8> Bytes(Width.getQuantity());
5538     llvm::StoreIntToMemory(Val, &*Bytes.begin(), Width.getQuantity());
5539     Buffer.writeObject(Offset, Bytes);
5540     return true;
5541   }
5542 
5543   bool visitFloat(const APFloat &Val, QualType Ty, CharUnits Offset) {
5544     APSInt AsInt(Val.bitcastToAPInt());
5545     return visitInt(AsInt, Ty, Offset);
5546   }
5547 
5548 public:
5549   static Optional<BitCastBuffer> convert(EvalInfo &Info, const APValue &Src,
5550                                          const CastExpr *BCE) {
5551     CharUnits DstSize = Info.Ctx.getTypeSizeInChars(BCE->getType());
5552     APValueToBufferConverter Converter(Info, DstSize, BCE);
5553     if (!Converter.visit(Src, BCE->getSubExpr()->getType()))
5554       return None;
5555     return Converter.Buffer;
5556   }
5557 };
5558 
5559 /// Write an BitCastBuffer into an APValue.
5560 class BufferToAPValueConverter {
5561   EvalInfo &Info;
5562   const BitCastBuffer &Buffer;
5563   const CastExpr *BCE;
5564 
5565   BufferToAPValueConverter(EvalInfo &Info, const BitCastBuffer &Buffer,
5566                            const CastExpr *BCE)
5567       : Info(Info), Buffer(Buffer), BCE(BCE) {}
5568 
5569   // Emit an unsupported bit_cast type error. Sema refuses to build a bit_cast
5570   // with an invalid type, so anything left is a deficiency on our part (FIXME).
5571   // Ideally this will be unreachable.
5572   llvm::NoneType unsupportedType(QualType Ty) {
5573     Info.FFDiag(BCE->getBeginLoc(),
5574                 diag::note_constexpr_bit_cast_unsupported_type)
5575         << Ty;
5576     return None;
5577   }
5578 
5579   Optional<APValue> visit(const BuiltinType *T, CharUnits Offset,
5580                           const EnumType *EnumSugar = nullptr) {
5581     if (T->isNullPtrType()) {
5582       uint64_t NullValue = Info.Ctx.getTargetNullPointerValue(QualType(T, 0));
5583       return APValue((Expr *)nullptr,
5584                      /*Offset=*/CharUnits::fromQuantity(NullValue),
5585                      APValue::NoLValuePath{}, /*IsNullPtr=*/true);
5586     }
5587 
5588     CharUnits SizeOf = Info.Ctx.getTypeSizeInChars(T);
5589     SmallVector<uint8_t, 8> Bytes;
5590     if (!Buffer.readObject(Offset, SizeOf, Bytes)) {
5591       // If this is std::byte or unsigned char, then its okay to store an
5592       // indeterminate value.
5593       bool IsStdByte = EnumSugar && EnumSugar->isStdByteType();
5594       bool IsUChar =
5595           !EnumSugar && (T->isSpecificBuiltinType(BuiltinType::UChar) ||
5596                          T->isSpecificBuiltinType(BuiltinType::Char_U));
5597       if (!IsStdByte && !IsUChar) {
5598         QualType DisplayType(EnumSugar ? (const Type *)EnumSugar : T, 0);
5599         Info.FFDiag(BCE->getExprLoc(),
5600                     diag::note_constexpr_bit_cast_indet_dest)
5601             << DisplayType << Info.Ctx.getLangOpts().CharIsSigned;
5602         return None;
5603       }
5604 
5605       return APValue::IndeterminateValue();
5606     }
5607 
5608     APSInt Val(SizeOf.getQuantity() * Info.Ctx.getCharWidth(), true);
5609     llvm::LoadIntFromMemory(Val, &*Bytes.begin(), Bytes.size());
5610 
5611     if (T->isIntegralOrEnumerationType()) {
5612       Val.setIsSigned(T->isSignedIntegerOrEnumerationType());
5613       return APValue(Val);
5614     }
5615 
5616     if (T->isRealFloatingType()) {
5617       const llvm::fltSemantics &Semantics =
5618           Info.Ctx.getFloatTypeSemantics(QualType(T, 0));
5619       return APValue(APFloat(Semantics, Val));
5620     }
5621 
5622     return unsupportedType(QualType(T, 0));
5623   }
5624 
5625   Optional<APValue> visit(const RecordType *RTy, CharUnits Offset) {
5626     const RecordDecl *RD = RTy->getAsRecordDecl();
5627     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5628 
5629     unsigned NumBases = 0;
5630     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD))
5631       NumBases = CXXRD->getNumBases();
5632 
5633     APValue ResultVal(APValue::UninitStruct(), NumBases,
5634                       std::distance(RD->field_begin(), RD->field_end()));
5635 
5636     // Visit the base classes.
5637     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
5638       for (size_t I = 0, E = CXXRD->getNumBases(); I != E; ++I) {
5639         const CXXBaseSpecifier &BS = CXXRD->bases_begin()[I];
5640         CXXRecordDecl *BaseDecl = BS.getType()->getAsCXXRecordDecl();
5641         if (BaseDecl->isEmpty() ||
5642             Info.Ctx.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
5643           continue;
5644 
5645         Optional<APValue> SubObj = visitType(
5646             BS.getType(), Layout.getBaseClassOffset(BaseDecl) + Offset);
5647         if (!SubObj)
5648           return None;
5649         ResultVal.getStructBase(I) = *SubObj;
5650       }
5651     }
5652 
5653     // Visit the fields.
5654     unsigned FieldIdx = 0;
5655     for (FieldDecl *FD : RD->fields()) {
5656       // FIXME: We don't currently support bit-fields. A lot of the logic for
5657       // this is in CodeGen, so we need to factor it around.
5658       if (FD->isBitField()) {
5659         Info.FFDiag(BCE->getBeginLoc(),
5660                     diag::note_constexpr_bit_cast_unsupported_bitfield);
5661         return None;
5662       }
5663 
5664       uint64_t FieldOffsetBits = Layout.getFieldOffset(FieldIdx);
5665       assert(FieldOffsetBits % Info.Ctx.getCharWidth() == 0);
5666 
5667       CharUnits FieldOffset =
5668           CharUnits::fromQuantity(FieldOffsetBits / Info.Ctx.getCharWidth()) +
5669           Offset;
5670       QualType FieldTy = FD->getType();
5671       Optional<APValue> SubObj = visitType(FieldTy, FieldOffset);
5672       if (!SubObj)
5673         return None;
5674       ResultVal.getStructField(FieldIdx) = *SubObj;
5675       ++FieldIdx;
5676     }
5677 
5678     return ResultVal;
5679   }
5680 
5681   Optional<APValue> visit(const EnumType *Ty, CharUnits Offset) {
5682     QualType RepresentationType = Ty->getDecl()->getIntegerType();
5683     assert(!RepresentationType.isNull() &&
5684            "enum forward decl should be caught by Sema");
5685     const BuiltinType *AsBuiltin =
5686         RepresentationType.getCanonicalType()->getAs<BuiltinType>();
5687     assert(AsBuiltin && "non-integral enum underlying type?");
5688     // Recurse into the underlying type. Treat std::byte transparently as
5689     // unsigned char.
5690     return visit(AsBuiltin, Offset, /*EnumTy=*/Ty);
5691   }
5692 
5693   Optional<APValue> visit(const ConstantArrayType *Ty, CharUnits Offset) {
5694     size_t Size = Ty->getSize().getLimitedValue();
5695     CharUnits ElementWidth = Info.Ctx.getTypeSizeInChars(Ty->getElementType());
5696 
5697     APValue ArrayValue(APValue::UninitArray(), Size, Size);
5698     for (size_t I = 0; I != Size; ++I) {
5699       Optional<APValue> ElementValue =
5700           visitType(Ty->getElementType(), Offset + I * ElementWidth);
5701       if (!ElementValue)
5702         return None;
5703       ArrayValue.getArrayInitializedElt(I) = std::move(*ElementValue);
5704     }
5705 
5706     return ArrayValue;
5707   }
5708 
5709   Optional<APValue> visit(const Type *Ty, CharUnits Offset) {
5710     return unsupportedType(QualType(Ty, 0));
5711   }
5712 
5713   Optional<APValue> visitType(QualType Ty, CharUnits Offset) {
5714     QualType Can = Ty.getCanonicalType();
5715 
5716     switch (Can->getTypeClass()) {
5717 #define TYPE(Class, Base)                                                      \
5718   case Type::Class:                                                            \
5719     return visit(cast<Class##Type>(Can.getTypePtr()), Offset);
5720 #define ABSTRACT_TYPE(Class, Base)
5721 #define NON_CANONICAL_TYPE(Class, Base)                                        \
5722   case Type::Class:                                                            \
5723     llvm_unreachable("non-canonical type should be impossible!");
5724 #define DEPENDENT_TYPE(Class, Base)                                            \
5725   case Type::Class:                                                            \
5726     llvm_unreachable(                                                          \
5727         "dependent types aren't supported in the constant evaluator!");
5728 #define NON_CANONICAL_UNLESS_DEPENDENT(Class, Base)                            \
5729   case Type::Class:                                                            \
5730     llvm_unreachable("either dependent or not canonical!");
5731 #include "clang/AST/TypeNodes.def"
5732     }
5733     llvm_unreachable("Unhandled Type::TypeClass");
5734   }
5735 
5736 public:
5737   // Pull out a full value of type DstType.
5738   static Optional<APValue> convert(EvalInfo &Info, BitCastBuffer &Buffer,
5739                                    const CastExpr *BCE) {
5740     BufferToAPValueConverter Converter(Info, Buffer, BCE);
5741     return Converter.visitType(BCE->getType(), CharUnits::fromQuantity(0));
5742   }
5743 };
5744 
5745 static bool checkBitCastConstexprEligibilityType(SourceLocation Loc,
5746                                                  QualType Ty, EvalInfo *Info,
5747                                                  const ASTContext &Ctx,
5748                                                  bool CheckingDest) {
5749   Ty = Ty.getCanonicalType();
5750 
5751   auto diag = [&](int Reason) {
5752     if (Info)
5753       Info->FFDiag(Loc, diag::note_constexpr_bit_cast_invalid_type)
5754           << CheckingDest << (Reason == 4) << Reason;
5755     return false;
5756   };
5757   auto note = [&](int Construct, QualType NoteTy, SourceLocation NoteLoc) {
5758     if (Info)
5759       Info->Note(NoteLoc, diag::note_constexpr_bit_cast_invalid_subtype)
5760           << NoteTy << Construct << Ty;
5761     return false;
5762   };
5763 
5764   if (Ty->isUnionType())
5765     return diag(0);
5766   if (Ty->isPointerType())
5767     return diag(1);
5768   if (Ty->isMemberPointerType())
5769     return diag(2);
5770   if (Ty.isVolatileQualified())
5771     return diag(3);
5772 
5773   if (RecordDecl *Record = Ty->getAsRecordDecl()) {
5774     if (auto *CXXRD = dyn_cast<CXXRecordDecl>(Record)) {
5775       for (CXXBaseSpecifier &BS : CXXRD->bases())
5776         if (!checkBitCastConstexprEligibilityType(Loc, BS.getType(), Info, Ctx,
5777                                                   CheckingDest))
5778           return note(1, BS.getType(), BS.getBeginLoc());
5779     }
5780     for (FieldDecl *FD : Record->fields()) {
5781       if (FD->getType()->isReferenceType())
5782         return diag(4);
5783       if (!checkBitCastConstexprEligibilityType(Loc, FD->getType(), Info, Ctx,
5784                                                 CheckingDest))
5785         return note(0, FD->getType(), FD->getBeginLoc());
5786     }
5787   }
5788 
5789   if (Ty->isArrayType() &&
5790       !checkBitCastConstexprEligibilityType(Loc, Ctx.getBaseElementType(Ty),
5791                                             Info, Ctx, CheckingDest))
5792     return false;
5793 
5794   return true;
5795 }
5796 
5797 static bool checkBitCastConstexprEligibility(EvalInfo *Info,
5798                                              const ASTContext &Ctx,
5799                                              const CastExpr *BCE) {
5800   bool DestOK = checkBitCastConstexprEligibilityType(
5801       BCE->getBeginLoc(), BCE->getType(), Info, Ctx, true);
5802   bool SourceOK = DestOK && checkBitCastConstexprEligibilityType(
5803                                 BCE->getBeginLoc(),
5804                                 BCE->getSubExpr()->getType(), Info, Ctx, false);
5805   return SourceOK;
5806 }
5807 
5808 static bool handleLValueToRValueBitCast(EvalInfo &Info, APValue &DestValue,
5809                                         APValue &SourceValue,
5810                                         const CastExpr *BCE) {
5811   assert(CHAR_BIT == 8 && Info.Ctx.getTargetInfo().getCharWidth() == 8 &&
5812          "no host or target supports non 8-bit chars");
5813   assert(SourceValue.isLValue() &&
5814          "LValueToRValueBitcast requires an lvalue operand!");
5815 
5816   if (!checkBitCastConstexprEligibility(&Info, Info.Ctx, BCE))
5817     return false;
5818 
5819   LValue SourceLValue;
5820   APValue SourceRValue;
5821   SourceLValue.setFrom(Info.Ctx, SourceValue);
5822   if (!handleLValueToRValueConversion(Info, BCE,
5823                                       BCE->getSubExpr()->getType().withConst(),
5824                                       SourceLValue, SourceRValue))
5825     return false;
5826 
5827   // Read out SourceValue into a char buffer.
5828   Optional<BitCastBuffer> Buffer =
5829       APValueToBufferConverter::convert(Info, SourceRValue, BCE);
5830   if (!Buffer)
5831     return false;
5832 
5833   // Write out the buffer into a new APValue.
5834   Optional<APValue> MaybeDestValue =
5835       BufferToAPValueConverter::convert(Info, *Buffer, BCE);
5836   if (!MaybeDestValue)
5837     return false;
5838 
5839   DestValue = std::move(*MaybeDestValue);
5840   return true;
5841 }
5842 
5843 template <class Derived>
5844 class ExprEvaluatorBase
5845   : public ConstStmtVisitor<Derived, bool> {
5846 private:
5847   Derived &getDerived() { return static_cast<Derived&>(*this); }
5848   bool DerivedSuccess(const APValue &V, const Expr *E) {
5849     return getDerived().Success(V, E);
5850   }
5851   bool DerivedZeroInitialization(const Expr *E) {
5852     return getDerived().ZeroInitialization(E);
5853   }
5854 
5855   // Check whether a conditional operator with a non-constant condition is a
5856   // potential constant expression. If neither arm is a potential constant
5857   // expression, then the conditional operator is not either.
5858   template<typename ConditionalOperator>
5859   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
5860     assert(Info.checkingPotentialConstantExpression());
5861 
5862     // Speculatively evaluate both arms.
5863     SmallVector<PartialDiagnosticAt, 8> Diag;
5864     {
5865       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5866       StmtVisitorTy::Visit(E->getFalseExpr());
5867       if (Diag.empty())
5868         return;
5869     }
5870 
5871     {
5872       SpeculativeEvaluationRAII Speculate(Info, &Diag);
5873       Diag.clear();
5874       StmtVisitorTy::Visit(E->getTrueExpr());
5875       if (Diag.empty())
5876         return;
5877     }
5878 
5879     Error(E, diag::note_constexpr_conditional_never_const);
5880   }
5881 
5882 
5883   template<typename ConditionalOperator>
5884   bool HandleConditionalOperator(const ConditionalOperator *E) {
5885     bool BoolResult;
5886     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
5887       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
5888         CheckPotentialConstantConditional(E);
5889         return false;
5890       }
5891       if (Info.noteFailure()) {
5892         StmtVisitorTy::Visit(E->getTrueExpr());
5893         StmtVisitorTy::Visit(E->getFalseExpr());
5894       }
5895       return false;
5896     }
5897 
5898     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
5899     return StmtVisitorTy::Visit(EvalExpr);
5900   }
5901 
5902 protected:
5903   EvalInfo &Info;
5904   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
5905   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
5906 
5907   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
5908     return Info.CCEDiag(E, D);
5909   }
5910 
5911   bool ZeroInitialization(const Expr *E) { return Error(E); }
5912 
5913 public:
5914   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
5915 
5916   EvalInfo &getEvalInfo() { return Info; }
5917 
5918   /// Report an evaluation error. This should only be called when an error is
5919   /// first discovered. When propagating an error, just return false.
5920   bool Error(const Expr *E, diag::kind D) {
5921     Info.FFDiag(E, D);
5922     return false;
5923   }
5924   bool Error(const Expr *E) {
5925     return Error(E, diag::note_invalid_subexpr_in_const_expr);
5926   }
5927 
5928   bool VisitStmt(const Stmt *) {
5929     llvm_unreachable("Expression evaluator should not be called on stmts");
5930   }
5931   bool VisitExpr(const Expr *E) {
5932     return Error(E);
5933   }
5934 
5935   bool VisitConstantExpr(const ConstantExpr *E)
5936     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5937   bool VisitParenExpr(const ParenExpr *E)
5938     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5939   bool VisitUnaryExtension(const UnaryOperator *E)
5940     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5941   bool VisitUnaryPlus(const UnaryOperator *E)
5942     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5943   bool VisitChooseExpr(const ChooseExpr *E)
5944     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
5945   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
5946     { return StmtVisitorTy::Visit(E->getResultExpr()); }
5947   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
5948     { return StmtVisitorTy::Visit(E->getReplacement()); }
5949   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
5950     TempVersionRAII RAII(*Info.CurrentCall);
5951     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5952     return StmtVisitorTy::Visit(E->getExpr());
5953   }
5954   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
5955     TempVersionRAII RAII(*Info.CurrentCall);
5956     // The initializer may not have been parsed yet, or might be erroneous.
5957     if (!E->getExpr())
5958       return Error(E);
5959     SourceLocExprScopeGuard Guard(E, Info.CurrentCall->CurSourceLocExprScope);
5960     return StmtVisitorTy::Visit(E->getExpr());
5961   }
5962 
5963   // We cannot create any objects for which cleanups are required, so there is
5964   // nothing to do here; all cleanups must come from unevaluated subexpressions.
5965   bool VisitExprWithCleanups(const ExprWithCleanups *E)
5966     { return StmtVisitorTy::Visit(E->getSubExpr()); }
5967 
5968   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
5969     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
5970     return static_cast<Derived*>(this)->VisitCastExpr(E);
5971   }
5972   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
5973     if (!Info.Ctx.getLangOpts().CPlusPlus2a)
5974       CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
5975     return static_cast<Derived*>(this)->VisitCastExpr(E);
5976   }
5977   bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E) {
5978     return static_cast<Derived*>(this)->VisitCastExpr(E);
5979   }
5980 
5981   bool VisitBinaryOperator(const BinaryOperator *E) {
5982     switch (E->getOpcode()) {
5983     default:
5984       return Error(E);
5985 
5986     case BO_Comma:
5987       VisitIgnoredValue(E->getLHS());
5988       return StmtVisitorTy::Visit(E->getRHS());
5989 
5990     case BO_PtrMemD:
5991     case BO_PtrMemI: {
5992       LValue Obj;
5993       if (!HandleMemberPointerAccess(Info, E, Obj))
5994         return false;
5995       APValue Result;
5996       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
5997         return false;
5998       return DerivedSuccess(Result, E);
5999     }
6000     }
6001   }
6002 
6003   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
6004     // Evaluate and cache the common expression. We treat it as a temporary,
6005     // even though it's not quite the same thing.
6006     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
6007                   Info, E->getCommon()))
6008       return false;
6009 
6010     return HandleConditionalOperator(E);
6011   }
6012 
6013   bool VisitConditionalOperator(const ConditionalOperator *E) {
6014     bool IsBcpCall = false;
6015     // If the condition (ignoring parens) is a __builtin_constant_p call,
6016     // the result is a constant expression if it can be folded without
6017     // side-effects. This is an important GNU extension. See GCC PR38377
6018     // for discussion.
6019     if (const CallExpr *CallCE =
6020           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
6021       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
6022         IsBcpCall = true;
6023 
6024     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
6025     // constant expression; we can't check whether it's potentially foldable.
6026     // FIXME: We should instead treat __builtin_constant_p as non-constant if
6027     // it would return 'false' in this mode.
6028     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
6029       return false;
6030 
6031     FoldConstant Fold(Info, IsBcpCall);
6032     if (!HandleConditionalOperator(E)) {
6033       Fold.keepDiagnostics();
6034       return false;
6035     }
6036 
6037     return true;
6038   }
6039 
6040   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
6041     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
6042       return DerivedSuccess(*Value, E);
6043 
6044     const Expr *Source = E->getSourceExpr();
6045     if (!Source)
6046       return Error(E);
6047     if (Source == E) { // sanity checking.
6048       assert(0 && "OpaqueValueExpr recursively refers to itself");
6049       return Error(E);
6050     }
6051     return StmtVisitorTy::Visit(Source);
6052   }
6053 
6054   bool VisitCallExpr(const CallExpr *E) {
6055     APValue Result;
6056     if (!handleCallExpr(E, Result, nullptr))
6057       return false;
6058     return DerivedSuccess(Result, E);
6059   }
6060 
6061   bool handleCallExpr(const CallExpr *E, APValue &Result,
6062                      const LValue *ResultSlot) {
6063     const Expr *Callee = E->getCallee()->IgnoreParens();
6064     QualType CalleeType = Callee->getType();
6065 
6066     const FunctionDecl *FD = nullptr;
6067     LValue *This = nullptr, ThisVal;
6068     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6069     bool HasQualifier = false;
6070 
6071     // Extract function decl and 'this' pointer from the callee.
6072     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
6073       const CXXMethodDecl *Member = nullptr;
6074       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
6075         // Explicit bound member calls, such as x.f() or p->g();
6076         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
6077           return false;
6078         Member = dyn_cast<CXXMethodDecl>(ME->getMemberDecl());
6079         if (!Member)
6080           return Error(Callee);
6081         This = &ThisVal;
6082         HasQualifier = ME->hasQualifier();
6083       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
6084         // Indirect bound member calls ('.*' or '->*').
6085         Member = dyn_cast_or_null<CXXMethodDecl>(
6086             HandleMemberPointerAccess(Info, BE, ThisVal, false));
6087         if (!Member)
6088           return Error(Callee);
6089         This = &ThisVal;
6090       } else
6091         return Error(Callee);
6092       FD = Member;
6093     } else if (CalleeType->isFunctionPointerType()) {
6094       LValue Call;
6095       if (!EvaluatePointer(Callee, Call, Info))
6096         return false;
6097 
6098       if (!Call.getLValueOffset().isZero())
6099         return Error(Callee);
6100       FD = dyn_cast_or_null<FunctionDecl>(
6101                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
6102       if (!FD)
6103         return Error(Callee);
6104       // Don't call function pointers which have been cast to some other type.
6105       // Per DR (no number yet), the caller and callee can differ in noexcept.
6106       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
6107         CalleeType->getPointeeType(), FD->getType())) {
6108         return Error(E);
6109       }
6110 
6111       // Overloaded operator calls to member functions are represented as normal
6112       // calls with '*this' as the first argument.
6113       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6114       if (MD && !MD->isStatic()) {
6115         // FIXME: When selecting an implicit conversion for an overloaded
6116         // operator delete, we sometimes try to evaluate calls to conversion
6117         // operators without a 'this' parameter!
6118         if (Args.empty())
6119           return Error(E);
6120 
6121         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
6122           return false;
6123         This = &ThisVal;
6124         Args = Args.slice(1);
6125       } else if (MD && MD->isLambdaStaticInvoker()) {
6126         // Map the static invoker for the lambda back to the call operator.
6127         // Conveniently, we don't have to slice out the 'this' argument (as is
6128         // being done for the non-static case), since a static member function
6129         // doesn't have an implicit argument passed in.
6130         const CXXRecordDecl *ClosureClass = MD->getParent();
6131         assert(
6132             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
6133             "Number of captures must be zero for conversion to function-ptr");
6134 
6135         const CXXMethodDecl *LambdaCallOp =
6136             ClosureClass->getLambdaCallOperator();
6137 
6138         // Set 'FD', the function that will be called below, to the call
6139         // operator.  If the closure object represents a generic lambda, find
6140         // the corresponding specialization of the call operator.
6141 
6142         if (ClosureClass->isGenericLambda()) {
6143           assert(MD->isFunctionTemplateSpecialization() &&
6144                  "A generic lambda's static-invoker function must be a "
6145                  "template specialization");
6146           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
6147           FunctionTemplateDecl *CallOpTemplate =
6148               LambdaCallOp->getDescribedFunctionTemplate();
6149           void *InsertPos = nullptr;
6150           FunctionDecl *CorrespondingCallOpSpecialization =
6151               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6152           assert(CorrespondingCallOpSpecialization &&
6153                  "We must always have a function call operator specialization "
6154                  "that corresponds to our static invoker specialization");
6155           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
6156         } else
6157           FD = LambdaCallOp;
6158       }
6159     } else
6160       return Error(E);
6161 
6162     SmallVector<QualType, 4> CovariantAdjustmentPath;
6163     if (This) {
6164       auto *NamedMember = dyn_cast<CXXMethodDecl>(FD);
6165       if (NamedMember && NamedMember->isVirtual() && !HasQualifier) {
6166         // Perform virtual dispatch, if necessary.
6167         FD = HandleVirtualDispatch(Info, E, *This, NamedMember,
6168                                    CovariantAdjustmentPath);
6169         if (!FD)
6170           return false;
6171       } else {
6172         // Check that the 'this' pointer points to an object of the right type.
6173         if (!checkNonVirtualMemberCallThisPointer(Info, E, *This))
6174           return false;
6175       }
6176     }
6177 
6178     const FunctionDecl *Definition = nullptr;
6179     Stmt *Body = FD->getBody(Definition);
6180 
6181     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
6182         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
6183                             Result, ResultSlot))
6184       return false;
6185 
6186     if (!CovariantAdjustmentPath.empty() &&
6187         !HandleCovariantReturnAdjustment(Info, E, Result,
6188                                          CovariantAdjustmentPath))
6189       return false;
6190 
6191     return true;
6192   }
6193 
6194   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6195     return StmtVisitorTy::Visit(E->getInitializer());
6196   }
6197   bool VisitInitListExpr(const InitListExpr *E) {
6198     if (E->getNumInits() == 0)
6199       return DerivedZeroInitialization(E);
6200     if (E->getNumInits() == 1)
6201       return StmtVisitorTy::Visit(E->getInit(0));
6202     return Error(E);
6203   }
6204   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
6205     return DerivedZeroInitialization(E);
6206   }
6207   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
6208     return DerivedZeroInitialization(E);
6209   }
6210   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
6211     return DerivedZeroInitialization(E);
6212   }
6213 
6214   /// A member expression where the object is a prvalue is itself a prvalue.
6215   bool VisitMemberExpr(const MemberExpr *E) {
6216     assert(!Info.Ctx.getLangOpts().CPlusPlus11 &&
6217            "missing temporary materialization conversion");
6218     assert(!E->isArrow() && "missing call to bound member function?");
6219 
6220     APValue Val;
6221     if (!Evaluate(Val, Info, E->getBase()))
6222       return false;
6223 
6224     QualType BaseTy = E->getBase()->getType();
6225 
6226     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
6227     if (!FD) return Error(E);
6228     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
6229     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6230            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6231 
6232     // Note: there is no lvalue base here. But this case should only ever
6233     // happen in C or in C++98, where we cannot be evaluating a constexpr
6234     // constructor, which is the only case the base matters.
6235     CompleteObject Obj(APValue::LValueBase(), &Val, BaseTy);
6236     SubobjectDesignator Designator(BaseTy);
6237     Designator.addDeclUnchecked(FD);
6238 
6239     APValue Result;
6240     return extractSubobject(Info, E, Obj, Designator, Result) &&
6241            DerivedSuccess(Result, E);
6242   }
6243 
6244   bool VisitCastExpr(const CastExpr *E) {
6245     switch (E->getCastKind()) {
6246     default:
6247       break;
6248 
6249     case CK_AtomicToNonAtomic: {
6250       APValue AtomicVal;
6251       // This does not need to be done in place even for class/array types:
6252       // atomic-to-non-atomic conversion implies copying the object
6253       // representation.
6254       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
6255         return false;
6256       return DerivedSuccess(AtomicVal, E);
6257     }
6258 
6259     case CK_NoOp:
6260     case CK_UserDefinedConversion:
6261       return StmtVisitorTy::Visit(E->getSubExpr());
6262 
6263     case CK_LValueToRValue: {
6264       LValue LVal;
6265       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
6266         return false;
6267       APValue RVal;
6268       // Note, we use the subexpression's type in order to retain cv-qualifiers.
6269       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
6270                                           LVal, RVal))
6271         return false;
6272       return DerivedSuccess(RVal, E);
6273     }
6274     case CK_LValueToRValueBitCast: {
6275       APValue DestValue, SourceValue;
6276       if (!Evaluate(SourceValue, Info, E->getSubExpr()))
6277         return false;
6278       if (!handleLValueToRValueBitCast(Info, DestValue, SourceValue, E))
6279         return false;
6280       return DerivedSuccess(DestValue, E);
6281     }
6282     }
6283 
6284     return Error(E);
6285   }
6286 
6287   bool VisitUnaryPostInc(const UnaryOperator *UO) {
6288     return VisitUnaryPostIncDec(UO);
6289   }
6290   bool VisitUnaryPostDec(const UnaryOperator *UO) {
6291     return VisitUnaryPostIncDec(UO);
6292   }
6293   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
6294     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6295       return Error(UO);
6296 
6297     LValue LVal;
6298     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
6299       return false;
6300     APValue RVal;
6301     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
6302                       UO->isIncrementOp(), &RVal))
6303       return false;
6304     return DerivedSuccess(RVal, UO);
6305   }
6306 
6307   bool VisitStmtExpr(const StmtExpr *E) {
6308     // We will have checked the full-expressions inside the statement expression
6309     // when they were completed, and don't need to check them again now.
6310     if (Info.checkingForUndefinedBehavior())
6311       return Error(E);
6312 
6313     BlockScopeRAII Scope(Info);
6314     const CompoundStmt *CS = E->getSubStmt();
6315     if (CS->body_empty())
6316       return true;
6317 
6318     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
6319                                            BE = CS->body_end();
6320          /**/; ++BI) {
6321       if (BI + 1 == BE) {
6322         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
6323         if (!FinalExpr) {
6324           Info.FFDiag((*BI)->getBeginLoc(),
6325                       diag::note_constexpr_stmt_expr_unsupported);
6326           return false;
6327         }
6328         return this->Visit(FinalExpr);
6329       }
6330 
6331       APValue ReturnValue;
6332       StmtResult Result = { ReturnValue, nullptr };
6333       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
6334       if (ESR != ESR_Succeeded) {
6335         // FIXME: If the statement-expression terminated due to 'return',
6336         // 'break', or 'continue', it would be nice to propagate that to
6337         // the outer statement evaluation rather than bailing out.
6338         if (ESR != ESR_Failed)
6339           Info.FFDiag((*BI)->getBeginLoc(),
6340                       diag::note_constexpr_stmt_expr_unsupported);
6341         return false;
6342       }
6343     }
6344 
6345     llvm_unreachable("Return from function from the loop above.");
6346   }
6347 
6348   /// Visit a value which is evaluated, but whose value is ignored.
6349   void VisitIgnoredValue(const Expr *E) {
6350     EvaluateIgnoredValue(Info, E);
6351   }
6352 
6353   /// Potentially visit a MemberExpr's base expression.
6354   void VisitIgnoredBaseExpression(const Expr *E) {
6355     // While MSVC doesn't evaluate the base expression, it does diagnose the
6356     // presence of side-effecting behavior.
6357     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
6358       return;
6359     VisitIgnoredValue(E);
6360   }
6361 };
6362 
6363 } // namespace
6364 
6365 //===----------------------------------------------------------------------===//
6366 // Common base class for lvalue and temporary evaluation.
6367 //===----------------------------------------------------------------------===//
6368 namespace {
6369 template<class Derived>
6370 class LValueExprEvaluatorBase
6371   : public ExprEvaluatorBase<Derived> {
6372 protected:
6373   LValue &Result;
6374   bool InvalidBaseOK;
6375   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
6376   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
6377 
6378   bool Success(APValue::LValueBase B) {
6379     Result.set(B);
6380     return true;
6381   }
6382 
6383   bool evaluatePointer(const Expr *E, LValue &Result) {
6384     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
6385   }
6386 
6387 public:
6388   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
6389       : ExprEvaluatorBaseTy(Info), Result(Result),
6390         InvalidBaseOK(InvalidBaseOK) {}
6391 
6392   bool Success(const APValue &V, const Expr *E) {
6393     Result.setFrom(this->Info.Ctx, V);
6394     return true;
6395   }
6396 
6397   bool VisitMemberExpr(const MemberExpr *E) {
6398     // Handle non-static data members.
6399     QualType BaseTy;
6400     bool EvalOK;
6401     if (E->isArrow()) {
6402       EvalOK = evaluatePointer(E->getBase(), Result);
6403       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
6404     } else if (E->getBase()->isRValue()) {
6405       assert(E->getBase()->getType()->isRecordType());
6406       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
6407       BaseTy = E->getBase()->getType();
6408     } else {
6409       EvalOK = this->Visit(E->getBase());
6410       BaseTy = E->getBase()->getType();
6411     }
6412     if (!EvalOK) {
6413       if (!InvalidBaseOK)
6414         return false;
6415       Result.setInvalid(E);
6416       return true;
6417     }
6418 
6419     const ValueDecl *MD = E->getMemberDecl();
6420     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
6421       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
6422              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
6423       (void)BaseTy;
6424       if (!HandleLValueMember(this->Info, E, Result, FD))
6425         return false;
6426     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
6427       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
6428         return false;
6429     } else
6430       return this->Error(E);
6431 
6432     if (MD->getType()->isReferenceType()) {
6433       APValue RefValue;
6434       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
6435                                           RefValue))
6436         return false;
6437       return Success(RefValue, E);
6438     }
6439     return true;
6440   }
6441 
6442   bool VisitBinaryOperator(const BinaryOperator *E) {
6443     switch (E->getOpcode()) {
6444     default:
6445       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6446 
6447     case BO_PtrMemD:
6448     case BO_PtrMemI:
6449       return HandleMemberPointerAccess(this->Info, E, Result);
6450     }
6451   }
6452 
6453   bool VisitCastExpr(const CastExpr *E) {
6454     switch (E->getCastKind()) {
6455     default:
6456       return ExprEvaluatorBaseTy::VisitCastExpr(E);
6457 
6458     case CK_DerivedToBase:
6459     case CK_UncheckedDerivedToBase:
6460       if (!this->Visit(E->getSubExpr()))
6461         return false;
6462 
6463       // Now figure out the necessary offset to add to the base LV to get from
6464       // the derived class to the base class.
6465       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
6466                                   Result);
6467     }
6468   }
6469 };
6470 }
6471 
6472 //===----------------------------------------------------------------------===//
6473 // LValue Evaluation
6474 //
6475 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
6476 // function designators (in C), decl references to void objects (in C), and
6477 // temporaries (if building with -Wno-address-of-temporary).
6478 //
6479 // LValue evaluation produces values comprising a base expression of one of the
6480 // following types:
6481 // - Declarations
6482 //  * VarDecl
6483 //  * FunctionDecl
6484 // - Literals
6485 //  * CompoundLiteralExpr in C (and in global scope in C++)
6486 //  * StringLiteral
6487 //  * PredefinedExpr
6488 //  * ObjCStringLiteralExpr
6489 //  * ObjCEncodeExpr
6490 //  * AddrLabelExpr
6491 //  * BlockExpr
6492 //  * CallExpr for a MakeStringConstant builtin
6493 // - typeid(T) expressions, as TypeInfoLValues
6494 // - Locals and temporaries
6495 //  * MaterializeTemporaryExpr
6496 //  * Any Expr, with a CallIndex indicating the function in which the temporary
6497 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
6498 //    from the AST (FIXME).
6499 //  * A MaterializeTemporaryExpr that has static storage duration, with no
6500 //    CallIndex, for a lifetime-extended temporary.
6501 // plus an offset in bytes.
6502 //===----------------------------------------------------------------------===//
6503 namespace {
6504 class LValueExprEvaluator
6505   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
6506 public:
6507   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
6508     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
6509 
6510   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
6511   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
6512 
6513   bool VisitDeclRefExpr(const DeclRefExpr *E);
6514   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
6515   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
6516   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
6517   bool VisitMemberExpr(const MemberExpr *E);
6518   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
6519   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
6520   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
6521   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
6522   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
6523   bool VisitUnaryDeref(const UnaryOperator *E);
6524   bool VisitUnaryReal(const UnaryOperator *E);
6525   bool VisitUnaryImag(const UnaryOperator *E);
6526   bool VisitUnaryPreInc(const UnaryOperator *UO) {
6527     return VisitUnaryPreIncDec(UO);
6528   }
6529   bool VisitUnaryPreDec(const UnaryOperator *UO) {
6530     return VisitUnaryPreIncDec(UO);
6531   }
6532   bool VisitBinAssign(const BinaryOperator *BO);
6533   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
6534 
6535   bool VisitCastExpr(const CastExpr *E) {
6536     switch (E->getCastKind()) {
6537     default:
6538       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6539 
6540     case CK_LValueBitCast:
6541       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
6542       if (!Visit(E->getSubExpr()))
6543         return false;
6544       Result.Designator.setInvalid();
6545       return true;
6546 
6547     case CK_BaseToDerived:
6548       if (!Visit(E->getSubExpr()))
6549         return false;
6550       return HandleBaseToDerivedCast(Info, E, Result);
6551 
6552     case CK_Dynamic:
6553       if (!Visit(E->getSubExpr()))
6554         return false;
6555       return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
6556     }
6557   }
6558 };
6559 } // end anonymous namespace
6560 
6561 /// Evaluate an expression as an lvalue. This can be legitimately called on
6562 /// expressions which are not glvalues, in three cases:
6563 ///  * function designators in C, and
6564 ///  * "extern void" objects
6565 ///  * @selector() expressions in Objective-C
6566 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
6567                            bool InvalidBaseOK) {
6568   assert(E->isGLValue() || E->getType()->isFunctionType() ||
6569          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
6570   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
6571 }
6572 
6573 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
6574   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
6575     return Success(FD);
6576   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
6577     return VisitVarDecl(E, VD);
6578   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
6579     return Visit(BD->getBinding());
6580   return Error(E);
6581 }
6582 
6583 
6584 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
6585 
6586   // If we are within a lambda's call operator, check whether the 'VD' referred
6587   // to within 'E' actually represents a lambda-capture that maps to a
6588   // data-member/field within the closure object, and if so, evaluate to the
6589   // field or what the field refers to.
6590   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
6591       isa<DeclRefExpr>(E) &&
6592       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
6593     // We don't always have a complete capture-map when checking or inferring if
6594     // the function call operator meets the requirements of a constexpr function
6595     // - but we don't need to evaluate the captures to determine constexprness
6596     // (dcl.constexpr C++17).
6597     if (Info.checkingPotentialConstantExpression())
6598       return false;
6599 
6600     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
6601       // Start with 'Result' referring to the complete closure object...
6602       Result = *Info.CurrentCall->This;
6603       // ... then update it to refer to the field of the closure object
6604       // that represents the capture.
6605       if (!HandleLValueMember(Info, E, Result, FD))
6606         return false;
6607       // And if the field is of reference type, update 'Result' to refer to what
6608       // the field refers to.
6609       if (FD->getType()->isReferenceType()) {
6610         APValue RVal;
6611         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
6612                                             RVal))
6613           return false;
6614         Result.setFrom(Info.Ctx, RVal);
6615       }
6616       return true;
6617     }
6618   }
6619   CallStackFrame *Frame = nullptr;
6620   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
6621     // Only if a local variable was declared in the function currently being
6622     // evaluated, do we expect to be able to find its value in the current
6623     // frame. (Otherwise it was likely declared in an enclosing context and
6624     // could either have a valid evaluatable value (for e.g. a constexpr
6625     // variable) or be ill-formed (and trigger an appropriate evaluation
6626     // diagnostic)).
6627     if (Info.CurrentCall->Callee &&
6628         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
6629       Frame = Info.CurrentCall;
6630     }
6631   }
6632 
6633   if (!VD->getType()->isReferenceType()) {
6634     if (Frame) {
6635       Result.set({VD, Frame->Index,
6636                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
6637       return true;
6638     }
6639     return Success(VD);
6640   }
6641 
6642   APValue *V;
6643   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
6644     return false;
6645   if (!V->hasValue()) {
6646     // FIXME: Is it possible for V to be indeterminate here? If so, we should
6647     // adjust the diagnostic to say that.
6648     if (!Info.checkingPotentialConstantExpression())
6649       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
6650     return false;
6651   }
6652   return Success(*V, E);
6653 }
6654 
6655 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
6656     const MaterializeTemporaryExpr *E) {
6657   // Walk through the expression to find the materialized temporary itself.
6658   SmallVector<const Expr *, 2> CommaLHSs;
6659   SmallVector<SubobjectAdjustment, 2> Adjustments;
6660   const Expr *Inner = E->GetTemporaryExpr()->
6661       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
6662 
6663   // If we passed any comma operators, evaluate their LHSs.
6664   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
6665     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
6666       return false;
6667 
6668   // A materialized temporary with static storage duration can appear within the
6669   // result of a constant expression evaluation, so we need to preserve its
6670   // value for use outside this evaluation.
6671   APValue *Value;
6672   if (E->getStorageDuration() == SD_Static) {
6673     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
6674     *Value = APValue();
6675     Result.set(E);
6676   } else {
6677     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
6678                              *Info.CurrentCall);
6679   }
6680 
6681   QualType Type = Inner->getType();
6682 
6683   // Materialize the temporary itself.
6684   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
6685       (E->getStorageDuration() == SD_Static &&
6686        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
6687     *Value = APValue();
6688     return false;
6689   }
6690 
6691   // Adjust our lvalue to refer to the desired subobject.
6692   for (unsigned I = Adjustments.size(); I != 0; /**/) {
6693     --I;
6694     switch (Adjustments[I].Kind) {
6695     case SubobjectAdjustment::DerivedToBaseAdjustment:
6696       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
6697                                 Type, Result))
6698         return false;
6699       Type = Adjustments[I].DerivedToBase.BasePath->getType();
6700       break;
6701 
6702     case SubobjectAdjustment::FieldAdjustment:
6703       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
6704         return false;
6705       Type = Adjustments[I].Field->getType();
6706       break;
6707 
6708     case SubobjectAdjustment::MemberPointerAdjustment:
6709       if (!HandleMemberPointerAccess(this->Info, Type, Result,
6710                                      Adjustments[I].Ptr.RHS))
6711         return false;
6712       Type = Adjustments[I].Ptr.MPT->getPointeeType();
6713       break;
6714     }
6715   }
6716 
6717   return true;
6718 }
6719 
6720 bool
6721 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
6722   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
6723          "lvalue compound literal in c++?");
6724   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
6725   // only see this when folding in C, so there's no standard to follow here.
6726   return Success(E);
6727 }
6728 
6729 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
6730   TypeInfoLValue TypeInfo;
6731 
6732   if (!E->isPotentiallyEvaluated()) {
6733     if (E->isTypeOperand())
6734       TypeInfo = TypeInfoLValue(E->getTypeOperand(Info.Ctx).getTypePtr());
6735     else
6736       TypeInfo = TypeInfoLValue(E->getExprOperand()->getType().getTypePtr());
6737   } else {
6738     if (!Info.Ctx.getLangOpts().CPlusPlus2a) {
6739       Info.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
6740         << E->getExprOperand()->getType()
6741         << E->getExprOperand()->getSourceRange();
6742     }
6743 
6744     if (!Visit(E->getExprOperand()))
6745       return false;
6746 
6747     Optional<DynamicType> DynType =
6748         ComputeDynamicType(Info, E, Result, AK_TypeId);
6749     if (!DynType)
6750       return false;
6751 
6752     TypeInfo =
6753         TypeInfoLValue(Info.Ctx.getRecordType(DynType->Type).getTypePtr());
6754   }
6755 
6756   return Success(APValue::LValueBase::getTypeInfo(TypeInfo, E->getType()));
6757 }
6758 
6759 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
6760   return Success(E);
6761 }
6762 
6763 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
6764   // Handle static data members.
6765   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
6766     VisitIgnoredBaseExpression(E->getBase());
6767     return VisitVarDecl(E, VD);
6768   }
6769 
6770   // Handle static member functions.
6771   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
6772     if (MD->isStatic()) {
6773       VisitIgnoredBaseExpression(E->getBase());
6774       return Success(MD);
6775     }
6776   }
6777 
6778   // Handle non-static data members.
6779   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
6780 }
6781 
6782 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
6783   // FIXME: Deal with vectors as array subscript bases.
6784   if (E->getBase()->getType()->isVectorType())
6785     return Error(E);
6786 
6787   bool Success = true;
6788   if (!evaluatePointer(E->getBase(), Result)) {
6789     if (!Info.noteFailure())
6790       return false;
6791     Success = false;
6792   }
6793 
6794   APSInt Index;
6795   if (!EvaluateInteger(E->getIdx(), Index, Info))
6796     return false;
6797 
6798   return Success &&
6799          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
6800 }
6801 
6802 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
6803   return evaluatePointer(E->getSubExpr(), Result);
6804 }
6805 
6806 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
6807   if (!Visit(E->getSubExpr()))
6808     return false;
6809   // __real is a no-op on scalar lvalues.
6810   if (E->getSubExpr()->getType()->isAnyComplexType())
6811     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
6812   return true;
6813 }
6814 
6815 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6816   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
6817          "lvalue __imag__ on scalar?");
6818   if (!Visit(E->getSubExpr()))
6819     return false;
6820   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
6821   return true;
6822 }
6823 
6824 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
6825   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6826     return Error(UO);
6827 
6828   if (!this->Visit(UO->getSubExpr()))
6829     return false;
6830 
6831   return handleIncDec(
6832       this->Info, UO, Result, UO->getSubExpr()->getType(),
6833       UO->isIncrementOp(), nullptr);
6834 }
6835 
6836 bool LValueExprEvaluator::VisitCompoundAssignOperator(
6837     const CompoundAssignOperator *CAO) {
6838   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6839     return Error(CAO);
6840 
6841   APValue RHS;
6842 
6843   // The overall lvalue result is the result of evaluating the LHS.
6844   if (!this->Visit(CAO->getLHS())) {
6845     if (Info.noteFailure())
6846       Evaluate(RHS, this->Info, CAO->getRHS());
6847     return false;
6848   }
6849 
6850   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
6851     return false;
6852 
6853   return handleCompoundAssignment(
6854       this->Info, CAO,
6855       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
6856       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
6857 }
6858 
6859 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
6860   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
6861     return Error(E);
6862 
6863   APValue NewVal;
6864 
6865   if (!this->Visit(E->getLHS())) {
6866     if (Info.noteFailure())
6867       Evaluate(NewVal, this->Info, E->getRHS());
6868     return false;
6869   }
6870 
6871   if (!Evaluate(NewVal, this->Info, E->getRHS()))
6872     return false;
6873 
6874   if (Info.getLangOpts().CPlusPlus2a &&
6875       !HandleUnionActiveMemberChange(Info, E->getLHS(), Result))
6876     return false;
6877 
6878   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
6879                           NewVal);
6880 }
6881 
6882 //===----------------------------------------------------------------------===//
6883 // Pointer Evaluation
6884 //===----------------------------------------------------------------------===//
6885 
6886 /// Attempts to compute the number of bytes available at the pointer
6887 /// returned by a function with the alloc_size attribute. Returns true if we
6888 /// were successful. Places an unsigned number into `Result`.
6889 ///
6890 /// This expects the given CallExpr to be a call to a function with an
6891 /// alloc_size attribute.
6892 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6893                                             const CallExpr *Call,
6894                                             llvm::APInt &Result) {
6895   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
6896 
6897   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
6898   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
6899   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
6900   if (Call->getNumArgs() <= SizeArgNo)
6901     return false;
6902 
6903   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
6904     Expr::EvalResult ExprResult;
6905     if (!E->EvaluateAsInt(ExprResult, Ctx, Expr::SE_AllowSideEffects))
6906       return false;
6907     Into = ExprResult.Val.getInt();
6908     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
6909       return false;
6910     Into = Into.zextOrSelf(BitsInSizeT);
6911     return true;
6912   };
6913 
6914   APSInt SizeOfElem;
6915   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
6916     return false;
6917 
6918   if (!AllocSize->getNumElemsParam().isValid()) {
6919     Result = std::move(SizeOfElem);
6920     return true;
6921   }
6922 
6923   APSInt NumberOfElems;
6924   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
6925   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
6926     return false;
6927 
6928   bool Overflow;
6929   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
6930   if (Overflow)
6931     return false;
6932 
6933   Result = std::move(BytesAvailable);
6934   return true;
6935 }
6936 
6937 /// Convenience function. LVal's base must be a call to an alloc_size
6938 /// function.
6939 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
6940                                             const LValue &LVal,
6941                                             llvm::APInt &Result) {
6942   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
6943          "Can't get the size of a non alloc_size function");
6944   const auto *Base = LVal.getLValueBase().get<const Expr *>();
6945   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
6946   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
6947 }
6948 
6949 /// Attempts to evaluate the given LValueBase as the result of a call to
6950 /// a function with the alloc_size attribute. If it was possible to do so, this
6951 /// function will return true, make Result's Base point to said function call,
6952 /// and mark Result's Base as invalid.
6953 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
6954                                       LValue &Result) {
6955   if (Base.isNull())
6956     return false;
6957 
6958   // Because we do no form of static analysis, we only support const variables.
6959   //
6960   // Additionally, we can't support parameters, nor can we support static
6961   // variables (in the latter case, use-before-assign isn't UB; in the former,
6962   // we have no clue what they'll be assigned to).
6963   const auto *VD =
6964       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
6965   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
6966     return false;
6967 
6968   const Expr *Init = VD->getAnyInitializer();
6969   if (!Init)
6970     return false;
6971 
6972   const Expr *E = Init->IgnoreParens();
6973   if (!tryUnwrapAllocSizeCall(E))
6974     return false;
6975 
6976   // Store E instead of E unwrapped so that the type of the LValue's base is
6977   // what the user wanted.
6978   Result.setInvalid(E);
6979 
6980   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
6981   Result.addUnsizedArray(Info, E, Pointee);
6982   return true;
6983 }
6984 
6985 namespace {
6986 class PointerExprEvaluator
6987   : public ExprEvaluatorBase<PointerExprEvaluator> {
6988   LValue &Result;
6989   bool InvalidBaseOK;
6990 
6991   bool Success(const Expr *E) {
6992     Result.set(E);
6993     return true;
6994   }
6995 
6996   bool evaluateLValue(const Expr *E, LValue &Result) {
6997     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
6998   }
6999 
7000   bool evaluatePointer(const Expr *E, LValue &Result) {
7001     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
7002   }
7003 
7004   bool visitNonBuiltinCallExpr(const CallExpr *E);
7005 public:
7006 
7007   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
7008       : ExprEvaluatorBaseTy(info), Result(Result),
7009         InvalidBaseOK(InvalidBaseOK) {}
7010 
7011   bool Success(const APValue &V, const Expr *E) {
7012     Result.setFrom(Info.Ctx, V);
7013     return true;
7014   }
7015   bool ZeroInitialization(const Expr *E) {
7016     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
7017     Result.setNull(E->getType(), TargetVal);
7018     return true;
7019   }
7020 
7021   bool VisitBinaryOperator(const BinaryOperator *E);
7022   bool VisitCastExpr(const CastExpr* E);
7023   bool VisitUnaryAddrOf(const UnaryOperator *E);
7024   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
7025       { return Success(E); }
7026   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
7027     if (E->isExpressibleAsConstantInitializer())
7028       return Success(E);
7029     if (Info.noteFailure())
7030       EvaluateIgnoredValue(Info, E->getSubExpr());
7031     return Error(E);
7032   }
7033   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
7034       { return Success(E); }
7035   bool VisitCallExpr(const CallExpr *E);
7036   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7037   bool VisitBlockExpr(const BlockExpr *E) {
7038     if (!E->getBlockDecl()->hasCaptures())
7039       return Success(E);
7040     return Error(E);
7041   }
7042   bool VisitCXXThisExpr(const CXXThisExpr *E) {
7043     // Can't look at 'this' when checking a potential constant expression.
7044     if (Info.checkingPotentialConstantExpression())
7045       return false;
7046     if (!Info.CurrentCall->This) {
7047       if (Info.getLangOpts().CPlusPlus11)
7048         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
7049       else
7050         Info.FFDiag(E);
7051       return false;
7052     }
7053     Result = *Info.CurrentCall->This;
7054     // If we are inside a lambda's call operator, the 'this' expression refers
7055     // to the enclosing '*this' object (either by value or reference) which is
7056     // either copied into the closure object's field that represents the '*this'
7057     // or refers to '*this'.
7058     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
7059       // Update 'Result' to refer to the data member/field of the closure object
7060       // that represents the '*this' capture.
7061       if (!HandleLValueMember(Info, E, Result,
7062                              Info.CurrentCall->LambdaThisCaptureField))
7063         return false;
7064       // If we captured '*this' by reference, replace the field with its referent.
7065       if (Info.CurrentCall->LambdaThisCaptureField->getType()
7066               ->isPointerType()) {
7067         APValue RVal;
7068         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
7069                                             RVal))
7070           return false;
7071 
7072         Result.setFrom(Info.Ctx, RVal);
7073       }
7074     }
7075     return true;
7076   }
7077 
7078   bool VisitSourceLocExpr(const SourceLocExpr *E) {
7079     assert(E->isStringType() && "SourceLocExpr isn't a pointer type?");
7080     APValue LValResult = E->EvaluateInContext(
7081         Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
7082     Result.setFrom(Info.Ctx, LValResult);
7083     return true;
7084   }
7085 
7086   // FIXME: Missing: @protocol, @selector
7087 };
7088 } // end anonymous namespace
7089 
7090 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
7091                             bool InvalidBaseOK) {
7092   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7093   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
7094 }
7095 
7096 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
7097   if (E->getOpcode() != BO_Add &&
7098       E->getOpcode() != BO_Sub)
7099     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7100 
7101   const Expr *PExp = E->getLHS();
7102   const Expr *IExp = E->getRHS();
7103   if (IExp->getType()->isPointerType())
7104     std::swap(PExp, IExp);
7105 
7106   bool EvalPtrOK = evaluatePointer(PExp, Result);
7107   if (!EvalPtrOK && !Info.noteFailure())
7108     return false;
7109 
7110   llvm::APSInt Offset;
7111   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
7112     return false;
7113 
7114   if (E->getOpcode() == BO_Sub)
7115     negateAsSigned(Offset);
7116 
7117   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
7118   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
7119 }
7120 
7121 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7122   return evaluateLValue(E->getSubExpr(), Result);
7123 }
7124 
7125 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7126   const Expr *SubExpr = E->getSubExpr();
7127 
7128   switch (E->getCastKind()) {
7129   default:
7130     break;
7131   case CK_BitCast:
7132   case CK_CPointerToObjCPointerCast:
7133   case CK_BlockPointerToObjCPointerCast:
7134   case CK_AnyPointerToBlockPointerCast:
7135   case CK_AddressSpaceConversion:
7136     if (!Visit(SubExpr))
7137       return false;
7138     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
7139     // permitted in constant expressions in C++11. Bitcasts from cv void* are
7140     // also static_casts, but we disallow them as a resolution to DR1312.
7141     if (!E->getType()->isVoidPointerType()) {
7142       Result.Designator.setInvalid();
7143       if (SubExpr->getType()->isVoidPointerType())
7144         CCEDiag(E, diag::note_constexpr_invalid_cast)
7145           << 3 << SubExpr->getType();
7146       else
7147         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7148     }
7149     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
7150       ZeroInitialization(E);
7151     return true;
7152 
7153   case CK_DerivedToBase:
7154   case CK_UncheckedDerivedToBase:
7155     if (!evaluatePointer(E->getSubExpr(), Result))
7156       return false;
7157     if (!Result.Base && Result.Offset.isZero())
7158       return true;
7159 
7160     // Now figure out the necessary offset to add to the base LV to get from
7161     // the derived class to the base class.
7162     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
7163                                   castAs<PointerType>()->getPointeeType(),
7164                                 Result);
7165 
7166   case CK_BaseToDerived:
7167     if (!Visit(E->getSubExpr()))
7168       return false;
7169     if (!Result.Base && Result.Offset.isZero())
7170       return true;
7171     return HandleBaseToDerivedCast(Info, E, Result);
7172 
7173   case CK_Dynamic:
7174     if (!Visit(E->getSubExpr()))
7175       return false;
7176     return HandleDynamicCast(Info, cast<ExplicitCastExpr>(E), Result);
7177 
7178   case CK_NullToPointer:
7179     VisitIgnoredValue(E->getSubExpr());
7180     return ZeroInitialization(E);
7181 
7182   case CK_IntegralToPointer: {
7183     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7184 
7185     APValue Value;
7186     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
7187       break;
7188 
7189     if (Value.isInt()) {
7190       unsigned Size = Info.Ctx.getTypeSize(E->getType());
7191       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
7192       Result.Base = (Expr*)nullptr;
7193       Result.InvalidBase = false;
7194       Result.Offset = CharUnits::fromQuantity(N);
7195       Result.Designator.setInvalid();
7196       Result.IsNullPtr = false;
7197       return true;
7198     } else {
7199       // Cast is of an lvalue, no need to change value.
7200       Result.setFrom(Info.Ctx, Value);
7201       return true;
7202     }
7203   }
7204 
7205   case CK_ArrayToPointerDecay: {
7206     if (SubExpr->isGLValue()) {
7207       if (!evaluateLValue(SubExpr, Result))
7208         return false;
7209     } else {
7210       APValue &Value = createTemporary(SubExpr, false, Result,
7211                                        *Info.CurrentCall);
7212       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
7213         return false;
7214     }
7215     // The result is a pointer to the first element of the array.
7216     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
7217     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
7218       Result.addArray(Info, E, CAT);
7219     else
7220       Result.addUnsizedArray(Info, E, AT->getElementType());
7221     return true;
7222   }
7223 
7224   case CK_FunctionToPointerDecay:
7225     return evaluateLValue(SubExpr, Result);
7226 
7227   case CK_LValueToRValue: {
7228     LValue LVal;
7229     if (!evaluateLValue(E->getSubExpr(), LVal))
7230       return false;
7231 
7232     APValue RVal;
7233     // Note, we use the subexpression's type in order to retain cv-qualifiers.
7234     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
7235                                         LVal, RVal))
7236       return InvalidBaseOK &&
7237              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
7238     return Success(RVal, E);
7239   }
7240   }
7241 
7242   return ExprEvaluatorBaseTy::VisitCastExpr(E);
7243 }
7244 
7245 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
7246                                 UnaryExprOrTypeTrait ExprKind) {
7247   // C++ [expr.alignof]p3:
7248   //     When alignof is applied to a reference type, the result is the
7249   //     alignment of the referenced type.
7250   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7251     T = Ref->getPointeeType();
7252 
7253   if (T.getQualifiers().hasUnaligned())
7254     return CharUnits::One();
7255 
7256   const bool AlignOfReturnsPreferred =
7257       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
7258 
7259   // __alignof is defined to return the preferred alignment.
7260   // Before 8, clang returned the preferred alignment for alignof and _Alignof
7261   // as well.
7262   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
7263     return Info.Ctx.toCharUnitsFromBits(
7264       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
7265   // alignof and _Alignof are defined to return the ABI alignment.
7266   else if (ExprKind == UETT_AlignOf)
7267     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
7268   else
7269     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
7270 }
7271 
7272 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
7273                                 UnaryExprOrTypeTrait ExprKind) {
7274   E = E->IgnoreParens();
7275 
7276   // The kinds of expressions that we have special-case logic here for
7277   // should be kept up to date with the special checks for those
7278   // expressions in Sema.
7279 
7280   // alignof decl is always accepted, even if it doesn't make sense: we default
7281   // to 1 in those cases.
7282   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
7283     return Info.Ctx.getDeclAlign(DRE->getDecl(),
7284                                  /*RefAsPointee*/true);
7285 
7286   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
7287     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7288                                  /*RefAsPointee*/true);
7289 
7290   return GetAlignOfType(Info, E->getType(), ExprKind);
7291 }
7292 
7293 // To be clear: this happily visits unsupported builtins. Better name welcomed.
7294 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
7295   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
7296     return true;
7297 
7298   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
7299     return false;
7300 
7301   Result.setInvalid(E);
7302   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
7303   Result.addUnsizedArray(Info, E, PointeeTy);
7304   return true;
7305 }
7306 
7307 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
7308   if (IsStringLiteralCall(E))
7309     return Success(E);
7310 
7311   if (unsigned BuiltinOp = E->getBuiltinCallee())
7312     return VisitBuiltinCallExpr(E, BuiltinOp);
7313 
7314   return visitNonBuiltinCallExpr(E);
7315 }
7316 
7317 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7318                                                 unsigned BuiltinOp) {
7319   switch (BuiltinOp) {
7320   case Builtin::BI__builtin_addressof:
7321     return evaluateLValue(E->getArg(0), Result);
7322   case Builtin::BI__builtin_assume_aligned: {
7323     // We need to be very careful here because: if the pointer does not have the
7324     // asserted alignment, then the behavior is undefined, and undefined
7325     // behavior is non-constant.
7326     if (!evaluatePointer(E->getArg(0), Result))
7327       return false;
7328 
7329     LValue OffsetResult(Result);
7330     APSInt Alignment;
7331     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
7332       return false;
7333     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
7334 
7335     if (E->getNumArgs() > 2) {
7336       APSInt Offset;
7337       if (!EvaluateInteger(E->getArg(2), Offset, Info))
7338         return false;
7339 
7340       int64_t AdditionalOffset = -Offset.getZExtValue();
7341       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
7342     }
7343 
7344     // If there is a base object, then it must have the correct alignment.
7345     if (OffsetResult.Base) {
7346       CharUnits BaseAlignment;
7347       if (const ValueDecl *VD =
7348           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
7349         BaseAlignment = Info.Ctx.getDeclAlign(VD);
7350       } else if (const Expr *E = OffsetResult.Base.dyn_cast<const Expr *>()) {
7351         BaseAlignment = GetAlignOfExpr(Info, E, UETT_AlignOf);
7352       } else {
7353         BaseAlignment = GetAlignOfType(
7354             Info, OffsetResult.Base.getTypeInfoType(), UETT_AlignOf);
7355       }
7356 
7357       if (BaseAlignment < Align) {
7358         Result.Designator.setInvalid();
7359         // FIXME: Add support to Diagnostic for long / long long.
7360         CCEDiag(E->getArg(0),
7361                 diag::note_constexpr_baa_insufficient_alignment) << 0
7362           << (unsigned)BaseAlignment.getQuantity()
7363           << (unsigned)Align.getQuantity();
7364         return false;
7365       }
7366     }
7367 
7368     // The offset must also have the correct alignment.
7369     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
7370       Result.Designator.setInvalid();
7371 
7372       (OffsetResult.Base
7373            ? CCEDiag(E->getArg(0),
7374                      diag::note_constexpr_baa_insufficient_alignment) << 1
7375            : CCEDiag(E->getArg(0),
7376                      diag::note_constexpr_baa_value_insufficient_alignment))
7377         << (int)OffsetResult.Offset.getQuantity()
7378         << (unsigned)Align.getQuantity();
7379       return false;
7380     }
7381 
7382     return true;
7383   }
7384   case Builtin::BI__builtin_launder:
7385     return evaluatePointer(E->getArg(0), Result);
7386   case Builtin::BIstrchr:
7387   case Builtin::BIwcschr:
7388   case Builtin::BImemchr:
7389   case Builtin::BIwmemchr:
7390     if (Info.getLangOpts().CPlusPlus11)
7391       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7392         << /*isConstexpr*/0 << /*isConstructor*/0
7393         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7394     else
7395       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7396     LLVM_FALLTHROUGH;
7397   case Builtin::BI__builtin_strchr:
7398   case Builtin::BI__builtin_wcschr:
7399   case Builtin::BI__builtin_memchr:
7400   case Builtin::BI__builtin_char_memchr:
7401   case Builtin::BI__builtin_wmemchr: {
7402     if (!Visit(E->getArg(0)))
7403       return false;
7404     APSInt Desired;
7405     if (!EvaluateInteger(E->getArg(1), Desired, Info))
7406       return false;
7407     uint64_t MaxLength = uint64_t(-1);
7408     if (BuiltinOp != Builtin::BIstrchr &&
7409         BuiltinOp != Builtin::BIwcschr &&
7410         BuiltinOp != Builtin::BI__builtin_strchr &&
7411         BuiltinOp != Builtin::BI__builtin_wcschr) {
7412       APSInt N;
7413       if (!EvaluateInteger(E->getArg(2), N, Info))
7414         return false;
7415       MaxLength = N.getExtValue();
7416     }
7417     // We cannot find the value if there are no candidates to match against.
7418     if (MaxLength == 0u)
7419       return ZeroInitialization(E);
7420     if (!Result.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
7421         Result.Designator.Invalid)
7422       return false;
7423     QualType CharTy = Result.Designator.getType(Info.Ctx);
7424     bool IsRawByte = BuiltinOp == Builtin::BImemchr ||
7425                      BuiltinOp == Builtin::BI__builtin_memchr;
7426     assert(IsRawByte ||
7427            Info.Ctx.hasSameUnqualifiedType(
7428                CharTy, E->getArg(0)->getType()->getPointeeType()));
7429     // Pointers to const void may point to objects of incomplete type.
7430     if (IsRawByte && CharTy->isIncompleteType()) {
7431       Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy;
7432       return false;
7433     }
7434     // Give up on byte-oriented matching against multibyte elements.
7435     // FIXME: We can compare the bytes in the correct order.
7436     if (IsRawByte && Info.Ctx.getTypeSizeInChars(CharTy) != CharUnits::One())
7437       return false;
7438     // Figure out what value we're actually looking for (after converting to
7439     // the corresponding unsigned type if necessary).
7440     uint64_t DesiredVal;
7441     bool StopAtNull = false;
7442     switch (BuiltinOp) {
7443     case Builtin::BIstrchr:
7444     case Builtin::BI__builtin_strchr:
7445       // strchr compares directly to the passed integer, and therefore
7446       // always fails if given an int that is not a char.
7447       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
7448                                                   E->getArg(1)->getType(),
7449                                                   Desired),
7450                                Desired))
7451         return ZeroInitialization(E);
7452       StopAtNull = true;
7453       LLVM_FALLTHROUGH;
7454     case Builtin::BImemchr:
7455     case Builtin::BI__builtin_memchr:
7456     case Builtin::BI__builtin_char_memchr:
7457       // memchr compares by converting both sides to unsigned char. That's also
7458       // correct for strchr if we get this far (to cope with plain char being
7459       // unsigned in the strchr case).
7460       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
7461       break;
7462 
7463     case Builtin::BIwcschr:
7464     case Builtin::BI__builtin_wcschr:
7465       StopAtNull = true;
7466       LLVM_FALLTHROUGH;
7467     case Builtin::BIwmemchr:
7468     case Builtin::BI__builtin_wmemchr:
7469       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
7470       DesiredVal = Desired.getZExtValue();
7471       break;
7472     }
7473 
7474     for (; MaxLength; --MaxLength) {
7475       APValue Char;
7476       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
7477           !Char.isInt())
7478         return false;
7479       if (Char.getInt().getZExtValue() == DesiredVal)
7480         return true;
7481       if (StopAtNull && !Char.getInt())
7482         break;
7483       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
7484         return false;
7485     }
7486     // Not found: return nullptr.
7487     return ZeroInitialization(E);
7488   }
7489 
7490   case Builtin::BImemcpy:
7491   case Builtin::BImemmove:
7492   case Builtin::BIwmemcpy:
7493   case Builtin::BIwmemmove:
7494     if (Info.getLangOpts().CPlusPlus11)
7495       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7496         << /*isConstexpr*/0 << /*isConstructor*/0
7497         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7498     else
7499       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7500     LLVM_FALLTHROUGH;
7501   case Builtin::BI__builtin_memcpy:
7502   case Builtin::BI__builtin_memmove:
7503   case Builtin::BI__builtin_wmemcpy:
7504   case Builtin::BI__builtin_wmemmove: {
7505     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
7506                  BuiltinOp == Builtin::BIwmemmove ||
7507                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
7508                  BuiltinOp == Builtin::BI__builtin_wmemmove;
7509     bool Move = BuiltinOp == Builtin::BImemmove ||
7510                 BuiltinOp == Builtin::BIwmemmove ||
7511                 BuiltinOp == Builtin::BI__builtin_memmove ||
7512                 BuiltinOp == Builtin::BI__builtin_wmemmove;
7513 
7514     // The result of mem* is the first argument.
7515     if (!Visit(E->getArg(0)))
7516       return false;
7517     LValue Dest = Result;
7518 
7519     LValue Src;
7520     if (!EvaluatePointer(E->getArg(1), Src, Info))
7521       return false;
7522 
7523     APSInt N;
7524     if (!EvaluateInteger(E->getArg(2), N, Info))
7525       return false;
7526     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
7527 
7528     // If the size is zero, we treat this as always being a valid no-op.
7529     // (Even if one of the src and dest pointers is null.)
7530     if (!N)
7531       return true;
7532 
7533     // Otherwise, if either of the operands is null, we can't proceed. Don't
7534     // try to determine the type of the copied objects, because there aren't
7535     // any.
7536     if (!Src.Base || !Dest.Base) {
7537       APValue Val;
7538       (!Src.Base ? Src : Dest).moveInto(Val);
7539       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
7540           << Move << WChar << !!Src.Base
7541           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
7542       return false;
7543     }
7544     if (Src.Designator.Invalid || Dest.Designator.Invalid)
7545       return false;
7546 
7547     // We require that Src and Dest are both pointers to arrays of
7548     // trivially-copyable type. (For the wide version, the designator will be
7549     // invalid if the designated object is not a wchar_t.)
7550     QualType T = Dest.Designator.getType(Info.Ctx);
7551     QualType SrcT = Src.Designator.getType(Info.Ctx);
7552     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
7553       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
7554       return false;
7555     }
7556     if (T->isIncompleteType()) {
7557       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
7558       return false;
7559     }
7560     if (!T.isTriviallyCopyableType(Info.Ctx)) {
7561       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
7562       return false;
7563     }
7564 
7565     // Figure out how many T's we're copying.
7566     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
7567     if (!WChar) {
7568       uint64_t Remainder;
7569       llvm::APInt OrigN = N;
7570       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
7571       if (Remainder) {
7572         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7573             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
7574             << (unsigned)TSize;
7575         return false;
7576       }
7577     }
7578 
7579     // Check that the copying will remain within the arrays, just so that we
7580     // can give a more meaningful diagnostic. This implicitly also checks that
7581     // N fits into 64 bits.
7582     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
7583     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
7584     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
7585       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
7586           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
7587           << N.toString(10, /*Signed*/false);
7588       return false;
7589     }
7590     uint64_t NElems = N.getZExtValue();
7591     uint64_t NBytes = NElems * TSize;
7592 
7593     // Check for overlap.
7594     int Direction = 1;
7595     if (HasSameBase(Src, Dest)) {
7596       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
7597       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
7598       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
7599         // Dest is inside the source region.
7600         if (!Move) {
7601           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7602           return false;
7603         }
7604         // For memmove and friends, copy backwards.
7605         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
7606             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
7607           return false;
7608         Direction = -1;
7609       } else if (!Move && SrcOffset >= DestOffset &&
7610                  SrcOffset - DestOffset < NBytes) {
7611         // Src is inside the destination region for memcpy: invalid.
7612         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
7613         return false;
7614       }
7615     }
7616 
7617     while (true) {
7618       APValue Val;
7619       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
7620           !handleAssignment(Info, E, Dest, T, Val))
7621         return false;
7622       // Do not iterate past the last element; if we're copying backwards, that
7623       // might take us off the start of the array.
7624       if (--NElems == 0)
7625         return true;
7626       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
7627           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
7628         return false;
7629     }
7630   }
7631 
7632   default:
7633     return visitNonBuiltinCallExpr(E);
7634   }
7635 }
7636 
7637 //===----------------------------------------------------------------------===//
7638 // Member Pointer Evaluation
7639 //===----------------------------------------------------------------------===//
7640 
7641 namespace {
7642 class MemberPointerExprEvaluator
7643   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
7644   MemberPtr &Result;
7645 
7646   bool Success(const ValueDecl *D) {
7647     Result = MemberPtr(D);
7648     return true;
7649   }
7650 public:
7651 
7652   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
7653     : ExprEvaluatorBaseTy(Info), Result(Result) {}
7654 
7655   bool Success(const APValue &V, const Expr *E) {
7656     Result.setFrom(V);
7657     return true;
7658   }
7659   bool ZeroInitialization(const Expr *E) {
7660     return Success((const ValueDecl*)nullptr);
7661   }
7662 
7663   bool VisitCastExpr(const CastExpr *E);
7664   bool VisitUnaryAddrOf(const UnaryOperator *E);
7665 };
7666 } // end anonymous namespace
7667 
7668 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
7669                                   EvalInfo &Info) {
7670   assert(E->isRValue() && E->getType()->isMemberPointerType());
7671   return MemberPointerExprEvaluator(Info, Result).Visit(E);
7672 }
7673 
7674 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
7675   switch (E->getCastKind()) {
7676   default:
7677     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7678 
7679   case CK_NullToMemberPointer:
7680     VisitIgnoredValue(E->getSubExpr());
7681     return ZeroInitialization(E);
7682 
7683   case CK_BaseToDerivedMemberPointer: {
7684     if (!Visit(E->getSubExpr()))
7685       return false;
7686     if (E->path_empty())
7687       return true;
7688     // Base-to-derived member pointer casts store the path in derived-to-base
7689     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
7690     // the wrong end of the derived->base arc, so stagger the path by one class.
7691     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
7692     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
7693          PathI != PathE; ++PathI) {
7694       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7695       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
7696       if (!Result.castToDerived(Derived))
7697         return Error(E);
7698     }
7699     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
7700     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
7701       return Error(E);
7702     return true;
7703   }
7704 
7705   case CK_DerivedToBaseMemberPointer:
7706     if (!Visit(E->getSubExpr()))
7707       return false;
7708     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7709          PathE = E->path_end(); PathI != PathE; ++PathI) {
7710       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
7711       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7712       if (!Result.castToBase(Base))
7713         return Error(E);
7714     }
7715     return true;
7716   }
7717 }
7718 
7719 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
7720   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7721   // member can be formed.
7722   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
7723 }
7724 
7725 //===----------------------------------------------------------------------===//
7726 // Record Evaluation
7727 //===----------------------------------------------------------------------===//
7728 
7729 namespace {
7730   class RecordExprEvaluator
7731   : public ExprEvaluatorBase<RecordExprEvaluator> {
7732     const LValue &This;
7733     APValue &Result;
7734   public:
7735 
7736     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
7737       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
7738 
7739     bool Success(const APValue &V, const Expr *E) {
7740       Result = V;
7741       return true;
7742     }
7743     bool ZeroInitialization(const Expr *E) {
7744       return ZeroInitialization(E, E->getType());
7745     }
7746     bool ZeroInitialization(const Expr *E, QualType T);
7747 
7748     bool VisitCallExpr(const CallExpr *E) {
7749       return handleCallExpr(E, Result, &This);
7750     }
7751     bool VisitCastExpr(const CastExpr *E);
7752     bool VisitInitListExpr(const InitListExpr *E);
7753     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
7754       return VisitCXXConstructExpr(E, E->getType());
7755     }
7756     bool VisitLambdaExpr(const LambdaExpr *E);
7757     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
7758     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
7759     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
7760 
7761     bool VisitBinCmp(const BinaryOperator *E);
7762   };
7763 }
7764 
7765 /// Perform zero-initialization on an object of non-union class type.
7766 /// C++11 [dcl.init]p5:
7767 ///  To zero-initialize an object or reference of type T means:
7768 ///    [...]
7769 ///    -- if T is a (possibly cv-qualified) non-union class type,
7770 ///       each non-static data member and each base-class subobject is
7771 ///       zero-initialized
7772 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
7773                                           const RecordDecl *RD,
7774                                           const LValue &This, APValue &Result) {
7775   assert(!RD->isUnion() && "Expected non-union class type");
7776   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
7777   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
7778                    std::distance(RD->field_begin(), RD->field_end()));
7779 
7780   if (RD->isInvalidDecl()) return false;
7781   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7782 
7783   if (CD) {
7784     unsigned Index = 0;
7785     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
7786            End = CD->bases_end(); I != End; ++I, ++Index) {
7787       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
7788       LValue Subobject = This;
7789       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
7790         return false;
7791       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
7792                                          Result.getStructBase(Index)))
7793         return false;
7794     }
7795   }
7796 
7797   for (const auto *I : RD->fields()) {
7798     // -- if T is a reference type, no initialization is performed.
7799     if (I->getType()->isReferenceType())
7800       continue;
7801 
7802     LValue Subobject = This;
7803     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
7804       return false;
7805 
7806     ImplicitValueInitExpr VIE(I->getType());
7807     if (!EvaluateInPlace(
7808           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
7809       return false;
7810   }
7811 
7812   return true;
7813 }
7814 
7815 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
7816   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
7817   if (RD->isInvalidDecl()) return false;
7818   if (RD->isUnion()) {
7819     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
7820     // object's first non-static named data member is zero-initialized
7821     RecordDecl::field_iterator I = RD->field_begin();
7822     if (I == RD->field_end()) {
7823       Result = APValue((const FieldDecl*)nullptr);
7824       return true;
7825     }
7826 
7827     LValue Subobject = This;
7828     if (!HandleLValueMember(Info, E, Subobject, *I))
7829       return false;
7830     Result = APValue(*I);
7831     ImplicitValueInitExpr VIE(I->getType());
7832     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
7833   }
7834 
7835   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
7836     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
7837     return false;
7838   }
7839 
7840   return HandleClassZeroInitialization(Info, E, RD, This, Result);
7841 }
7842 
7843 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
7844   switch (E->getCastKind()) {
7845   default:
7846     return ExprEvaluatorBaseTy::VisitCastExpr(E);
7847 
7848   case CK_ConstructorConversion:
7849     return Visit(E->getSubExpr());
7850 
7851   case CK_DerivedToBase:
7852   case CK_UncheckedDerivedToBase: {
7853     APValue DerivedObject;
7854     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
7855       return false;
7856     if (!DerivedObject.isStruct())
7857       return Error(E->getSubExpr());
7858 
7859     // Derived-to-base rvalue conversion: just slice off the derived part.
7860     APValue *Value = &DerivedObject;
7861     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
7862     for (CastExpr::path_const_iterator PathI = E->path_begin(),
7863          PathE = E->path_end(); PathI != PathE; ++PathI) {
7864       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
7865       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
7866       Value = &Value->getStructBase(getBaseIndex(RD, Base));
7867       RD = Base;
7868     }
7869     Result = *Value;
7870     return true;
7871   }
7872   }
7873 }
7874 
7875 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7876   if (E->isTransparent())
7877     return Visit(E->getInit(0));
7878 
7879   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
7880   if (RD->isInvalidDecl()) return false;
7881   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
7882   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
7883 
7884   EvalInfo::EvaluatingConstructorRAII EvalObj(
7885       Info,
7886       ObjectUnderConstruction{This.getLValueBase(), This.Designator.Entries},
7887       CXXRD && CXXRD->getNumBases());
7888 
7889   if (RD->isUnion()) {
7890     const FieldDecl *Field = E->getInitializedFieldInUnion();
7891     Result = APValue(Field);
7892     if (!Field)
7893       return true;
7894 
7895     // If the initializer list for a union does not contain any elements, the
7896     // first element of the union is value-initialized.
7897     // FIXME: The element should be initialized from an initializer list.
7898     //        Is this difference ever observable for initializer lists which
7899     //        we don't build?
7900     ImplicitValueInitExpr VIE(Field->getType());
7901     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
7902 
7903     LValue Subobject = This;
7904     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
7905       return false;
7906 
7907     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7908     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7909                                   isa<CXXDefaultInitExpr>(InitExpr));
7910 
7911     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
7912   }
7913 
7914   if (!Result.hasValue())
7915     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
7916                      std::distance(RD->field_begin(), RD->field_end()));
7917   unsigned ElementNo = 0;
7918   bool Success = true;
7919 
7920   // Initialize base classes.
7921   if (CXXRD && CXXRD->getNumBases()) {
7922     for (const auto &Base : CXXRD->bases()) {
7923       assert(ElementNo < E->getNumInits() && "missing init for base class");
7924       const Expr *Init = E->getInit(ElementNo);
7925 
7926       LValue Subobject = This;
7927       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
7928         return false;
7929 
7930       APValue &FieldVal = Result.getStructBase(ElementNo);
7931       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
7932         if (!Info.noteFailure())
7933           return false;
7934         Success = false;
7935       }
7936       ++ElementNo;
7937     }
7938 
7939     EvalObj.finishedConstructingBases();
7940   }
7941 
7942   // Initialize members.
7943   for (const auto *Field : RD->fields()) {
7944     // Anonymous bit-fields are not considered members of the class for
7945     // purposes of aggregate initialization.
7946     if (Field->isUnnamedBitfield())
7947       continue;
7948 
7949     LValue Subobject = This;
7950 
7951     bool HaveInit = ElementNo < E->getNumInits();
7952 
7953     // FIXME: Diagnostics here should point to the end of the initializer
7954     // list, not the start.
7955     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
7956                             Subobject, Field, &Layout))
7957       return false;
7958 
7959     // Perform an implicit value-initialization for members beyond the end of
7960     // the initializer list.
7961     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
7962     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
7963 
7964     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
7965     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
7966                                   isa<CXXDefaultInitExpr>(Init));
7967 
7968     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
7969     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
7970         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
7971                                                        FieldVal, Field))) {
7972       if (!Info.noteFailure())
7973         return false;
7974       Success = false;
7975     }
7976   }
7977 
7978   return Success;
7979 }
7980 
7981 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7982                                                 QualType T) {
7983   // Note that E's type is not necessarily the type of our class here; we might
7984   // be initializing an array element instead.
7985   const CXXConstructorDecl *FD = E->getConstructor();
7986   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
7987 
7988   bool ZeroInit = E->requiresZeroInitialization();
7989   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
7990     // If we've already performed zero-initialization, we're already done.
7991     if (Result.hasValue())
7992       return true;
7993 
7994     // We can get here in two different ways:
7995     //  1) We're performing value-initialization, and should zero-initialize
7996     //     the object, or
7997     //  2) We're performing default-initialization of an object with a trivial
7998     //     constexpr default constructor, in which case we should start the
7999     //     lifetimes of all the base subobjects (there can be no data member
8000     //     subobjects in this case) per [basic.life]p1.
8001     // Either way, ZeroInitialization is appropriate.
8002     return ZeroInitialization(E, T);
8003   }
8004 
8005   const FunctionDecl *Definition = nullptr;
8006   auto Body = FD->getBody(Definition);
8007 
8008   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8009     return false;
8010 
8011   // Avoid materializing a temporary for an elidable copy/move constructor.
8012   if (E->isElidable() && !ZeroInit)
8013     if (const MaterializeTemporaryExpr *ME
8014           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
8015       return Visit(ME->GetTemporaryExpr());
8016 
8017   if (ZeroInit && !ZeroInitialization(E, T))
8018     return false;
8019 
8020   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
8021   return HandleConstructorCall(E, This, Args,
8022                                cast<CXXConstructorDecl>(Definition), Info,
8023                                Result);
8024 }
8025 
8026 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
8027     const CXXInheritedCtorInitExpr *E) {
8028   if (!Info.CurrentCall) {
8029     assert(Info.checkingPotentialConstantExpression());
8030     return false;
8031   }
8032 
8033   const CXXConstructorDecl *FD = E->getConstructor();
8034   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
8035     return false;
8036 
8037   const FunctionDecl *Definition = nullptr;
8038   auto Body = FD->getBody(Definition);
8039 
8040   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
8041     return false;
8042 
8043   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
8044                                cast<CXXConstructorDecl>(Definition), Info,
8045                                Result);
8046 }
8047 
8048 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
8049     const CXXStdInitializerListExpr *E) {
8050   const ConstantArrayType *ArrayType =
8051       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
8052 
8053   LValue Array;
8054   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
8055     return false;
8056 
8057   // Get a pointer to the first element of the array.
8058   Array.addArray(Info, E, ArrayType);
8059 
8060   // FIXME: Perform the checks on the field types in SemaInit.
8061   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
8062   RecordDecl::field_iterator Field = Record->field_begin();
8063   if (Field == Record->field_end())
8064     return Error(E);
8065 
8066   // Start pointer.
8067   if (!Field->getType()->isPointerType() ||
8068       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8069                             ArrayType->getElementType()))
8070     return Error(E);
8071 
8072   // FIXME: What if the initializer_list type has base classes, etc?
8073   Result = APValue(APValue::UninitStruct(), 0, 2);
8074   Array.moveInto(Result.getStructField(0));
8075 
8076   if (++Field == Record->field_end())
8077     return Error(E);
8078 
8079   if (Field->getType()->isPointerType() &&
8080       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
8081                            ArrayType->getElementType())) {
8082     // End pointer.
8083     if (!HandleLValueArrayAdjustment(Info, E, Array,
8084                                      ArrayType->getElementType(),
8085                                      ArrayType->getSize().getZExtValue()))
8086       return false;
8087     Array.moveInto(Result.getStructField(1));
8088   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
8089     // Length.
8090     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
8091   else
8092     return Error(E);
8093 
8094   if (++Field != Record->field_end())
8095     return Error(E);
8096 
8097   return true;
8098 }
8099 
8100 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
8101   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
8102   if (ClosureClass->isInvalidDecl()) return false;
8103 
8104   if (Info.checkingPotentialConstantExpression()) return true;
8105 
8106   const size_t NumFields =
8107       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
8108 
8109   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
8110                                             E->capture_init_end()) &&
8111          "The number of lambda capture initializers should equal the number of "
8112          "fields within the closure type");
8113 
8114   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
8115   // Iterate through all the lambda's closure object's fields and initialize
8116   // them.
8117   auto *CaptureInitIt = E->capture_init_begin();
8118   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
8119   bool Success = true;
8120   for (const auto *Field : ClosureClass->fields()) {
8121     assert(CaptureInitIt != E->capture_init_end());
8122     // Get the initializer for this field
8123     Expr *const CurFieldInit = *CaptureInitIt++;
8124 
8125     // If there is no initializer, either this is a VLA or an error has
8126     // occurred.
8127     if (!CurFieldInit)
8128       return Error(E);
8129 
8130     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
8131     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
8132       if (!Info.keepEvaluatingAfterFailure())
8133         return false;
8134       Success = false;
8135     }
8136     ++CaptureIt;
8137   }
8138   return Success;
8139 }
8140 
8141 static bool EvaluateRecord(const Expr *E, const LValue &This,
8142                            APValue &Result, EvalInfo &Info) {
8143   assert(E->isRValue() && E->getType()->isRecordType() &&
8144          "can't evaluate expression as a record rvalue");
8145   return RecordExprEvaluator(Info, This, Result).Visit(E);
8146 }
8147 
8148 //===----------------------------------------------------------------------===//
8149 // Temporary Evaluation
8150 //
8151 // Temporaries are represented in the AST as rvalues, but generally behave like
8152 // lvalues. The full-object of which the temporary is a subobject is implicitly
8153 // materialized so that a reference can bind to it.
8154 //===----------------------------------------------------------------------===//
8155 namespace {
8156 class TemporaryExprEvaluator
8157   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
8158 public:
8159   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
8160     LValueExprEvaluatorBaseTy(Info, Result, false) {}
8161 
8162   /// Visit an expression which constructs the value of this temporary.
8163   bool VisitConstructExpr(const Expr *E) {
8164     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
8165     return EvaluateInPlace(Value, Info, Result, E);
8166   }
8167 
8168   bool VisitCastExpr(const CastExpr *E) {
8169     switch (E->getCastKind()) {
8170     default:
8171       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
8172 
8173     case CK_ConstructorConversion:
8174       return VisitConstructExpr(E->getSubExpr());
8175     }
8176   }
8177   bool VisitInitListExpr(const InitListExpr *E) {
8178     return VisitConstructExpr(E);
8179   }
8180   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
8181     return VisitConstructExpr(E);
8182   }
8183   bool VisitCallExpr(const CallExpr *E) {
8184     return VisitConstructExpr(E);
8185   }
8186   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
8187     return VisitConstructExpr(E);
8188   }
8189   bool VisitLambdaExpr(const LambdaExpr *E) {
8190     return VisitConstructExpr(E);
8191   }
8192 };
8193 } // end anonymous namespace
8194 
8195 /// Evaluate an expression of record type as a temporary.
8196 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
8197   assert(E->isRValue() && E->getType()->isRecordType());
8198   return TemporaryExprEvaluator(Info, Result).Visit(E);
8199 }
8200 
8201 //===----------------------------------------------------------------------===//
8202 // Vector Evaluation
8203 //===----------------------------------------------------------------------===//
8204 
8205 namespace {
8206   class VectorExprEvaluator
8207   : public ExprEvaluatorBase<VectorExprEvaluator> {
8208     APValue &Result;
8209   public:
8210 
8211     VectorExprEvaluator(EvalInfo &info, APValue &Result)
8212       : ExprEvaluatorBaseTy(info), Result(Result) {}
8213 
8214     bool Success(ArrayRef<APValue> V, const Expr *E) {
8215       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
8216       // FIXME: remove this APValue copy.
8217       Result = APValue(V.data(), V.size());
8218       return true;
8219     }
8220     bool Success(const APValue &V, const Expr *E) {
8221       assert(V.isVector());
8222       Result = V;
8223       return true;
8224     }
8225     bool ZeroInitialization(const Expr *E);
8226 
8227     bool VisitUnaryReal(const UnaryOperator *E)
8228       { return Visit(E->getSubExpr()); }
8229     bool VisitCastExpr(const CastExpr* E);
8230     bool VisitInitListExpr(const InitListExpr *E);
8231     bool VisitUnaryImag(const UnaryOperator *E);
8232     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
8233     //                 binary comparisons, binary and/or/xor,
8234     //                 shufflevector, ExtVectorElementExpr
8235   };
8236 } // end anonymous namespace
8237 
8238 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
8239   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
8240   return VectorExprEvaluator(Info, Result).Visit(E);
8241 }
8242 
8243 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
8244   const VectorType *VTy = E->getType()->castAs<VectorType>();
8245   unsigned NElts = VTy->getNumElements();
8246 
8247   const Expr *SE = E->getSubExpr();
8248   QualType SETy = SE->getType();
8249 
8250   switch (E->getCastKind()) {
8251   case CK_VectorSplat: {
8252     APValue Val = APValue();
8253     if (SETy->isIntegerType()) {
8254       APSInt IntResult;
8255       if (!EvaluateInteger(SE, IntResult, Info))
8256         return false;
8257       Val = APValue(std::move(IntResult));
8258     } else if (SETy->isRealFloatingType()) {
8259       APFloat FloatResult(0.0);
8260       if (!EvaluateFloat(SE, FloatResult, Info))
8261         return false;
8262       Val = APValue(std::move(FloatResult));
8263     } else {
8264       return Error(E);
8265     }
8266 
8267     // Splat and create vector APValue.
8268     SmallVector<APValue, 4> Elts(NElts, Val);
8269     return Success(Elts, E);
8270   }
8271   case CK_BitCast: {
8272     // Evaluate the operand into an APInt we can extract from.
8273     llvm::APInt SValInt;
8274     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
8275       return false;
8276     // Extract the elements
8277     QualType EltTy = VTy->getElementType();
8278     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
8279     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
8280     SmallVector<APValue, 4> Elts;
8281     if (EltTy->isRealFloatingType()) {
8282       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
8283       unsigned FloatEltSize = EltSize;
8284       if (&Sem == &APFloat::x87DoubleExtended())
8285         FloatEltSize = 80;
8286       for (unsigned i = 0; i < NElts; i++) {
8287         llvm::APInt Elt;
8288         if (BigEndian)
8289           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
8290         else
8291           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
8292         Elts.push_back(APValue(APFloat(Sem, Elt)));
8293       }
8294     } else if (EltTy->isIntegerType()) {
8295       for (unsigned i = 0; i < NElts; i++) {
8296         llvm::APInt Elt;
8297         if (BigEndian)
8298           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
8299         else
8300           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
8301         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
8302       }
8303     } else {
8304       return Error(E);
8305     }
8306     return Success(Elts, E);
8307   }
8308   default:
8309     return ExprEvaluatorBaseTy::VisitCastExpr(E);
8310   }
8311 }
8312 
8313 bool
8314 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8315   const VectorType *VT = E->getType()->castAs<VectorType>();
8316   unsigned NumInits = E->getNumInits();
8317   unsigned NumElements = VT->getNumElements();
8318 
8319   QualType EltTy = VT->getElementType();
8320   SmallVector<APValue, 4> Elements;
8321 
8322   // The number of initializers can be less than the number of
8323   // vector elements. For OpenCL, this can be due to nested vector
8324   // initialization. For GCC compatibility, missing trailing elements
8325   // should be initialized with zeroes.
8326   unsigned CountInits = 0, CountElts = 0;
8327   while (CountElts < NumElements) {
8328     // Handle nested vector initialization.
8329     if (CountInits < NumInits
8330         && E->getInit(CountInits)->getType()->isVectorType()) {
8331       APValue v;
8332       if (!EvaluateVector(E->getInit(CountInits), v, Info))
8333         return Error(E);
8334       unsigned vlen = v.getVectorLength();
8335       for (unsigned j = 0; j < vlen; j++)
8336         Elements.push_back(v.getVectorElt(j));
8337       CountElts += vlen;
8338     } else if (EltTy->isIntegerType()) {
8339       llvm::APSInt sInt(32);
8340       if (CountInits < NumInits) {
8341         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
8342           return false;
8343       } else // trailing integer zero.
8344         sInt = Info.Ctx.MakeIntValue(0, EltTy);
8345       Elements.push_back(APValue(sInt));
8346       CountElts++;
8347     } else {
8348       llvm::APFloat f(0.0);
8349       if (CountInits < NumInits) {
8350         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
8351           return false;
8352       } else // trailing float zero.
8353         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
8354       Elements.push_back(APValue(f));
8355       CountElts++;
8356     }
8357     CountInits++;
8358   }
8359   return Success(Elements, E);
8360 }
8361 
8362 bool
8363 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
8364   const VectorType *VT = E->getType()->getAs<VectorType>();
8365   QualType EltTy = VT->getElementType();
8366   APValue ZeroElement;
8367   if (EltTy->isIntegerType())
8368     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
8369   else
8370     ZeroElement =
8371         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
8372 
8373   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
8374   return Success(Elements, E);
8375 }
8376 
8377 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
8378   VisitIgnoredValue(E->getSubExpr());
8379   return ZeroInitialization(E);
8380 }
8381 
8382 //===----------------------------------------------------------------------===//
8383 // Array Evaluation
8384 //===----------------------------------------------------------------------===//
8385 
8386 namespace {
8387   class ArrayExprEvaluator
8388   : public ExprEvaluatorBase<ArrayExprEvaluator> {
8389     const LValue &This;
8390     APValue &Result;
8391   public:
8392 
8393     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
8394       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
8395 
8396     bool Success(const APValue &V, const Expr *E) {
8397       assert(V.isArray() && "expected array");
8398       Result = V;
8399       return true;
8400     }
8401 
8402     bool ZeroInitialization(const Expr *E) {
8403       const ConstantArrayType *CAT =
8404           Info.Ctx.getAsConstantArrayType(E->getType());
8405       if (!CAT)
8406         return Error(E);
8407 
8408       Result = APValue(APValue::UninitArray(), 0,
8409                        CAT->getSize().getZExtValue());
8410       if (!Result.hasArrayFiller()) return true;
8411 
8412       // Zero-initialize all elements.
8413       LValue Subobject = This;
8414       Subobject.addArray(Info, E, CAT);
8415       ImplicitValueInitExpr VIE(CAT->getElementType());
8416       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
8417     }
8418 
8419     bool VisitCallExpr(const CallExpr *E) {
8420       return handleCallExpr(E, Result, &This);
8421     }
8422     bool VisitInitListExpr(const InitListExpr *E);
8423     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
8424     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
8425     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
8426                                const LValue &Subobject,
8427                                APValue *Value, QualType Type);
8428     bool VisitStringLiteral(const StringLiteral *E) {
8429       expandStringLiteral(Info, E, Result);
8430       return true;
8431     }
8432   };
8433 } // end anonymous namespace
8434 
8435 static bool EvaluateArray(const Expr *E, const LValue &This,
8436                           APValue &Result, EvalInfo &Info) {
8437   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
8438   return ArrayExprEvaluator(Info, This, Result).Visit(E);
8439 }
8440 
8441 // Return true iff the given array filler may depend on the element index.
8442 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
8443   // For now, just whitelist non-class value-initialization and initialization
8444   // lists comprised of them.
8445   if (isa<ImplicitValueInitExpr>(FillerExpr))
8446     return false;
8447   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
8448     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
8449       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
8450         return true;
8451     }
8452     return false;
8453   }
8454   return true;
8455 }
8456 
8457 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8458   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
8459   if (!CAT)
8460     return Error(E);
8461 
8462   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
8463   // an appropriately-typed string literal enclosed in braces.
8464   if (E->isStringLiteralInit())
8465     return Visit(E->getInit(0));
8466 
8467   bool Success = true;
8468 
8469   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
8470          "zero-initialized array shouldn't have any initialized elts");
8471   APValue Filler;
8472   if (Result.isArray() && Result.hasArrayFiller())
8473     Filler = Result.getArrayFiller();
8474 
8475   unsigned NumEltsToInit = E->getNumInits();
8476   unsigned NumElts = CAT->getSize().getZExtValue();
8477   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
8478 
8479   // If the initializer might depend on the array index, run it for each
8480   // array element.
8481   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
8482     NumEltsToInit = NumElts;
8483 
8484   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
8485                           << NumEltsToInit << ".\n");
8486 
8487   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
8488 
8489   // If the array was previously zero-initialized, preserve the
8490   // zero-initialized values.
8491   if (Filler.hasValue()) {
8492     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
8493       Result.getArrayInitializedElt(I) = Filler;
8494     if (Result.hasArrayFiller())
8495       Result.getArrayFiller() = Filler;
8496   }
8497 
8498   LValue Subobject = This;
8499   Subobject.addArray(Info, E, CAT);
8500   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
8501     const Expr *Init =
8502         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
8503     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8504                          Info, Subobject, Init) ||
8505         !HandleLValueArrayAdjustment(Info, Init, Subobject,
8506                                      CAT->getElementType(), 1)) {
8507       if (!Info.noteFailure())
8508         return false;
8509       Success = false;
8510     }
8511   }
8512 
8513   if (!Result.hasArrayFiller())
8514     return Success;
8515 
8516   // If we get here, we have a trivial filler, which we can just evaluate
8517   // once and splat over the rest of the array elements.
8518   assert(FillerExpr && "no array filler for incomplete init list");
8519   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
8520                          FillerExpr) && Success;
8521 }
8522 
8523 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
8524   if (E->getCommonExpr() &&
8525       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
8526                 Info, E->getCommonExpr()->getSourceExpr()))
8527     return false;
8528 
8529   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
8530 
8531   uint64_t Elements = CAT->getSize().getZExtValue();
8532   Result = APValue(APValue::UninitArray(), Elements, Elements);
8533 
8534   LValue Subobject = This;
8535   Subobject.addArray(Info, E, CAT);
8536 
8537   bool Success = true;
8538   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
8539     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
8540                          Info, Subobject, E->getSubExpr()) ||
8541         !HandleLValueArrayAdjustment(Info, E, Subobject,
8542                                      CAT->getElementType(), 1)) {
8543       if (!Info.noteFailure())
8544         return false;
8545       Success = false;
8546     }
8547   }
8548 
8549   return Success;
8550 }
8551 
8552 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
8553   return VisitCXXConstructExpr(E, This, &Result, E->getType());
8554 }
8555 
8556 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
8557                                                const LValue &Subobject,
8558                                                APValue *Value,
8559                                                QualType Type) {
8560   bool HadZeroInit = Value->hasValue();
8561 
8562   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
8563     unsigned N = CAT->getSize().getZExtValue();
8564 
8565     // Preserve the array filler if we had prior zero-initialization.
8566     APValue Filler =
8567       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
8568                                              : APValue();
8569 
8570     *Value = APValue(APValue::UninitArray(), N, N);
8571 
8572     if (HadZeroInit)
8573       for (unsigned I = 0; I != N; ++I)
8574         Value->getArrayInitializedElt(I) = Filler;
8575 
8576     // Initialize the elements.
8577     LValue ArrayElt = Subobject;
8578     ArrayElt.addArray(Info, E, CAT);
8579     for (unsigned I = 0; I != N; ++I)
8580       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
8581                                  CAT->getElementType()) ||
8582           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
8583                                        CAT->getElementType(), 1))
8584         return false;
8585 
8586     return true;
8587   }
8588 
8589   if (!Type->isRecordType())
8590     return Error(E);
8591 
8592   return RecordExprEvaluator(Info, Subobject, *Value)
8593              .VisitCXXConstructExpr(E, Type);
8594 }
8595 
8596 //===----------------------------------------------------------------------===//
8597 // Integer Evaluation
8598 //
8599 // As a GNU extension, we support casting pointers to sufficiently-wide integer
8600 // types and back in constant folding. Integer values are thus represented
8601 // either as an integer-valued APValue, or as an lvalue-valued APValue.
8602 //===----------------------------------------------------------------------===//
8603 
8604 namespace {
8605 class IntExprEvaluator
8606         : public ExprEvaluatorBase<IntExprEvaluator> {
8607   APValue &Result;
8608 public:
8609   IntExprEvaluator(EvalInfo &info, APValue &result)
8610       : ExprEvaluatorBaseTy(info), Result(result) {}
8611 
8612   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
8613     assert(E->getType()->isIntegralOrEnumerationType() &&
8614            "Invalid evaluation result.");
8615     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
8616            "Invalid evaluation result.");
8617     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8618            "Invalid evaluation result.");
8619     Result = APValue(SI);
8620     return true;
8621   }
8622   bool Success(const llvm::APSInt &SI, const Expr *E) {
8623     return Success(SI, E, Result);
8624   }
8625 
8626   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
8627     assert(E->getType()->isIntegralOrEnumerationType() &&
8628            "Invalid evaluation result.");
8629     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8630            "Invalid evaluation result.");
8631     Result = APValue(APSInt(I));
8632     Result.getInt().setIsUnsigned(
8633                             E->getType()->isUnsignedIntegerOrEnumerationType());
8634     return true;
8635   }
8636   bool Success(const llvm::APInt &I, const Expr *E) {
8637     return Success(I, E, Result);
8638   }
8639 
8640   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8641     assert(E->getType()->isIntegralOrEnumerationType() &&
8642            "Invalid evaluation result.");
8643     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
8644     return true;
8645   }
8646   bool Success(uint64_t Value, const Expr *E) {
8647     return Success(Value, E, Result);
8648   }
8649 
8650   bool Success(CharUnits Size, const Expr *E) {
8651     return Success(Size.getQuantity(), E);
8652   }
8653 
8654   bool Success(const APValue &V, const Expr *E) {
8655     if (V.isLValue() || V.isAddrLabelDiff() || V.isIndeterminate()) {
8656       Result = V;
8657       return true;
8658     }
8659     return Success(V.getInt(), E);
8660   }
8661 
8662   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
8663 
8664   //===--------------------------------------------------------------------===//
8665   //                            Visitor Methods
8666   //===--------------------------------------------------------------------===//
8667 
8668   bool VisitConstantExpr(const ConstantExpr *E);
8669 
8670   bool VisitIntegerLiteral(const IntegerLiteral *E) {
8671     return Success(E->getValue(), E);
8672   }
8673   bool VisitCharacterLiteral(const CharacterLiteral *E) {
8674     return Success(E->getValue(), E);
8675   }
8676 
8677   bool CheckReferencedDecl(const Expr *E, const Decl *D);
8678   bool VisitDeclRefExpr(const DeclRefExpr *E) {
8679     if (CheckReferencedDecl(E, E->getDecl()))
8680       return true;
8681 
8682     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
8683   }
8684   bool VisitMemberExpr(const MemberExpr *E) {
8685     if (CheckReferencedDecl(E, E->getMemberDecl())) {
8686       VisitIgnoredBaseExpression(E->getBase());
8687       return true;
8688     }
8689 
8690     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
8691   }
8692 
8693   bool VisitCallExpr(const CallExpr *E);
8694   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
8695   bool VisitBinaryOperator(const BinaryOperator *E);
8696   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
8697   bool VisitUnaryOperator(const UnaryOperator *E);
8698 
8699   bool VisitCastExpr(const CastExpr* E);
8700   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
8701 
8702   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
8703     return Success(E->getValue(), E);
8704   }
8705 
8706   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
8707     return Success(E->getValue(), E);
8708   }
8709 
8710   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
8711     if (Info.ArrayInitIndex == uint64_t(-1)) {
8712       // We were asked to evaluate this subexpression independent of the
8713       // enclosing ArrayInitLoopExpr. We can't do that.
8714       Info.FFDiag(E);
8715       return false;
8716     }
8717     return Success(Info.ArrayInitIndex, E);
8718   }
8719 
8720   // Note, GNU defines __null as an integer, not a pointer.
8721   bool VisitGNUNullExpr(const GNUNullExpr *E) {
8722     return ZeroInitialization(E);
8723   }
8724 
8725   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
8726     return Success(E->getValue(), E);
8727   }
8728 
8729   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
8730     return Success(E->getValue(), E);
8731   }
8732 
8733   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
8734     return Success(E->getValue(), E);
8735   }
8736 
8737   bool VisitUnaryReal(const UnaryOperator *E);
8738   bool VisitUnaryImag(const UnaryOperator *E);
8739 
8740   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
8741   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
8742   bool VisitSourceLocExpr(const SourceLocExpr *E);
8743   // FIXME: Missing: array subscript of vector, member of vector
8744 };
8745 
8746 class FixedPointExprEvaluator
8747     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
8748   APValue &Result;
8749 
8750  public:
8751   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
8752       : ExprEvaluatorBaseTy(info), Result(result) {}
8753 
8754   bool Success(const llvm::APInt &I, const Expr *E) {
8755     return Success(
8756         APFixedPoint(I, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8757   }
8758 
8759   bool Success(uint64_t Value, const Expr *E) {
8760     return Success(
8761         APFixedPoint(Value, Info.Ctx.getFixedPointSemantics(E->getType())), E);
8762   }
8763 
8764   bool Success(const APValue &V, const Expr *E) {
8765     return Success(V.getFixedPoint(), E);
8766   }
8767 
8768   bool Success(const APFixedPoint &V, const Expr *E) {
8769     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
8770     assert(V.getWidth() == Info.Ctx.getIntWidth(E->getType()) &&
8771            "Invalid evaluation result.");
8772     Result = APValue(V);
8773     return true;
8774   }
8775 
8776   //===--------------------------------------------------------------------===//
8777   //                            Visitor Methods
8778   //===--------------------------------------------------------------------===//
8779 
8780   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
8781     return Success(E->getValue(), E);
8782   }
8783 
8784   bool VisitCastExpr(const CastExpr *E);
8785   bool VisitUnaryOperator(const UnaryOperator *E);
8786   bool VisitBinaryOperator(const BinaryOperator *E);
8787 };
8788 } // end anonymous namespace
8789 
8790 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
8791 /// produce either the integer value or a pointer.
8792 ///
8793 /// GCC has a heinous extension which folds casts between pointer types and
8794 /// pointer-sized integral types. We support this by allowing the evaluation of
8795 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
8796 /// Some simple arithmetic on such values is supported (they are treated much
8797 /// like char*).
8798 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
8799                                     EvalInfo &Info) {
8800   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
8801   return IntExprEvaluator(Info, Result).Visit(E);
8802 }
8803 
8804 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
8805   APValue Val;
8806   if (!EvaluateIntegerOrLValue(E, Val, Info))
8807     return false;
8808   if (!Val.isInt()) {
8809     // FIXME: It would be better to produce the diagnostic for casting
8810     //        a pointer to an integer.
8811     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8812     return false;
8813   }
8814   Result = Val.getInt();
8815   return true;
8816 }
8817 
8818 bool IntExprEvaluator::VisitSourceLocExpr(const SourceLocExpr *E) {
8819   APValue Evaluated = E->EvaluateInContext(
8820       Info.Ctx, Info.CurrentCall->CurSourceLocExprScope.getDefaultExpr());
8821   return Success(Evaluated, E);
8822 }
8823 
8824 static bool EvaluateFixedPoint(const Expr *E, APFixedPoint &Result,
8825                                EvalInfo &Info) {
8826   if (E->getType()->isFixedPointType()) {
8827     APValue Val;
8828     if (!FixedPointExprEvaluator(Info, Val).Visit(E))
8829       return false;
8830     if (!Val.isFixedPoint())
8831       return false;
8832 
8833     Result = Val.getFixedPoint();
8834     return true;
8835   }
8836   return false;
8837 }
8838 
8839 static bool EvaluateFixedPointOrInteger(const Expr *E, APFixedPoint &Result,
8840                                         EvalInfo &Info) {
8841   if (E->getType()->isIntegerType()) {
8842     auto FXSema = Info.Ctx.getFixedPointSemantics(E->getType());
8843     APSInt Val;
8844     if (!EvaluateInteger(E, Val, Info))
8845       return false;
8846     Result = APFixedPoint(Val, FXSema);
8847     return true;
8848   } else if (E->getType()->isFixedPointType()) {
8849     return EvaluateFixedPoint(E, Result, Info);
8850   }
8851   return false;
8852 }
8853 
8854 /// Check whether the given declaration can be directly converted to an integral
8855 /// rvalue. If not, no diagnostic is produced; there are other things we can
8856 /// try.
8857 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
8858   // Enums are integer constant exprs.
8859   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
8860     // Check for signedness/width mismatches between E type and ECD value.
8861     bool SameSign = (ECD->getInitVal().isSigned()
8862                      == E->getType()->isSignedIntegerOrEnumerationType());
8863     bool SameWidth = (ECD->getInitVal().getBitWidth()
8864                       == Info.Ctx.getIntWidth(E->getType()));
8865     if (SameSign && SameWidth)
8866       return Success(ECD->getInitVal(), E);
8867     else {
8868       // Get rid of mismatch (otherwise Success assertions will fail)
8869       // by computing a new value matching the type of E.
8870       llvm::APSInt Val = ECD->getInitVal();
8871       if (!SameSign)
8872         Val.setIsSigned(!ECD->getInitVal().isSigned());
8873       if (!SameWidth)
8874         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
8875       return Success(Val, E);
8876     }
8877   }
8878   return false;
8879 }
8880 
8881 /// Values returned by __builtin_classify_type, chosen to match the values
8882 /// produced by GCC's builtin.
8883 enum class GCCTypeClass {
8884   None = -1,
8885   Void = 0,
8886   Integer = 1,
8887   // GCC reserves 2 for character types, but instead classifies them as
8888   // integers.
8889   Enum = 3,
8890   Bool = 4,
8891   Pointer = 5,
8892   // GCC reserves 6 for references, but appears to never use it (because
8893   // expressions never have reference type, presumably).
8894   PointerToDataMember = 7,
8895   RealFloat = 8,
8896   Complex = 9,
8897   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
8898   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
8899   // GCC claims to reserve 11 for pointers to member functions, but *actually*
8900   // uses 12 for that purpose, same as for a class or struct. Maybe it
8901   // internally implements a pointer to member as a struct?  Who knows.
8902   PointerToMemberFunction = 12, // Not a bug, see above.
8903   ClassOrStruct = 12,
8904   Union = 13,
8905   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
8906   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
8907   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
8908   // literals.
8909 };
8910 
8911 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
8912 /// as GCC.
8913 static GCCTypeClass
8914 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
8915   assert(!T->isDependentType() && "unexpected dependent type");
8916 
8917   QualType CanTy = T.getCanonicalType();
8918   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
8919 
8920   switch (CanTy->getTypeClass()) {
8921 #define TYPE(ID, BASE)
8922 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
8923 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
8924 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
8925 #include "clang/AST/TypeNodes.def"
8926   case Type::Auto:
8927   case Type::DeducedTemplateSpecialization:
8928       llvm_unreachable("unexpected non-canonical or dependent type");
8929 
8930   case Type::Builtin:
8931     switch (BT->getKind()) {
8932 #define BUILTIN_TYPE(ID, SINGLETON_ID)
8933 #define SIGNED_TYPE(ID, SINGLETON_ID) \
8934     case BuiltinType::ID: return GCCTypeClass::Integer;
8935 #define FLOATING_TYPE(ID, SINGLETON_ID) \
8936     case BuiltinType::ID: return GCCTypeClass::RealFloat;
8937 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
8938     case BuiltinType::ID: break;
8939 #include "clang/AST/BuiltinTypes.def"
8940     case BuiltinType::Void:
8941       return GCCTypeClass::Void;
8942 
8943     case BuiltinType::Bool:
8944       return GCCTypeClass::Bool;
8945 
8946     case BuiltinType::Char_U:
8947     case BuiltinType::UChar:
8948     case BuiltinType::WChar_U:
8949     case BuiltinType::Char8:
8950     case BuiltinType::Char16:
8951     case BuiltinType::Char32:
8952     case BuiltinType::UShort:
8953     case BuiltinType::UInt:
8954     case BuiltinType::ULong:
8955     case BuiltinType::ULongLong:
8956     case BuiltinType::UInt128:
8957       return GCCTypeClass::Integer;
8958 
8959     case BuiltinType::UShortAccum:
8960     case BuiltinType::UAccum:
8961     case BuiltinType::ULongAccum:
8962     case BuiltinType::UShortFract:
8963     case BuiltinType::UFract:
8964     case BuiltinType::ULongFract:
8965     case BuiltinType::SatUShortAccum:
8966     case BuiltinType::SatUAccum:
8967     case BuiltinType::SatULongAccum:
8968     case BuiltinType::SatUShortFract:
8969     case BuiltinType::SatUFract:
8970     case BuiltinType::SatULongFract:
8971       return GCCTypeClass::None;
8972 
8973     case BuiltinType::NullPtr:
8974 
8975     case BuiltinType::ObjCId:
8976     case BuiltinType::ObjCClass:
8977     case BuiltinType::ObjCSel:
8978 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8979     case BuiltinType::Id:
8980 #include "clang/Basic/OpenCLImageTypes.def"
8981 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
8982     case BuiltinType::Id:
8983 #include "clang/Basic/OpenCLExtensionTypes.def"
8984     case BuiltinType::OCLSampler:
8985     case BuiltinType::OCLEvent:
8986     case BuiltinType::OCLClkEvent:
8987     case BuiltinType::OCLQueue:
8988     case BuiltinType::OCLReserveID:
8989 #define SVE_TYPE(Name, Id, SingletonId) \
8990     case BuiltinType::Id:
8991 #include "clang/Basic/AArch64SVEACLETypes.def"
8992       return GCCTypeClass::None;
8993 
8994     case BuiltinType::Dependent:
8995       llvm_unreachable("unexpected dependent type");
8996     };
8997     llvm_unreachable("unexpected placeholder type");
8998 
8999   case Type::Enum:
9000     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
9001 
9002   case Type::Pointer:
9003   case Type::ConstantArray:
9004   case Type::VariableArray:
9005   case Type::IncompleteArray:
9006   case Type::FunctionNoProto:
9007   case Type::FunctionProto:
9008     return GCCTypeClass::Pointer;
9009 
9010   case Type::MemberPointer:
9011     return CanTy->isMemberDataPointerType()
9012                ? GCCTypeClass::PointerToDataMember
9013                : GCCTypeClass::PointerToMemberFunction;
9014 
9015   case Type::Complex:
9016     return GCCTypeClass::Complex;
9017 
9018   case Type::Record:
9019     return CanTy->isUnionType() ? GCCTypeClass::Union
9020                                 : GCCTypeClass::ClassOrStruct;
9021 
9022   case Type::Atomic:
9023     // GCC classifies _Atomic T the same as T.
9024     return EvaluateBuiltinClassifyType(
9025         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
9026 
9027   case Type::BlockPointer:
9028   case Type::Vector:
9029   case Type::ExtVector:
9030   case Type::ObjCObject:
9031   case Type::ObjCInterface:
9032   case Type::ObjCObjectPointer:
9033   case Type::Pipe:
9034     // GCC classifies vectors as None. We follow its lead and classify all
9035     // other types that don't fit into the regular classification the same way.
9036     return GCCTypeClass::None;
9037 
9038   case Type::LValueReference:
9039   case Type::RValueReference:
9040     llvm_unreachable("invalid type for expression");
9041   }
9042 
9043   llvm_unreachable("unexpected type class");
9044 }
9045 
9046 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9047 /// as GCC.
9048 static GCCTypeClass
9049 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9050   // If no argument was supplied, default to None. This isn't
9051   // ideal, however it is what gcc does.
9052   if (E->getNumArgs() == 0)
9053     return GCCTypeClass::None;
9054 
9055   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9056   // being an ICE, but still folds it to a constant using the type of the first
9057   // argument.
9058   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
9059 }
9060 
9061 /// EvaluateBuiltinConstantPForLValue - Determine the result of
9062 /// __builtin_constant_p when applied to the given pointer.
9063 ///
9064 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
9065 /// or it points to the first character of a string literal.
9066 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9067   APValue::LValueBase Base = LV.getLValueBase();
9068   if (Base.isNull()) {
9069     // A null base is acceptable.
9070     return true;
9071   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9072     if (!isa<StringLiteral>(E))
9073       return false;
9074     return LV.getLValueOffset().isZero();
9075   } else if (Base.is<TypeInfoLValue>()) {
9076     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9077     // evaluate to true.
9078     return true;
9079   } else {
9080     // Any other base is not constant enough for GCC.
9081     return false;
9082   }
9083 }
9084 
9085 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9086 /// GCC as we can manage.
9087 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
9088   // This evaluation is not permitted to have side-effects, so evaluate it in
9089   // a speculative evaluation context.
9090   SpeculativeEvaluationRAII SpeculativeEval(Info);
9091 
9092   // Constant-folding is always enabled for the operand of __builtin_constant_p
9093   // (even when the enclosing evaluation context otherwise requires a strict
9094   // language-specific constant expression).
9095   FoldConstant Fold(Info, true);
9096 
9097   QualType ArgType = Arg->getType();
9098 
9099   // __builtin_constant_p always has one operand. The rules which gcc follows
9100   // are not precisely documented, but are as follows:
9101   //
9102   //  - If the operand is of integral, floating, complex or enumeration type,
9103   //    and can be folded to a known value of that type, it returns 1.
9104   //  - If the operand can be folded to a pointer to the first character
9105   //    of a string literal (or such a pointer cast to an integral type)
9106   //    or to a null pointer or an integer cast to a pointer, it returns 1.
9107   //
9108   // Otherwise, it returns 0.
9109   //
9110   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
9111   // its support for this did not work prior to GCC 9 and is not yet well
9112   // understood.
9113   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9114       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9115       ArgType->isNullPtrType()) {
9116     APValue V;
9117     if (!::EvaluateAsRValue(Info, Arg, V)) {
9118       Fold.keepDiagnostics();
9119       return false;
9120     }
9121 
9122     // For a pointer (possibly cast to integer), there are special rules.
9123     if (V.getKind() == APValue::LValue)
9124       return EvaluateBuiltinConstantPForLValue(V);
9125 
9126     // Otherwise, any constant value is good enough.
9127     return V.hasValue();
9128   }
9129 
9130   // Anything else isn't considered to be sufficiently constant.
9131   return false;
9132 }
9133 
9134 /// Retrieves the "underlying object type" of the given expression,
9135 /// as used by __builtin_object_size.
9136 static QualType getObjectType(APValue::LValueBase B) {
9137   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9138     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9139       return VD->getType();
9140   } else if (const Expr *E = B.get<const Expr*>()) {
9141     if (isa<CompoundLiteralExpr>(E))
9142       return E->getType();
9143   } else if (B.is<TypeInfoLValue>()) {
9144     return B.getTypeInfoType();
9145   }
9146 
9147   return QualType();
9148 }
9149 
9150 /// A more selective version of E->IgnoreParenCasts for
9151 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
9152 /// to change the type of E.
9153 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9154 ///
9155 /// Always returns an RValue with a pointer representation.
9156 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9157   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9158 
9159   auto *NoParens = E->IgnoreParens();
9160   auto *Cast = dyn_cast<CastExpr>(NoParens);
9161   if (Cast == nullptr)
9162     return NoParens;
9163 
9164   // We only conservatively allow a few kinds of casts, because this code is
9165   // inherently a simple solution that seeks to support the common case.
9166   auto CastKind = Cast->getCastKind();
9167   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9168       CastKind != CK_AddressSpaceConversion)
9169     return NoParens;
9170 
9171   auto *SubExpr = Cast->getSubExpr();
9172   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9173     return NoParens;
9174   return ignorePointerCastsAndParens(SubExpr);
9175 }
9176 
9177 /// Checks to see if the given LValue's Designator is at the end of the LValue's
9178 /// record layout. e.g.
9179 ///   struct { struct { int a, b; } fst, snd; } obj;
9180 ///   obj.fst   // no
9181 ///   obj.snd   // yes
9182 ///   obj.fst.a // no
9183 ///   obj.fst.b // no
9184 ///   obj.snd.a // no
9185 ///   obj.snd.b // yes
9186 ///
9187 /// Please note: this function is specialized for how __builtin_object_size
9188 /// views "objects".
9189 ///
9190 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
9191 /// correct result, it will always return true.
9192 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9193   assert(!LVal.Designator.Invalid);
9194 
9195   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9196     const RecordDecl *Parent = FD->getParent();
9197     Invalid = Parent->isInvalidDecl();
9198     if (Invalid || Parent->isUnion())
9199       return true;
9200     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
9201     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9202   };
9203 
9204   auto &Base = LVal.getLValueBase();
9205   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9206     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9207       bool Invalid;
9208       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9209         return Invalid;
9210     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
9211       for (auto *FD : IFD->chain()) {
9212         bool Invalid;
9213         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9214           return Invalid;
9215       }
9216     }
9217   }
9218 
9219   unsigned I = 0;
9220   QualType BaseType = getType(Base);
9221   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
9222     // If we don't know the array bound, conservatively assume we're looking at
9223     // the final array element.
9224     ++I;
9225     if (BaseType->isIncompleteArrayType())
9226       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9227     else
9228       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
9229   }
9230 
9231   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9232     const auto &Entry = LVal.Designator.Entries[I];
9233     if (BaseType->isArrayType()) {
9234       // Because __builtin_object_size treats arrays as objects, we can ignore
9235       // the index iff this is the last array in the Designator.
9236       if (I + 1 == E)
9237         return true;
9238       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
9239       uint64_t Index = Entry.getAsArrayIndex();
9240       if (Index + 1 != CAT->getSize())
9241         return false;
9242       BaseType = CAT->getElementType();
9243     } else if (BaseType->isAnyComplexType()) {
9244       const auto *CT = BaseType->castAs<ComplexType>();
9245       uint64_t Index = Entry.getAsArrayIndex();
9246       if (Index != 1)
9247         return false;
9248       BaseType = CT->getElementType();
9249     } else if (auto *FD = getAsField(Entry)) {
9250       bool Invalid;
9251       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9252         return Invalid;
9253       BaseType = FD->getType();
9254     } else {
9255       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
9256       return false;
9257     }
9258   }
9259   return true;
9260 }
9261 
9262 /// Tests to see if the LValue has a user-specified designator (that isn't
9263 /// necessarily valid). Note that this always returns 'true' if the LValue has
9264 /// an unsized array as its first designator entry, because there's currently no
9265 /// way to tell if the user typed *foo or foo[0].
9266 static bool refersToCompleteObject(const LValue &LVal) {
9267   if (LVal.Designator.Invalid)
9268     return false;
9269 
9270   if (!LVal.Designator.Entries.empty())
9271     return LVal.Designator.isMostDerivedAnUnsizedArray();
9272 
9273   if (!LVal.InvalidBase)
9274     return true;
9275 
9276   // If `E` is a MemberExpr, then the first part of the designator is hiding in
9277   // the LValueBase.
9278   const auto *E = LVal.Base.dyn_cast<const Expr *>();
9279   return !E || !isa<MemberExpr>(E);
9280 }
9281 
9282 /// Attempts to detect a user writing into a piece of memory that's impossible
9283 /// to figure out the size of by just using types.
9284 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9285   const SubobjectDesignator &Designator = LVal.Designator;
9286   // Notes:
9287   // - Users can only write off of the end when we have an invalid base. Invalid
9288   //   bases imply we don't know where the memory came from.
9289   // - We used to be a bit more aggressive here; we'd only be conservative if
9290   //   the array at the end was flexible, or if it had 0 or 1 elements. This
9291   //   broke some common standard library extensions (PR30346), but was
9292   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
9293   //   with some sort of whitelist. OTOH, it seems that GCC is always
9294   //   conservative with the last element in structs (if it's an array), so our
9295   //   current behavior is more compatible than a whitelisting approach would
9296   //   be.
9297   return LVal.InvalidBase &&
9298          Designator.Entries.size() == Designator.MostDerivedPathLength &&
9299          Designator.MostDerivedIsArrayElement &&
9300          isDesignatorAtObjectEnd(Ctx, LVal);
9301 }
9302 
9303 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9304 /// Fails if the conversion would cause loss of precision.
9305 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9306                                             CharUnits &Result) {
9307   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9308   if (Int.ugt(CharUnitsMax))
9309     return false;
9310   Result = CharUnits::fromQuantity(Int.getZExtValue());
9311   return true;
9312 }
9313 
9314 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9315 /// determine how many bytes exist from the beginning of the object to either
9316 /// the end of the current subobject, or the end of the object itself, depending
9317 /// on what the LValue looks like + the value of Type.
9318 ///
9319 /// If this returns false, the value of Result is undefined.
9320 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9321                                unsigned Type, const LValue &LVal,
9322                                CharUnits &EndOffset) {
9323   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
9324 
9325   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9326     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9327       return false;
9328     return HandleSizeof(Info, ExprLoc, Ty, Result);
9329   };
9330 
9331   // We want to evaluate the size of the entire object. This is a valid fallback
9332   // for when Type=1 and the designator is invalid, because we're asked for an
9333   // upper-bound.
9334   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9335     // Type=3 wants a lower bound, so we can't fall back to this.
9336     if (Type == 3 && !DetermineForCompleteObject)
9337       return false;
9338 
9339     llvm::APInt APEndOffset;
9340     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9341         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9342       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9343 
9344     if (LVal.InvalidBase)
9345       return false;
9346 
9347     QualType BaseTy = getObjectType(LVal.getLValueBase());
9348     return CheckedHandleSizeof(BaseTy, EndOffset);
9349   }
9350 
9351   // We want to evaluate the size of a subobject.
9352   const SubobjectDesignator &Designator = LVal.Designator;
9353 
9354   // The following is a moderately common idiom in C:
9355   //
9356   // struct Foo { int a; char c[1]; };
9357   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9358   // strcpy(&F->c[0], Bar);
9359   //
9360   // In order to not break too much legacy code, we need to support it.
9361   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9362     // If we can resolve this to an alloc_size call, we can hand that back,
9363     // because we know for certain how many bytes there are to write to.
9364     llvm::APInt APEndOffset;
9365     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9366         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9367       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9368 
9369     // If we cannot determine the size of the initial allocation, then we can't
9370     // given an accurate upper-bound. However, we are still able to give
9371     // conservative lower-bounds for Type=3.
9372     if (Type == 1)
9373       return false;
9374   }
9375 
9376   CharUnits BytesPerElem;
9377   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
9378     return false;
9379 
9380   // According to the GCC documentation, we want the size of the subobject
9381   // denoted by the pointer. But that's not quite right -- what we actually
9382   // want is the size of the immediately-enclosing array, if there is one.
9383   int64_t ElemsRemaining;
9384   if (Designator.MostDerivedIsArrayElement &&
9385       Designator.Entries.size() == Designator.MostDerivedPathLength) {
9386     uint64_t ArraySize = Designator.getMostDerivedArraySize();
9387     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
9388     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9389   } else {
9390     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9391   }
9392 
9393   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9394   return true;
9395 }
9396 
9397 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
9398 /// returns true and stores the result in @p Size.
9399 ///
9400 /// If @p WasError is non-null, this will report whether the failure to evaluate
9401 /// is to be treated as an Error in IntExprEvaluator.
9402 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9403                                          EvalInfo &Info, uint64_t &Size) {
9404   // Determine the denoted object.
9405   LValue LVal;
9406   {
9407     // The operand of __builtin_object_size is never evaluated for side-effects.
9408     // If there are any, but we can determine the pointed-to object anyway, then
9409     // ignore the side-effects.
9410     SpeculativeEvaluationRAII SpeculativeEval(Info);
9411     IgnoreSideEffectsRAII Fold(Info);
9412 
9413     if (E->isGLValue()) {
9414       // It's possible for us to be given GLValues if we're called via
9415       // Expr::tryEvaluateObjectSize.
9416       APValue RVal;
9417       if (!EvaluateAsRValue(Info, E, RVal))
9418         return false;
9419       LVal.setFrom(Info.Ctx, RVal);
9420     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9421                                 /*InvalidBaseOK=*/true))
9422       return false;
9423   }
9424 
9425   // If we point to before the start of the object, there are no accessible
9426   // bytes.
9427   if (LVal.getLValueOffset().isNegative()) {
9428     Size = 0;
9429     return true;
9430   }
9431 
9432   CharUnits EndOffset;
9433   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9434     return false;
9435 
9436   // If we've fallen outside of the end offset, just pretend there's nothing to
9437   // write to/read from.
9438   if (EndOffset <= LVal.getLValueOffset())
9439     Size = 0;
9440   else
9441     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9442   return true;
9443 }
9444 
9445 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9446   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
9447   if (E->getResultAPValueKind() != APValue::None)
9448     return Success(E->getAPValueResult(), E);
9449   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9450 }
9451 
9452 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
9453   if (unsigned BuiltinOp = E->getBuiltinCallee())
9454     return VisitBuiltinCallExpr(E, BuiltinOp);
9455 
9456   return ExprEvaluatorBaseTy::VisitCallExpr(E);
9457 }
9458 
9459 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9460                                             unsigned BuiltinOp) {
9461   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
9462   default:
9463     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9464 
9465   case Builtin::BI__builtin_dynamic_object_size:
9466   case Builtin::BI__builtin_object_size: {
9467     // The type was checked when we built the expression.
9468     unsigned Type =
9469         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9470     assert(Type <= 3 && "unexpected type");
9471 
9472     uint64_t Size;
9473     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9474       return Success(Size, E);
9475 
9476     if (E->getArg(0)->HasSideEffects(Info.Ctx))
9477       return Success((Type & 2) ? 0 : -1, E);
9478 
9479     // Expression had no side effects, but we couldn't statically determine the
9480     // size of the referenced object.
9481     switch (Info.EvalMode) {
9482     case EvalInfo::EM_ConstantExpression:
9483     case EvalInfo::EM_ConstantFold:
9484     case EvalInfo::EM_IgnoreSideEffects:
9485       // Leave it to IR generation.
9486       return Error(E);
9487     case EvalInfo::EM_ConstantExpressionUnevaluated:
9488       // Reduce it to a constant now.
9489       return Success((Type & 2) ? 0 : -1, E);
9490     }
9491 
9492     llvm_unreachable("unexpected EvalMode");
9493   }
9494 
9495   case Builtin::BI__builtin_os_log_format_buffer_size: {
9496     analyze_os_log::OSLogBufferLayout Layout;
9497     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9498     return Success(Layout.size().getQuantity(), E);
9499   }
9500 
9501   case Builtin::BI__builtin_bswap16:
9502   case Builtin::BI__builtin_bswap32:
9503   case Builtin::BI__builtin_bswap64: {
9504     APSInt Val;
9505     if (!EvaluateInteger(E->getArg(0), Val, Info))
9506       return false;
9507 
9508     return Success(Val.byteSwap(), E);
9509   }
9510 
9511   case Builtin::BI__builtin_classify_type:
9512     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9513 
9514   case Builtin::BI__builtin_clrsb:
9515   case Builtin::BI__builtin_clrsbl:
9516   case Builtin::BI__builtin_clrsbll: {
9517     APSInt Val;
9518     if (!EvaluateInteger(E->getArg(0), Val, Info))
9519       return false;
9520 
9521     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9522   }
9523 
9524   case Builtin::BI__builtin_clz:
9525   case Builtin::BI__builtin_clzl:
9526   case Builtin::BI__builtin_clzll:
9527   case Builtin::BI__builtin_clzs: {
9528     APSInt Val;
9529     if (!EvaluateInteger(E->getArg(0), Val, Info))
9530       return false;
9531     if (!Val)
9532       return Error(E);
9533 
9534     return Success(Val.countLeadingZeros(), E);
9535   }
9536 
9537   case Builtin::BI__builtin_constant_p: {
9538     const Expr *Arg = E->getArg(0);
9539     if (EvaluateBuiltinConstantP(Info, Arg))
9540       return Success(true, E);
9541     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9542       // Outside a constant context, eagerly evaluate to false in the presence
9543       // of side-effects in order to avoid -Wunsequenced false-positives in
9544       // a branch on __builtin_constant_p(expr).
9545       return Success(false, E);
9546     }
9547     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9548     return false;
9549   }
9550 
9551   case Builtin::BI__builtin_is_constant_evaluated:
9552     return Success(Info.InConstantContext, E);
9553 
9554   case Builtin::BI__builtin_ctz:
9555   case Builtin::BI__builtin_ctzl:
9556   case Builtin::BI__builtin_ctzll:
9557   case Builtin::BI__builtin_ctzs: {
9558     APSInt Val;
9559     if (!EvaluateInteger(E->getArg(0), Val, Info))
9560       return false;
9561     if (!Val)
9562       return Error(E);
9563 
9564     return Success(Val.countTrailingZeros(), E);
9565   }
9566 
9567   case Builtin::BI__builtin_eh_return_data_regno: {
9568     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9569     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9570     return Success(Operand, E);
9571   }
9572 
9573   case Builtin::BI__builtin_expect:
9574     return Visit(E->getArg(0));
9575 
9576   case Builtin::BI__builtin_ffs:
9577   case Builtin::BI__builtin_ffsl:
9578   case Builtin::BI__builtin_ffsll: {
9579     APSInt Val;
9580     if (!EvaluateInteger(E->getArg(0), Val, Info))
9581       return false;
9582 
9583     unsigned N = Val.countTrailingZeros();
9584     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9585   }
9586 
9587   case Builtin::BI__builtin_fpclassify: {
9588     APFloat Val(0.0);
9589     if (!EvaluateFloat(E->getArg(5), Val, Info))
9590       return false;
9591     unsigned Arg;
9592     switch (Val.getCategory()) {
9593     case APFloat::fcNaN: Arg = 0; break;
9594     case APFloat::fcInfinity: Arg = 1; break;
9595     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9596     case APFloat::fcZero: Arg = 4; break;
9597     }
9598     return Visit(E->getArg(Arg));
9599   }
9600 
9601   case Builtin::BI__builtin_isinf_sign: {
9602     APFloat Val(0.0);
9603     return EvaluateFloat(E->getArg(0), Val, Info) &&
9604            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9605   }
9606 
9607   case Builtin::BI__builtin_isinf: {
9608     APFloat Val(0.0);
9609     return EvaluateFloat(E->getArg(0), Val, Info) &&
9610            Success(Val.isInfinity() ? 1 : 0, E);
9611   }
9612 
9613   case Builtin::BI__builtin_isfinite: {
9614     APFloat Val(0.0);
9615     return EvaluateFloat(E->getArg(0), Val, Info) &&
9616            Success(Val.isFinite() ? 1 : 0, E);
9617   }
9618 
9619   case Builtin::BI__builtin_isnan: {
9620     APFloat Val(0.0);
9621     return EvaluateFloat(E->getArg(0), Val, Info) &&
9622            Success(Val.isNaN() ? 1 : 0, E);
9623   }
9624 
9625   case Builtin::BI__builtin_isnormal: {
9626     APFloat Val(0.0);
9627     return EvaluateFloat(E->getArg(0), Val, Info) &&
9628            Success(Val.isNormal() ? 1 : 0, E);
9629   }
9630 
9631   case Builtin::BI__builtin_parity:
9632   case Builtin::BI__builtin_parityl:
9633   case Builtin::BI__builtin_parityll: {
9634     APSInt Val;
9635     if (!EvaluateInteger(E->getArg(0), Val, Info))
9636       return false;
9637 
9638     return Success(Val.countPopulation() % 2, E);
9639   }
9640 
9641   case Builtin::BI__builtin_popcount:
9642   case Builtin::BI__builtin_popcountl:
9643   case Builtin::BI__builtin_popcountll: {
9644     APSInt Val;
9645     if (!EvaluateInteger(E->getArg(0), Val, Info))
9646       return false;
9647 
9648     return Success(Val.countPopulation(), E);
9649   }
9650 
9651   case Builtin::BIstrlen:
9652   case Builtin::BIwcslen:
9653     // A call to strlen is not a constant expression.
9654     if (Info.getLangOpts().CPlusPlus11)
9655       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9656         << /*isConstexpr*/0 << /*isConstructor*/0
9657         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9658     else
9659       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9660     LLVM_FALLTHROUGH;
9661   case Builtin::BI__builtin_strlen:
9662   case Builtin::BI__builtin_wcslen: {
9663     // As an extension, we support __builtin_strlen() as a constant expression,
9664     // and support folding strlen() to a constant.
9665     LValue String;
9666     if (!EvaluatePointer(E->getArg(0), String, Info))
9667       return false;
9668 
9669     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9670 
9671     // Fast path: if it's a string literal, search the string value.
9672     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9673             String.getLValueBase().dyn_cast<const Expr *>())) {
9674       // The string literal may have embedded null characters. Find the first
9675       // one and truncate there.
9676       StringRef Str = S->getBytes();
9677       int64_t Off = String.Offset.getQuantity();
9678       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9679           S->getCharByteWidth() == 1 &&
9680           // FIXME: Add fast-path for wchar_t too.
9681           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9682         Str = Str.substr(Off);
9683 
9684         StringRef::size_type Pos = Str.find(0);
9685         if (Pos != StringRef::npos)
9686           Str = Str.substr(0, Pos);
9687 
9688         return Success(Str.size(), E);
9689       }
9690 
9691       // Fall through to slow path to issue appropriate diagnostic.
9692     }
9693 
9694     // Slow path: scan the bytes of the string looking for the terminating 0.
9695     for (uint64_t Strlen = 0; /**/; ++Strlen) {
9696       APValue Char;
9697       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9698           !Char.isInt())
9699         return false;
9700       if (!Char.getInt())
9701         return Success(Strlen, E);
9702       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9703         return false;
9704     }
9705   }
9706 
9707   case Builtin::BIstrcmp:
9708   case Builtin::BIwcscmp:
9709   case Builtin::BIstrncmp:
9710   case Builtin::BIwcsncmp:
9711   case Builtin::BImemcmp:
9712   case Builtin::BIbcmp:
9713   case Builtin::BIwmemcmp:
9714     // A call to strlen is not a constant expression.
9715     if (Info.getLangOpts().CPlusPlus11)
9716       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9717         << /*isConstexpr*/0 << /*isConstructor*/0
9718         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9719     else
9720       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9721     LLVM_FALLTHROUGH;
9722   case Builtin::BI__builtin_strcmp:
9723   case Builtin::BI__builtin_wcscmp:
9724   case Builtin::BI__builtin_strncmp:
9725   case Builtin::BI__builtin_wcsncmp:
9726   case Builtin::BI__builtin_memcmp:
9727   case Builtin::BI__builtin_bcmp:
9728   case Builtin::BI__builtin_wmemcmp: {
9729     LValue String1, String2;
9730     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9731         !EvaluatePointer(E->getArg(1), String2, Info))
9732       return false;
9733 
9734     uint64_t MaxLength = uint64_t(-1);
9735     if (BuiltinOp != Builtin::BIstrcmp &&
9736         BuiltinOp != Builtin::BIwcscmp &&
9737         BuiltinOp != Builtin::BI__builtin_strcmp &&
9738         BuiltinOp != Builtin::BI__builtin_wcscmp) {
9739       APSInt N;
9740       if (!EvaluateInteger(E->getArg(2), N, Info))
9741         return false;
9742       MaxLength = N.getExtValue();
9743     }
9744 
9745     // Empty substrings compare equal by definition.
9746     if (MaxLength == 0u)
9747       return Success(0, E);
9748 
9749     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9750         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9751         String1.Designator.Invalid || String2.Designator.Invalid)
9752       return false;
9753 
9754     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9755     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9756 
9757     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9758                      BuiltinOp == Builtin::BIbcmp ||
9759                      BuiltinOp == Builtin::BI__builtin_memcmp ||
9760                      BuiltinOp == Builtin::BI__builtin_bcmp;
9761 
9762     assert(IsRawByte ||
9763            (Info.Ctx.hasSameUnqualifiedType(
9764                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9765             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9766 
9767     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9768       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9769              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9770              Char1.isInt() && Char2.isInt();
9771     };
9772     const auto &AdvanceElems = [&] {
9773       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9774              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9775     };
9776 
9777     if (IsRawByte) {
9778       uint64_t BytesRemaining = MaxLength;
9779       // Pointers to const void may point to objects of incomplete type.
9780       if (CharTy1->isIncompleteType()) {
9781         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9782         return false;
9783       }
9784       if (CharTy2->isIncompleteType()) {
9785         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9786         return false;
9787       }
9788       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9789       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9790       // Give up on comparing between elements with disparate widths.
9791       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9792         return false;
9793       uint64_t BytesPerElement = CharTy1Size.getQuantity();
9794       assert(BytesRemaining && "BytesRemaining should not be zero: the "
9795                                "following loop considers at least one element");
9796       while (true) {
9797         APValue Char1, Char2;
9798         if (!ReadCurElems(Char1, Char2))
9799           return false;
9800         // We have compatible in-memory widths, but a possible type and
9801         // (for `bool`) internal representation mismatch.
9802         // Assuming two's complement representation, including 0 for `false` and
9803         // 1 for `true`, we can check an appropriate number of elements for
9804         // equality even if they are not byte-sized.
9805         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9806         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9807         if (Char1InMem.ne(Char2InMem)) {
9808           // If the elements are byte-sized, then we can produce a three-way
9809           // comparison result in a straightforward manner.
9810           if (BytesPerElement == 1u) {
9811             // memcmp always compares unsigned chars.
9812             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9813           }
9814           // The result is byte-order sensitive, and we have multibyte elements.
9815           // FIXME: We can compare the remaining bytes in the correct order.
9816           return false;
9817         }
9818         if (!AdvanceElems())
9819           return false;
9820         if (BytesRemaining <= BytesPerElement)
9821           break;
9822         BytesRemaining -= BytesPerElement;
9823       }
9824       // Enough elements are equal to account for the memcmp limit.
9825       return Success(0, E);
9826     }
9827 
9828     bool StopAtNull =
9829         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9830          BuiltinOp != Builtin::BIwmemcmp &&
9831          BuiltinOp != Builtin::BI__builtin_memcmp &&
9832          BuiltinOp != Builtin::BI__builtin_bcmp &&
9833          BuiltinOp != Builtin::BI__builtin_wmemcmp);
9834     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9835                   BuiltinOp == Builtin::BIwcsncmp ||
9836                   BuiltinOp == Builtin::BIwmemcmp ||
9837                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
9838                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9839                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
9840 
9841     for (; MaxLength; --MaxLength) {
9842       APValue Char1, Char2;
9843       if (!ReadCurElems(Char1, Char2))
9844         return false;
9845       if (Char1.getInt() != Char2.getInt()) {
9846         if (IsWide) // wmemcmp compares with wchar_t signedness.
9847           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9848         // memcmp always compares unsigned chars.
9849         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9850       }
9851       if (StopAtNull && !Char1.getInt())
9852         return Success(0, E);
9853       assert(!(StopAtNull && !Char2.getInt()));
9854       if (!AdvanceElems())
9855         return false;
9856     }
9857     // We hit the strncmp / memcmp limit.
9858     return Success(0, E);
9859   }
9860 
9861   case Builtin::BI__atomic_always_lock_free:
9862   case Builtin::BI__atomic_is_lock_free:
9863   case Builtin::BI__c11_atomic_is_lock_free: {
9864     APSInt SizeVal;
9865     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9866       return false;
9867 
9868     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9869     // of two less than the maximum inline atomic width, we know it is
9870     // lock-free.  If the size isn't a power of two, or greater than the
9871     // maximum alignment where we promote atomics, we know it is not lock-free
9872     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
9873     // the answer can only be determined at runtime; for example, 16-byte
9874     // atomics have lock-free implementations on some, but not all,
9875     // x86-64 processors.
9876 
9877     // Check power-of-two.
9878     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9879     if (Size.isPowerOfTwo()) {
9880       // Check against inlining width.
9881       unsigned InlineWidthBits =
9882           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9883       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9884         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9885             Size == CharUnits::One() ||
9886             E->getArg(1)->isNullPointerConstant(Info.Ctx,
9887                                                 Expr::NPC_NeverValueDependent))
9888           // OK, we will inline appropriately-aligned operations of this size,
9889           // and _Atomic(T) is appropriately-aligned.
9890           return Success(1, E);
9891 
9892         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9893           castAs<PointerType>()->getPointeeType();
9894         if (!PointeeType->isIncompleteType() &&
9895             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9896           // OK, we will inline operations on this object.
9897           return Success(1, E);
9898         }
9899       }
9900     }
9901 
9902     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9903         Success(0, E) : Error(E);
9904   }
9905   case Builtin::BIomp_is_initial_device:
9906     // We can decide statically which value the runtime would return if called.
9907     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9908   case Builtin::BI__builtin_add_overflow:
9909   case Builtin::BI__builtin_sub_overflow:
9910   case Builtin::BI__builtin_mul_overflow:
9911   case Builtin::BI__builtin_sadd_overflow:
9912   case Builtin::BI__builtin_uadd_overflow:
9913   case Builtin::BI__builtin_uaddl_overflow:
9914   case Builtin::BI__builtin_uaddll_overflow:
9915   case Builtin::BI__builtin_usub_overflow:
9916   case Builtin::BI__builtin_usubl_overflow:
9917   case Builtin::BI__builtin_usubll_overflow:
9918   case Builtin::BI__builtin_umul_overflow:
9919   case Builtin::BI__builtin_umull_overflow:
9920   case Builtin::BI__builtin_umulll_overflow:
9921   case Builtin::BI__builtin_saddl_overflow:
9922   case Builtin::BI__builtin_saddll_overflow:
9923   case Builtin::BI__builtin_ssub_overflow:
9924   case Builtin::BI__builtin_ssubl_overflow:
9925   case Builtin::BI__builtin_ssubll_overflow:
9926   case Builtin::BI__builtin_smul_overflow:
9927   case Builtin::BI__builtin_smull_overflow:
9928   case Builtin::BI__builtin_smulll_overflow: {
9929     LValue ResultLValue;
9930     APSInt LHS, RHS;
9931 
9932     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9933     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9934         !EvaluateInteger(E->getArg(1), RHS, Info) ||
9935         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9936       return false;
9937 
9938     APSInt Result;
9939     bool DidOverflow = false;
9940 
9941     // If the types don't have to match, enlarge all 3 to the largest of them.
9942     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9943         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9944         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9945       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9946                       ResultType->isSignedIntegerOrEnumerationType();
9947       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9948                       ResultType->isSignedIntegerOrEnumerationType();
9949       uint64_t LHSSize = LHS.getBitWidth();
9950       uint64_t RHSSize = RHS.getBitWidth();
9951       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9952       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9953 
9954       // Add an additional bit if the signedness isn't uniformly agreed to. We
9955       // could do this ONLY if there is a signed and an unsigned that both have
9956       // MaxBits, but the code to check that is pretty nasty.  The issue will be
9957       // caught in the shrink-to-result later anyway.
9958       if (IsSigned && !AllSigned)
9959         ++MaxBits;
9960 
9961       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9962       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9963       Result = APSInt(MaxBits, !IsSigned);
9964     }
9965 
9966     // Find largest int.
9967     switch (BuiltinOp) {
9968     default:
9969       llvm_unreachable("Invalid value for BuiltinOp");
9970     case Builtin::BI__builtin_add_overflow:
9971     case Builtin::BI__builtin_sadd_overflow:
9972     case Builtin::BI__builtin_saddl_overflow:
9973     case Builtin::BI__builtin_saddll_overflow:
9974     case Builtin::BI__builtin_uadd_overflow:
9975     case Builtin::BI__builtin_uaddl_overflow:
9976     case Builtin::BI__builtin_uaddll_overflow:
9977       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9978                               : LHS.uadd_ov(RHS, DidOverflow);
9979       break;
9980     case Builtin::BI__builtin_sub_overflow:
9981     case Builtin::BI__builtin_ssub_overflow:
9982     case Builtin::BI__builtin_ssubl_overflow:
9983     case Builtin::BI__builtin_ssubll_overflow:
9984     case Builtin::BI__builtin_usub_overflow:
9985     case Builtin::BI__builtin_usubl_overflow:
9986     case Builtin::BI__builtin_usubll_overflow:
9987       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9988                               : LHS.usub_ov(RHS, DidOverflow);
9989       break;
9990     case Builtin::BI__builtin_mul_overflow:
9991     case Builtin::BI__builtin_smul_overflow:
9992     case Builtin::BI__builtin_smull_overflow:
9993     case Builtin::BI__builtin_smulll_overflow:
9994     case Builtin::BI__builtin_umul_overflow:
9995     case Builtin::BI__builtin_umull_overflow:
9996     case Builtin::BI__builtin_umulll_overflow:
9997       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
9998                               : LHS.umul_ov(RHS, DidOverflow);
9999       break;
10000     }
10001 
10002     // In the case where multiple sizes are allowed, truncate and see if
10003     // the values are the same.
10004     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10005         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10006         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10007       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10008       // since it will give us the behavior of a TruncOrSelf in the case where
10009       // its parameter <= its size.  We previously set Result to be at least the
10010       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10011       // will work exactly like TruncOrSelf.
10012       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10013       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10014 
10015       if (!APSInt::isSameValue(Temp, Result))
10016         DidOverflow = true;
10017       Result = Temp;
10018     }
10019 
10020     APValue APV{Result};
10021     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10022       return false;
10023     return Success(DidOverflow, E);
10024   }
10025   }
10026 }
10027 
10028 /// Determine whether this is a pointer past the end of the complete
10029 /// object referred to by the lvalue.
10030 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10031                                             const LValue &LV) {
10032   // A null pointer can be viewed as being "past the end" but we don't
10033   // choose to look at it that way here.
10034   if (!LV.getLValueBase())
10035     return false;
10036 
10037   // If the designator is valid and refers to a subobject, we're not pointing
10038   // past the end.
10039   if (!LV.getLValueDesignator().Invalid &&
10040       !LV.getLValueDesignator().isOnePastTheEnd())
10041     return false;
10042 
10043   // A pointer to an incomplete type might be past-the-end if the type's size is
10044   // zero.  We cannot tell because the type is incomplete.
10045   QualType Ty = getType(LV.getLValueBase());
10046   if (Ty->isIncompleteType())
10047     return true;
10048 
10049   // We're a past-the-end pointer if we point to the byte after the object,
10050   // no matter what our type or path is.
10051   auto Size = Ctx.getTypeSizeInChars(Ty);
10052   return LV.getLValueOffset() == Size;
10053 }
10054 
10055 namespace {
10056 
10057 /// Data recursive integer evaluator of certain binary operators.
10058 ///
10059 /// We use a data recursive algorithm for binary operators so that we are able
10060 /// to handle extreme cases of chained binary operators without causing stack
10061 /// overflow.
10062 class DataRecursiveIntBinOpEvaluator {
10063   struct EvalResult {
10064     APValue Val;
10065     bool Failed;
10066 
10067     EvalResult() : Failed(false) { }
10068 
10069     void swap(EvalResult &RHS) {
10070       Val.swap(RHS.Val);
10071       Failed = RHS.Failed;
10072       RHS.Failed = false;
10073     }
10074   };
10075 
10076   struct Job {
10077     const Expr *E;
10078     EvalResult LHSResult; // meaningful only for binary operator expression.
10079     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
10080 
10081     Job() = default;
10082     Job(Job &&) = default;
10083 
10084     void startSpeculativeEval(EvalInfo &Info) {
10085       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
10086     }
10087 
10088   private:
10089     SpeculativeEvaluationRAII SpecEvalRAII;
10090   };
10091 
10092   SmallVector<Job, 16> Queue;
10093 
10094   IntExprEvaluator &IntEval;
10095   EvalInfo &Info;
10096   APValue &FinalResult;
10097 
10098 public:
10099   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10100     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10101 
10102   /// True if \param E is a binary operator that we are going to handle
10103   /// data recursively.
10104   /// We handle binary operators that are comma, logical, or that have operands
10105   /// with integral or enumeration type.
10106   static bool shouldEnqueue(const BinaryOperator *E) {
10107     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10108            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
10109             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10110             E->getRHS()->getType()->isIntegralOrEnumerationType());
10111   }
10112 
10113   bool Traverse(const BinaryOperator *E) {
10114     enqueue(E);
10115     EvalResult PrevResult;
10116     while (!Queue.empty())
10117       process(PrevResult);
10118 
10119     if (PrevResult.Failed) return false;
10120 
10121     FinalResult.swap(PrevResult.Val);
10122     return true;
10123   }
10124 
10125 private:
10126   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10127     return IntEval.Success(Value, E, Result);
10128   }
10129   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10130     return IntEval.Success(Value, E, Result);
10131   }
10132   bool Error(const Expr *E) {
10133     return IntEval.Error(E);
10134   }
10135   bool Error(const Expr *E, diag::kind D) {
10136     return IntEval.Error(E, D);
10137   }
10138 
10139   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10140     return Info.CCEDiag(E, D);
10141   }
10142 
10143   // Returns true if visiting the RHS is necessary, false otherwise.
10144   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10145                          bool &SuppressRHSDiags);
10146 
10147   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10148                   const BinaryOperator *E, APValue &Result);
10149 
10150   void EvaluateExpr(const Expr *E, EvalResult &Result) {
10151     Result.Failed = !Evaluate(Result.Val, Info, E);
10152     if (Result.Failed)
10153       Result.Val = APValue();
10154   }
10155 
10156   void process(EvalResult &Result);
10157 
10158   void enqueue(const Expr *E) {
10159     E = E->IgnoreParens();
10160     Queue.resize(Queue.size()+1);
10161     Queue.back().E = E;
10162     Queue.back().Kind = Job::AnyExprKind;
10163   }
10164 };
10165 
10166 }
10167 
10168 bool DataRecursiveIntBinOpEvaluator::
10169        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10170                          bool &SuppressRHSDiags) {
10171   if (E->getOpcode() == BO_Comma) {
10172     // Ignore LHS but note if we could not evaluate it.
10173     if (LHSResult.Failed)
10174       return Info.noteSideEffect();
10175     return true;
10176   }
10177 
10178   if (E->isLogicalOp()) {
10179     bool LHSAsBool;
10180     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
10181       // We were able to evaluate the LHS, see if we can get away with not
10182       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
10183       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10184         Success(LHSAsBool, E, LHSResult.Val);
10185         return false; // Ignore RHS
10186       }
10187     } else {
10188       LHSResult.Failed = true;
10189 
10190       // Since we weren't able to evaluate the left hand side, it
10191       // might have had side effects.
10192       if (!Info.noteSideEffect())
10193         return false;
10194 
10195       // We can't evaluate the LHS; however, sometimes the result
10196       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10197       // Don't ignore RHS and suppress diagnostics from this arm.
10198       SuppressRHSDiags = true;
10199     }
10200 
10201     return true;
10202   }
10203 
10204   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10205          E->getRHS()->getType()->isIntegralOrEnumerationType());
10206 
10207   if (LHSResult.Failed && !Info.noteFailure())
10208     return false; // Ignore RHS;
10209 
10210   return true;
10211 }
10212 
10213 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10214                                     bool IsSub) {
10215   // Compute the new offset in the appropriate width, wrapping at 64 bits.
10216   // FIXME: When compiling for a 32-bit target, we should use 32-bit
10217   // offsets.
10218   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10219   CharUnits &Offset = LVal.getLValueOffset();
10220   uint64_t Offset64 = Offset.getQuantity();
10221   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10222   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10223                                          : Offset64 + Index64);
10224 }
10225 
10226 bool DataRecursiveIntBinOpEvaluator::
10227        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10228                   const BinaryOperator *E, APValue &Result) {
10229   if (E->getOpcode() == BO_Comma) {
10230     if (RHSResult.Failed)
10231       return false;
10232     Result = RHSResult.Val;
10233     return true;
10234   }
10235 
10236   if (E->isLogicalOp()) {
10237     bool lhsResult, rhsResult;
10238     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10239     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
10240 
10241     if (LHSIsOK) {
10242       if (RHSIsOK) {
10243         if (E->getOpcode() == BO_LOr)
10244           return Success(lhsResult || rhsResult, E, Result);
10245         else
10246           return Success(lhsResult && rhsResult, E, Result);
10247       }
10248     } else {
10249       if (RHSIsOK) {
10250         // We can't evaluate the LHS; however, sometimes the result
10251         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10252         if (rhsResult == (E->getOpcode() == BO_LOr))
10253           return Success(rhsResult, E, Result);
10254       }
10255     }
10256 
10257     return false;
10258   }
10259 
10260   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10261          E->getRHS()->getType()->isIntegralOrEnumerationType());
10262 
10263   if (LHSResult.Failed || RHSResult.Failed)
10264     return false;
10265 
10266   const APValue &LHSVal = LHSResult.Val;
10267   const APValue &RHSVal = RHSResult.Val;
10268 
10269   // Handle cases like (unsigned long)&a + 4.
10270   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10271     Result = LHSVal;
10272     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
10273     return true;
10274   }
10275 
10276   // Handle cases like 4 + (unsigned long)&a
10277   if (E->getOpcode() == BO_Add &&
10278       RHSVal.isLValue() && LHSVal.isInt()) {
10279     Result = RHSVal;
10280     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
10281     return true;
10282   }
10283 
10284   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10285     // Handle (intptr_t)&&A - (intptr_t)&&B.
10286     if (!LHSVal.getLValueOffset().isZero() ||
10287         !RHSVal.getLValueOffset().isZero())
10288       return false;
10289     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10290     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10291     if (!LHSExpr || !RHSExpr)
10292       return false;
10293     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10294     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10295     if (!LHSAddrExpr || !RHSAddrExpr)
10296       return false;
10297     // Make sure both labels come from the same function.
10298     if (LHSAddrExpr->getLabel()->getDeclContext() !=
10299         RHSAddrExpr->getLabel()->getDeclContext())
10300       return false;
10301     Result = APValue(LHSAddrExpr, RHSAddrExpr);
10302     return true;
10303   }
10304 
10305   // All the remaining cases expect both operands to be an integer
10306   if (!LHSVal.isInt() || !RHSVal.isInt())
10307     return Error(E);
10308 
10309   // Set up the width and signedness manually, in case it can't be deduced
10310   // from the operation we're performing.
10311   // FIXME: Don't do this in the cases where we can deduce it.
10312   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10313                E->getType()->isUnsignedIntegerOrEnumerationType());
10314   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10315                          RHSVal.getInt(), Value))
10316     return false;
10317   return Success(Value, E, Result);
10318 }
10319 
10320 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
10321   Job &job = Queue.back();
10322 
10323   switch (job.Kind) {
10324     case Job::AnyExprKind: {
10325       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10326         if (shouldEnqueue(Bop)) {
10327           job.Kind = Job::BinOpKind;
10328           enqueue(Bop->getLHS());
10329           return;
10330         }
10331       }
10332 
10333       EvaluateExpr(job.E, Result);
10334       Queue.pop_back();
10335       return;
10336     }
10337 
10338     case Job::BinOpKind: {
10339       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10340       bool SuppressRHSDiags = false;
10341       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
10342         Queue.pop_back();
10343         return;
10344       }
10345       if (SuppressRHSDiags)
10346         job.startSpeculativeEval(Info);
10347       job.LHSResult.swap(Result);
10348       job.Kind = Job::BinOpVisitedLHSKind;
10349       enqueue(Bop->getRHS());
10350       return;
10351     }
10352 
10353     case Job::BinOpVisitedLHSKind: {
10354       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10355       EvalResult RHS;
10356       RHS.swap(Result);
10357       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
10358       Queue.pop_back();
10359       return;
10360     }
10361   }
10362 
10363   llvm_unreachable("Invalid Job::Kind!");
10364 }
10365 
10366 namespace {
10367 /// Used when we determine that we should fail, but can keep evaluating prior to
10368 /// noting that we had a failure.
10369 class DelayedNoteFailureRAII {
10370   EvalInfo &Info;
10371   bool NoteFailure;
10372 
10373 public:
10374   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10375       : Info(Info), NoteFailure(NoteFailure) {}
10376   ~DelayedNoteFailureRAII() {
10377     if (NoteFailure) {
10378       bool ContinueAfterFailure = Info.noteFailure();
10379       (void)ContinueAfterFailure;
10380       assert(ContinueAfterFailure &&
10381              "Shouldn't have kept evaluating on failure.");
10382     }
10383   }
10384 };
10385 }
10386 
10387 template <class SuccessCB, class AfterCB>
10388 static bool
10389 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10390                                  SuccessCB &&Success, AfterCB &&DoAfter) {
10391   assert(E->isComparisonOp() && "expected comparison operator");
10392   assert((E->getOpcode() == BO_Cmp ||
10393           E->getType()->isIntegralOrEnumerationType()) &&
10394          "unsupported binary expression evaluation");
10395   auto Error = [&](const Expr *E) {
10396     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10397     return false;
10398   };
10399 
10400   using CCR = ComparisonCategoryResult;
10401   bool IsRelational = E->isRelationalOp();
10402   bool IsEquality = E->isEqualityOp();
10403   if (E->getOpcode() == BO_Cmp) {
10404     const ComparisonCategoryInfo &CmpInfo =
10405         Info.Ctx.CompCategories.getInfoForType(E->getType());
10406     IsRelational = CmpInfo.isOrdered();
10407     IsEquality = CmpInfo.isEquality();
10408   }
10409 
10410   QualType LHSTy = E->getLHS()->getType();
10411   QualType RHSTy = E->getRHS()->getType();
10412 
10413   if (LHSTy->isIntegralOrEnumerationType() &&
10414       RHSTy->isIntegralOrEnumerationType()) {
10415     APSInt LHS, RHS;
10416     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10417     if (!LHSOK && !Info.noteFailure())
10418       return false;
10419     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10420       return false;
10421     if (LHS < RHS)
10422       return Success(CCR::Less, E);
10423     if (LHS > RHS)
10424       return Success(CCR::Greater, E);
10425     return Success(CCR::Equal, E);
10426   }
10427 
10428   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10429     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10430     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10431 
10432     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10433     if (!LHSOK && !Info.noteFailure())
10434       return false;
10435     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10436       return false;
10437     if (LHSFX < RHSFX)
10438       return Success(CCR::Less, E);
10439     if (LHSFX > RHSFX)
10440       return Success(CCR::Greater, E);
10441     return Success(CCR::Equal, E);
10442   }
10443 
10444   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
10445     ComplexValue LHS, RHS;
10446     bool LHSOK;
10447     if (E->isAssignmentOp()) {
10448       LValue LV;
10449       EvaluateLValue(E->getLHS(), LV, Info);
10450       LHSOK = false;
10451     } else if (LHSTy->isRealFloatingType()) {
10452       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10453       if (LHSOK) {
10454         LHS.makeComplexFloat();
10455         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10456       }
10457     } else {
10458       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10459     }
10460     if (!LHSOK && !Info.noteFailure())
10461       return false;
10462 
10463     if (E->getRHS()->getType()->isRealFloatingType()) {
10464       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10465         return false;
10466       RHS.makeComplexFloat();
10467       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10468     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10469       return false;
10470 
10471     if (LHS.isComplexFloat()) {
10472       APFloat::cmpResult CR_r =
10473         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
10474       APFloat::cmpResult CR_i =
10475         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10476       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10477       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10478     } else {
10479       assert(IsEquality && "invalid complex comparison");
10480       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10481                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
10482       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10483     }
10484   }
10485 
10486   if (LHSTy->isRealFloatingType() &&
10487       RHSTy->isRealFloatingType()) {
10488     APFloat RHS(0.0), LHS(0.0);
10489 
10490     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10491     if (!LHSOK && !Info.noteFailure())
10492       return false;
10493 
10494     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10495       return false;
10496 
10497     assert(E->isComparisonOp() && "Invalid binary operator!");
10498     auto GetCmpRes = [&]() {
10499       switch (LHS.compare(RHS)) {
10500       case APFloat::cmpEqual:
10501         return CCR::Equal;
10502       case APFloat::cmpLessThan:
10503         return CCR::Less;
10504       case APFloat::cmpGreaterThan:
10505         return CCR::Greater;
10506       case APFloat::cmpUnordered:
10507         return CCR::Unordered;
10508       }
10509       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10510     };
10511     return Success(GetCmpRes(), E);
10512   }
10513 
10514   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10515     LValue LHSValue, RHSValue;
10516 
10517     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10518     if (!LHSOK && !Info.noteFailure())
10519       return false;
10520 
10521     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10522       return false;
10523 
10524     // Reject differing bases from the normal codepath; we special-case
10525     // comparisons to null.
10526     if (!HasSameBase(LHSValue, RHSValue)) {
10527       // Inequalities and subtractions between unrelated pointers have
10528       // unspecified or undefined behavior.
10529       if (!IsEquality)
10530         return Error(E);
10531       // A constant address may compare equal to the address of a symbol.
10532       // The one exception is that address of an object cannot compare equal
10533       // to a null pointer constant.
10534       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10535           (!RHSValue.Base && !RHSValue.Offset.isZero()))
10536         return Error(E);
10537       // It's implementation-defined whether distinct literals will have
10538       // distinct addresses. In clang, the result of such a comparison is
10539       // unspecified, so it is not a constant expression. However, we do know
10540       // that the address of a literal will be non-null.
10541       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10542           LHSValue.Base && RHSValue.Base)
10543         return Error(E);
10544       // We can't tell whether weak symbols will end up pointing to the same
10545       // object.
10546       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10547         return Error(E);
10548       // We can't compare the address of the start of one object with the
10549       // past-the-end address of another object, per C++ DR1652.
10550       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10551            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10552           (RHSValue.Base && RHSValue.Offset.isZero() &&
10553            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10554         return Error(E);
10555       // We can't tell whether an object is at the same address as another
10556       // zero sized object.
10557       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10558           (LHSValue.Base && isZeroSized(RHSValue)))
10559         return Error(E);
10560       return Success(CCR::Nonequal, E);
10561     }
10562 
10563     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10564     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10565 
10566     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10567     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10568 
10569     // C++11 [expr.rel]p3:
10570     //   Pointers to void (after pointer conversions) can be compared, with a
10571     //   result defined as follows: If both pointers represent the same
10572     //   address or are both the null pointer value, the result is true if the
10573     //   operator is <= or >= and false otherwise; otherwise the result is
10574     //   unspecified.
10575     // We interpret this as applying to pointers to *cv* void.
10576     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10577       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10578 
10579     // C++11 [expr.rel]p2:
10580     // - If two pointers point to non-static data members of the same object,
10581     //   or to subobjects or array elements fo such members, recursively, the
10582     //   pointer to the later declared member compares greater provided the
10583     //   two members have the same access control and provided their class is
10584     //   not a union.
10585     //   [...]
10586     // - Otherwise pointer comparisons are unspecified.
10587     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10588       bool WasArrayIndex;
10589       unsigned Mismatch = FindDesignatorMismatch(
10590           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10591       // At the point where the designators diverge, the comparison has a
10592       // specified value if:
10593       //  - we are comparing array indices
10594       //  - we are comparing fields of a union, or fields with the same access
10595       // Otherwise, the result is unspecified and thus the comparison is not a
10596       // constant expression.
10597       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10598           Mismatch < RHSDesignator.Entries.size()) {
10599         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10600         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10601         if (!LF && !RF)
10602           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10603         else if (!LF)
10604           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10605               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10606               << RF->getParent() << RF;
10607         else if (!RF)
10608           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10609               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10610               << LF->getParent() << LF;
10611         else if (!LF->getParent()->isUnion() &&
10612                  LF->getAccess() != RF->getAccess())
10613           Info.CCEDiag(E,
10614                        diag::note_constexpr_pointer_comparison_differing_access)
10615               << LF << LF->getAccess() << RF << RF->getAccess()
10616               << LF->getParent();
10617       }
10618     }
10619 
10620     // The comparison here must be unsigned, and performed with the same
10621     // width as the pointer.
10622     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10623     uint64_t CompareLHS = LHSOffset.getQuantity();
10624     uint64_t CompareRHS = RHSOffset.getQuantity();
10625     assert(PtrSize <= 64 && "Unexpected pointer width");
10626     uint64_t Mask = ~0ULL >> (64 - PtrSize);
10627     CompareLHS &= Mask;
10628     CompareRHS &= Mask;
10629 
10630     // If there is a base and this is a relational operator, we can only
10631     // compare pointers within the object in question; otherwise, the result
10632     // depends on where the object is located in memory.
10633     if (!LHSValue.Base.isNull() && IsRelational) {
10634       QualType BaseTy = getType(LHSValue.Base);
10635       if (BaseTy->isIncompleteType())
10636         return Error(E);
10637       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10638       uint64_t OffsetLimit = Size.getQuantity();
10639       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10640         return Error(E);
10641     }
10642 
10643     if (CompareLHS < CompareRHS)
10644       return Success(CCR::Less, E);
10645     if (CompareLHS > CompareRHS)
10646       return Success(CCR::Greater, E);
10647     return Success(CCR::Equal, E);
10648   }
10649 
10650   if (LHSTy->isMemberPointerType()) {
10651     assert(IsEquality && "unexpected member pointer operation");
10652     assert(RHSTy->isMemberPointerType() && "invalid comparison");
10653 
10654     MemberPtr LHSValue, RHSValue;
10655 
10656     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10657     if (!LHSOK && !Info.noteFailure())
10658       return false;
10659 
10660     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10661       return false;
10662 
10663     // C++11 [expr.eq]p2:
10664     //   If both operands are null, they compare equal. Otherwise if only one is
10665     //   null, they compare unequal.
10666     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10667       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10668       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10669     }
10670 
10671     //   Otherwise if either is a pointer to a virtual member function, the
10672     //   result is unspecified.
10673     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10674       if (MD->isVirtual())
10675         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10676     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10677       if (MD->isVirtual())
10678         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10679 
10680     //   Otherwise they compare equal if and only if they would refer to the
10681     //   same member of the same most derived object or the same subobject if
10682     //   they were dereferenced with a hypothetical object of the associated
10683     //   class type.
10684     bool Equal = LHSValue == RHSValue;
10685     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10686   }
10687 
10688   if (LHSTy->isNullPtrType()) {
10689     assert(E->isComparisonOp() && "unexpected nullptr operation");
10690     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10691     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10692     // are compared, the result is true of the operator is <=, >= or ==, and
10693     // false otherwise.
10694     return Success(CCR::Equal, E);
10695   }
10696 
10697   return DoAfter();
10698 }
10699 
10700 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10701   if (!CheckLiteralType(Info, E))
10702     return false;
10703 
10704   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10705                        const BinaryOperator *E) {
10706     // Evaluation succeeded. Lookup the information for the comparison category
10707     // type and fetch the VarDecl for the result.
10708     const ComparisonCategoryInfo &CmpInfo =
10709         Info.Ctx.CompCategories.getInfoForType(E->getType());
10710     const VarDecl *VD =
10711         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10712     // Check and evaluate the result as a constant expression.
10713     LValue LV;
10714     LV.set(VD);
10715     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10716       return false;
10717     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10718   };
10719   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10720     return ExprEvaluatorBaseTy::VisitBinCmp(E);
10721   });
10722 }
10723 
10724 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10725   // We don't call noteFailure immediately because the assignment happens after
10726   // we evaluate LHS and RHS.
10727   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10728     return Error(E);
10729 
10730   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10731   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10732     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10733 
10734   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10735           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10736          "DataRecursiveIntBinOpEvaluator should have handled integral types");
10737 
10738   if (E->isComparisonOp()) {
10739     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10740     // comparisons and then translating the result.
10741     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10742                          const BinaryOperator *E) {
10743       using CCR = ComparisonCategoryResult;
10744       bool IsEqual   = ResKind == CCR::Equal,
10745            IsLess    = ResKind == CCR::Less,
10746            IsGreater = ResKind == CCR::Greater;
10747       auto Op = E->getOpcode();
10748       switch (Op) {
10749       default:
10750         llvm_unreachable("unsupported binary operator");
10751       case BO_EQ:
10752       case BO_NE:
10753         return Success(IsEqual == (Op == BO_EQ), E);
10754       case BO_LT: return Success(IsLess, E);
10755       case BO_GT: return Success(IsGreater, E);
10756       case BO_LE: return Success(IsEqual || IsLess, E);
10757       case BO_GE: return Success(IsEqual || IsGreater, E);
10758       }
10759     };
10760     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10761       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10762     });
10763   }
10764 
10765   QualType LHSTy = E->getLHS()->getType();
10766   QualType RHSTy = E->getRHS()->getType();
10767 
10768   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10769       E->getOpcode() == BO_Sub) {
10770     LValue LHSValue, RHSValue;
10771 
10772     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10773     if (!LHSOK && !Info.noteFailure())
10774       return false;
10775 
10776     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10777       return false;
10778 
10779     // Reject differing bases from the normal codepath; we special-case
10780     // comparisons to null.
10781     if (!HasSameBase(LHSValue, RHSValue)) {
10782       // Handle &&A - &&B.
10783       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10784         return Error(E);
10785       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10786       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10787       if (!LHSExpr || !RHSExpr)
10788         return Error(E);
10789       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10790       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10791       if (!LHSAddrExpr || !RHSAddrExpr)
10792         return Error(E);
10793       // Make sure both labels come from the same function.
10794       if (LHSAddrExpr->getLabel()->getDeclContext() !=
10795           RHSAddrExpr->getLabel()->getDeclContext())
10796         return Error(E);
10797       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10798     }
10799     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10800     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10801 
10802     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10803     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10804 
10805     // C++11 [expr.add]p6:
10806     //   Unless both pointers point to elements of the same array object, or
10807     //   one past the last element of the array object, the behavior is
10808     //   undefined.
10809     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10810         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10811                                 RHSDesignator))
10812       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10813 
10814     QualType Type = E->getLHS()->getType();
10815     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10816 
10817     CharUnits ElementSize;
10818     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10819       return false;
10820 
10821     // As an extension, a type may have zero size (empty struct or union in
10822     // C, array of zero length). Pointer subtraction in such cases has
10823     // undefined behavior, so is not constant.
10824     if (ElementSize.isZero()) {
10825       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10826           << ElementType;
10827       return false;
10828     }
10829 
10830     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10831     // and produce incorrect results when it overflows. Such behavior
10832     // appears to be non-conforming, but is common, so perhaps we should
10833     // assume the standard intended for such cases to be undefined behavior
10834     // and check for them.
10835 
10836     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10837     // overflow in the final conversion to ptrdiff_t.
10838     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10839     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10840     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10841                     false);
10842     APSInt TrueResult = (LHS - RHS) / ElemSize;
10843     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10844 
10845     if (Result.extend(65) != TrueResult &&
10846         !HandleOverflow(Info, E, TrueResult, E->getType()))
10847       return false;
10848     return Success(Result, E);
10849   }
10850 
10851   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10852 }
10853 
10854 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10855 /// a result as the expression's type.
10856 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10857                                     const UnaryExprOrTypeTraitExpr *E) {
10858   switch(E->getKind()) {
10859   case UETT_PreferredAlignOf:
10860   case UETT_AlignOf: {
10861     if (E->isArgumentType())
10862       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10863                      E);
10864     else
10865       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10866                      E);
10867   }
10868 
10869   case UETT_VecStep: {
10870     QualType Ty = E->getTypeOfArgument();
10871 
10872     if (Ty->isVectorType()) {
10873       unsigned n = Ty->castAs<VectorType>()->getNumElements();
10874 
10875       // The vec_step built-in functions that take a 3-component
10876       // vector return 4. (OpenCL 1.1 spec 6.11.12)
10877       if (n == 3)
10878         n = 4;
10879 
10880       return Success(n, E);
10881     } else
10882       return Success(1, E);
10883   }
10884 
10885   case UETT_SizeOf: {
10886     QualType SrcTy = E->getTypeOfArgument();
10887     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10888     //   the result is the size of the referenced type."
10889     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10890       SrcTy = Ref->getPointeeType();
10891 
10892     CharUnits Sizeof;
10893     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10894       return false;
10895     return Success(Sizeof, E);
10896   }
10897   case UETT_OpenMPRequiredSimdAlign:
10898     assert(E->isArgumentType());
10899     return Success(
10900         Info.Ctx.toCharUnitsFromBits(
10901                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10902             .getQuantity(),
10903         E);
10904   }
10905 
10906   llvm_unreachable("unknown expr/type trait");
10907 }
10908 
10909 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10910   CharUnits Result;
10911   unsigned n = OOE->getNumComponents();
10912   if (n == 0)
10913     return Error(OOE);
10914   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10915   for (unsigned i = 0; i != n; ++i) {
10916     OffsetOfNode ON = OOE->getComponent(i);
10917     switch (ON.getKind()) {
10918     case OffsetOfNode::Array: {
10919       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10920       APSInt IdxResult;
10921       if (!EvaluateInteger(Idx, IdxResult, Info))
10922         return false;
10923       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10924       if (!AT)
10925         return Error(OOE);
10926       CurrentType = AT->getElementType();
10927       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10928       Result += IdxResult.getSExtValue() * ElementSize;
10929       break;
10930     }
10931 
10932     case OffsetOfNode::Field: {
10933       FieldDecl *MemberDecl = ON.getField();
10934       const RecordType *RT = CurrentType->getAs<RecordType>();
10935       if (!RT)
10936         return Error(OOE);
10937       RecordDecl *RD = RT->getDecl();
10938       if (RD->isInvalidDecl()) return false;
10939       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10940       unsigned i = MemberDecl->getFieldIndex();
10941       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10942       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10943       CurrentType = MemberDecl->getType().getNonReferenceType();
10944       break;
10945     }
10946 
10947     case OffsetOfNode::Identifier:
10948       llvm_unreachable("dependent __builtin_offsetof");
10949 
10950     case OffsetOfNode::Base: {
10951       CXXBaseSpecifier *BaseSpec = ON.getBase();
10952       if (BaseSpec->isVirtual())
10953         return Error(OOE);
10954 
10955       // Find the layout of the class whose base we are looking into.
10956       const RecordType *RT = CurrentType->getAs<RecordType>();
10957       if (!RT)
10958         return Error(OOE);
10959       RecordDecl *RD = RT->getDecl();
10960       if (RD->isInvalidDecl()) return false;
10961       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10962 
10963       // Find the base class itself.
10964       CurrentType = BaseSpec->getType();
10965       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10966       if (!BaseRT)
10967         return Error(OOE);
10968 
10969       // Add the offset to the base.
10970       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10971       break;
10972     }
10973     }
10974   }
10975   return Success(Result, OOE);
10976 }
10977 
10978 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10979   switch (E->getOpcode()) {
10980   default:
10981     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10982     // See C99 6.6p3.
10983     return Error(E);
10984   case UO_Extension:
10985     // FIXME: Should extension allow i-c-e extension expressions in its scope?
10986     // If so, we could clear the diagnostic ID.
10987     return Visit(E->getSubExpr());
10988   case UO_Plus:
10989     // The result is just the value.
10990     return Visit(E->getSubExpr());
10991   case UO_Minus: {
10992     if (!Visit(E->getSubExpr()))
10993       return false;
10994     if (!Result.isInt()) return Error(E);
10995     const APSInt &Value = Result.getInt();
10996     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
10997         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
10998                         E->getType()))
10999       return false;
11000     return Success(-Value, E);
11001   }
11002   case UO_Not: {
11003     if (!Visit(E->getSubExpr()))
11004       return false;
11005     if (!Result.isInt()) return Error(E);
11006     return Success(~Result.getInt(), E);
11007   }
11008   case UO_LNot: {
11009     bool bres;
11010     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11011       return false;
11012     return Success(!bres, E);
11013   }
11014   }
11015 }
11016 
11017 /// HandleCast - This is used to evaluate implicit or explicit casts where the
11018 /// result type is integer.
11019 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11020   const Expr *SubExpr = E->getSubExpr();
11021   QualType DestType = E->getType();
11022   QualType SrcType = SubExpr->getType();
11023 
11024   switch (E->getCastKind()) {
11025   case CK_BaseToDerived:
11026   case CK_DerivedToBase:
11027   case CK_UncheckedDerivedToBase:
11028   case CK_Dynamic:
11029   case CK_ToUnion:
11030   case CK_ArrayToPointerDecay:
11031   case CK_FunctionToPointerDecay:
11032   case CK_NullToPointer:
11033   case CK_NullToMemberPointer:
11034   case CK_BaseToDerivedMemberPointer:
11035   case CK_DerivedToBaseMemberPointer:
11036   case CK_ReinterpretMemberPointer:
11037   case CK_ConstructorConversion:
11038   case CK_IntegralToPointer:
11039   case CK_ToVoid:
11040   case CK_VectorSplat:
11041   case CK_IntegralToFloating:
11042   case CK_FloatingCast:
11043   case CK_CPointerToObjCPointerCast:
11044   case CK_BlockPointerToObjCPointerCast:
11045   case CK_AnyPointerToBlockPointerCast:
11046   case CK_ObjCObjectLValueCast:
11047   case CK_FloatingRealToComplex:
11048   case CK_FloatingComplexToReal:
11049   case CK_FloatingComplexCast:
11050   case CK_FloatingComplexToIntegralComplex:
11051   case CK_IntegralRealToComplex:
11052   case CK_IntegralComplexCast:
11053   case CK_IntegralComplexToFloatingComplex:
11054   case CK_BuiltinFnToFnPtr:
11055   case CK_ZeroToOCLOpaqueType:
11056   case CK_NonAtomicToAtomic:
11057   case CK_AddressSpaceConversion:
11058   case CK_IntToOCLSampler:
11059   case CK_FixedPointCast:
11060   case CK_IntegralToFixedPoint:
11061     llvm_unreachable("invalid cast kind for integral value");
11062 
11063   case CK_BitCast:
11064   case CK_Dependent:
11065   case CK_LValueBitCast:
11066   case CK_ARCProduceObject:
11067   case CK_ARCConsumeObject:
11068   case CK_ARCReclaimReturnedObject:
11069   case CK_ARCExtendBlockObject:
11070   case CK_CopyAndAutoreleaseBlockObject:
11071     return Error(E);
11072 
11073   case CK_UserDefinedConversion:
11074   case CK_LValueToRValue:
11075   case CK_AtomicToNonAtomic:
11076   case CK_NoOp:
11077   case CK_LValueToRValueBitCast:
11078     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11079 
11080   case CK_MemberPointerToBoolean:
11081   case CK_PointerToBoolean:
11082   case CK_IntegralToBoolean:
11083   case CK_FloatingToBoolean:
11084   case CK_BooleanToSignedIntegral:
11085   case CK_FloatingComplexToBoolean:
11086   case CK_IntegralComplexToBoolean: {
11087     bool BoolResult;
11088     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
11089       return false;
11090     uint64_t IntResult = BoolResult;
11091     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11092       IntResult = (uint64_t)-1;
11093     return Success(IntResult, E);
11094   }
11095 
11096   case CK_FixedPointToIntegral: {
11097     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11098     if (!EvaluateFixedPoint(SubExpr, Src, Info))
11099       return false;
11100     bool Overflowed;
11101     llvm::APSInt Result = Src.convertToInt(
11102         Info.Ctx.getIntWidth(DestType),
11103         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11104     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11105       return false;
11106     return Success(Result, E);
11107   }
11108 
11109   case CK_FixedPointToBoolean: {
11110     // Unsigned padding does not affect this.
11111     APValue Val;
11112     if (!Evaluate(Val, Info, SubExpr))
11113       return false;
11114     return Success(Val.getFixedPoint().getBoolValue(), E);
11115   }
11116 
11117   case CK_IntegralCast: {
11118     if (!Visit(SubExpr))
11119       return false;
11120 
11121     if (!Result.isInt()) {
11122       // Allow casts of address-of-label differences if they are no-ops
11123       // or narrowing.  (The narrowing case isn't actually guaranteed to
11124       // be constant-evaluatable except in some narrow cases which are hard
11125       // to detect here.  We let it through on the assumption the user knows
11126       // what they are doing.)
11127       if (Result.isAddrLabelDiff())
11128         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
11129       // Only allow casts of lvalues if they are lossless.
11130       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11131     }
11132 
11133     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11134                                       Result.getInt()), E);
11135   }
11136 
11137   case CK_PointerToIntegral: {
11138     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11139 
11140     LValue LV;
11141     if (!EvaluatePointer(SubExpr, LV, Info))
11142       return false;
11143 
11144     if (LV.getLValueBase()) {
11145       // Only allow based lvalue casts if they are lossless.
11146       // FIXME: Allow a larger integer size than the pointer size, and allow
11147       // narrowing back down to pointer width in subsequent integral casts.
11148       // FIXME: Check integer type's active bits, not its type size.
11149       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
11150         return Error(E);
11151 
11152       LV.Designator.setInvalid();
11153       LV.moveInto(Result);
11154       return true;
11155     }
11156 
11157     APSInt AsInt;
11158     APValue V;
11159     LV.moveInto(V);
11160     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11161       llvm_unreachable("Can't cast this!");
11162 
11163     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
11164   }
11165 
11166   case CK_IntegralComplexToReal: {
11167     ComplexValue C;
11168     if (!EvaluateComplex(SubExpr, C, Info))
11169       return false;
11170     return Success(C.getComplexIntReal(), E);
11171   }
11172 
11173   case CK_FloatingToIntegral: {
11174     APFloat F(0.0);
11175     if (!EvaluateFloat(SubExpr, F, Info))
11176       return false;
11177 
11178     APSInt Value;
11179     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11180       return false;
11181     return Success(Value, E);
11182   }
11183   }
11184 
11185   llvm_unreachable("unknown cast resulting in integral value");
11186 }
11187 
11188 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11189   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11190     ComplexValue LV;
11191     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11192       return false;
11193     if (!LV.isComplexInt())
11194       return Error(E);
11195     return Success(LV.getComplexIntReal(), E);
11196   }
11197 
11198   return Visit(E->getSubExpr());
11199 }
11200 
11201 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11202   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
11203     ComplexValue LV;
11204     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11205       return false;
11206     if (!LV.isComplexInt())
11207       return Error(E);
11208     return Success(LV.getComplexIntImag(), E);
11209   }
11210 
11211   VisitIgnoredValue(E->getSubExpr());
11212   return Success(0, E);
11213 }
11214 
11215 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11216   return Success(E->getPackLength(), E);
11217 }
11218 
11219 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11220   return Success(E->getValue(), E);
11221 }
11222 
11223 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11224   switch (E->getOpcode()) {
11225     default:
11226       // Invalid unary operators
11227       return Error(E);
11228     case UO_Plus:
11229       // The result is just the value.
11230       return Visit(E->getSubExpr());
11231     case UO_Minus: {
11232       if (!Visit(E->getSubExpr())) return false;
11233       if (!Result.isFixedPoint())
11234         return Error(E);
11235       bool Overflowed;
11236       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11237       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11238         return false;
11239       return Success(Negated, E);
11240     }
11241     case UO_LNot: {
11242       bool bres;
11243       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11244         return false;
11245       return Success(!bres, E);
11246     }
11247   }
11248 }
11249 
11250 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11251   const Expr *SubExpr = E->getSubExpr();
11252   QualType DestType = E->getType();
11253   assert(DestType->isFixedPointType() &&
11254          "Expected destination type to be a fixed point type");
11255   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11256 
11257   switch (E->getCastKind()) {
11258   case CK_FixedPointCast: {
11259     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11260     if (!EvaluateFixedPoint(SubExpr, Src, Info))
11261       return false;
11262     bool Overflowed;
11263     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11264     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11265       return false;
11266     return Success(Result, E);
11267   }
11268   case CK_IntegralToFixedPoint: {
11269     APSInt Src;
11270     if (!EvaluateInteger(SubExpr, Src, Info))
11271       return false;
11272 
11273     bool Overflowed;
11274     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11275         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11276 
11277     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11278       return false;
11279 
11280     return Success(IntResult, E);
11281   }
11282   case CK_NoOp:
11283   case CK_LValueToRValue:
11284     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11285   default:
11286     return Error(E);
11287   }
11288 }
11289 
11290 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11291   const Expr *LHS = E->getLHS();
11292   const Expr *RHS = E->getRHS();
11293   FixedPointSemantics ResultFXSema =
11294       Info.Ctx.getFixedPointSemantics(E->getType());
11295 
11296   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11297   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11298     return false;
11299   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11300   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11301     return false;
11302 
11303   switch (E->getOpcode()) {
11304   case BO_Add: {
11305     bool AddOverflow, ConversionOverflow;
11306     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11307                               .convert(ResultFXSema, &ConversionOverflow);
11308     if ((AddOverflow || ConversionOverflow) &&
11309         !HandleOverflow(Info, E, Result, E->getType()))
11310       return false;
11311     return Success(Result, E);
11312   }
11313   default:
11314     return false;
11315   }
11316   llvm_unreachable("Should've exited before this");
11317 }
11318 
11319 //===----------------------------------------------------------------------===//
11320 // Float Evaluation
11321 //===----------------------------------------------------------------------===//
11322 
11323 namespace {
11324 class FloatExprEvaluator
11325   : public ExprEvaluatorBase<FloatExprEvaluator> {
11326   APFloat &Result;
11327 public:
11328   FloatExprEvaluator(EvalInfo &info, APFloat &result)
11329     : ExprEvaluatorBaseTy(info), Result(result) {}
11330 
11331   bool Success(const APValue &V, const Expr *e) {
11332     Result = V.getFloat();
11333     return true;
11334   }
11335 
11336   bool ZeroInitialization(const Expr *E) {
11337     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11338     return true;
11339   }
11340 
11341   bool VisitCallExpr(const CallExpr *E);
11342 
11343   bool VisitUnaryOperator(const UnaryOperator *E);
11344   bool VisitBinaryOperator(const BinaryOperator *E);
11345   bool VisitFloatingLiteral(const FloatingLiteral *E);
11346   bool VisitCastExpr(const CastExpr *E);
11347 
11348   bool VisitUnaryReal(const UnaryOperator *E);
11349   bool VisitUnaryImag(const UnaryOperator *E);
11350 
11351   // FIXME: Missing: array subscript of vector, member of vector
11352 };
11353 } // end anonymous namespace
11354 
11355 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
11356   assert(E->isRValue() && E->getType()->isRealFloatingType());
11357   return FloatExprEvaluator(Info, Result).Visit(E);
11358 }
11359 
11360 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
11361                                   QualType ResultTy,
11362                                   const Expr *Arg,
11363                                   bool SNaN,
11364                                   llvm::APFloat &Result) {
11365   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11366   if (!S) return false;
11367 
11368   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11369 
11370   llvm::APInt fill;
11371 
11372   // Treat empty strings as if they were zero.
11373   if (S->getString().empty())
11374     fill = llvm::APInt(32, 0);
11375   else if (S->getString().getAsInteger(0, fill))
11376     return false;
11377 
11378   if (Context.getTargetInfo().isNan2008()) {
11379     if (SNaN)
11380       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11381     else
11382       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11383   } else {
11384     // Prior to IEEE 754-2008, architectures were allowed to choose whether
11385     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11386     // a different encoding to what became a standard in 2008, and for pre-
11387     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11388     // sNaN. This is now known as "legacy NaN" encoding.
11389     if (SNaN)
11390       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11391     else
11392       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11393   }
11394 
11395   return true;
11396 }
11397 
11398 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
11399   switch (E->getBuiltinCallee()) {
11400   default:
11401     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11402 
11403   case Builtin::BI__builtin_huge_val:
11404   case Builtin::BI__builtin_huge_valf:
11405   case Builtin::BI__builtin_huge_vall:
11406   case Builtin::BI__builtin_huge_valf128:
11407   case Builtin::BI__builtin_inf:
11408   case Builtin::BI__builtin_inff:
11409   case Builtin::BI__builtin_infl:
11410   case Builtin::BI__builtin_inff128: {
11411     const llvm::fltSemantics &Sem =
11412       Info.Ctx.getFloatTypeSemantics(E->getType());
11413     Result = llvm::APFloat::getInf(Sem);
11414     return true;
11415   }
11416 
11417   case Builtin::BI__builtin_nans:
11418   case Builtin::BI__builtin_nansf:
11419   case Builtin::BI__builtin_nansl:
11420   case Builtin::BI__builtin_nansf128:
11421     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11422                                true, Result))
11423       return Error(E);
11424     return true;
11425 
11426   case Builtin::BI__builtin_nan:
11427   case Builtin::BI__builtin_nanf:
11428   case Builtin::BI__builtin_nanl:
11429   case Builtin::BI__builtin_nanf128:
11430     // If this is __builtin_nan() turn this into a nan, otherwise we
11431     // can't constant fold it.
11432     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11433                                false, Result))
11434       return Error(E);
11435     return true;
11436 
11437   case Builtin::BI__builtin_fabs:
11438   case Builtin::BI__builtin_fabsf:
11439   case Builtin::BI__builtin_fabsl:
11440   case Builtin::BI__builtin_fabsf128:
11441     if (!EvaluateFloat(E->getArg(0), Result, Info))
11442       return false;
11443 
11444     if (Result.isNegative())
11445       Result.changeSign();
11446     return true;
11447 
11448   // FIXME: Builtin::BI__builtin_powi
11449   // FIXME: Builtin::BI__builtin_powif
11450   // FIXME: Builtin::BI__builtin_powil
11451 
11452   case Builtin::BI__builtin_copysign:
11453   case Builtin::BI__builtin_copysignf:
11454   case Builtin::BI__builtin_copysignl:
11455   case Builtin::BI__builtin_copysignf128: {
11456     APFloat RHS(0.);
11457     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11458         !EvaluateFloat(E->getArg(1), RHS, Info))
11459       return false;
11460     Result.copySign(RHS);
11461     return true;
11462   }
11463   }
11464 }
11465 
11466 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11467   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11468     ComplexValue CV;
11469     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11470       return false;
11471     Result = CV.FloatReal;
11472     return true;
11473   }
11474 
11475   return Visit(E->getSubExpr());
11476 }
11477 
11478 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11479   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11480     ComplexValue CV;
11481     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11482       return false;
11483     Result = CV.FloatImag;
11484     return true;
11485   }
11486 
11487   VisitIgnoredValue(E->getSubExpr());
11488   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11489   Result = llvm::APFloat::getZero(Sem);
11490   return true;
11491 }
11492 
11493 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11494   switch (E->getOpcode()) {
11495   default: return Error(E);
11496   case UO_Plus:
11497     return EvaluateFloat(E->getSubExpr(), Result, Info);
11498   case UO_Minus:
11499     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11500       return false;
11501     Result.changeSign();
11502     return true;
11503   }
11504 }
11505 
11506 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11507   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11508     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11509 
11510   APFloat RHS(0.0);
11511   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11512   if (!LHSOK && !Info.noteFailure())
11513     return false;
11514   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11515          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11516 }
11517 
11518 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11519   Result = E->getValue();
11520   return true;
11521 }
11522 
11523 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11524   const Expr* SubExpr = E->getSubExpr();
11525 
11526   switch (E->getCastKind()) {
11527   default:
11528     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11529 
11530   case CK_IntegralToFloating: {
11531     APSInt IntResult;
11532     return EvaluateInteger(SubExpr, IntResult, Info) &&
11533            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11534                                 E->getType(), Result);
11535   }
11536 
11537   case CK_FloatingCast: {
11538     if (!Visit(SubExpr))
11539       return false;
11540     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11541                                   Result);
11542   }
11543 
11544   case CK_FloatingComplexToReal: {
11545     ComplexValue V;
11546     if (!EvaluateComplex(SubExpr, V, Info))
11547       return false;
11548     Result = V.getComplexFloatReal();
11549     return true;
11550   }
11551   }
11552 }
11553 
11554 //===----------------------------------------------------------------------===//
11555 // Complex Evaluation (for float and integer)
11556 //===----------------------------------------------------------------------===//
11557 
11558 namespace {
11559 class ComplexExprEvaluator
11560   : public ExprEvaluatorBase<ComplexExprEvaluator> {
11561   ComplexValue &Result;
11562 
11563 public:
11564   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11565     : ExprEvaluatorBaseTy(info), Result(Result) {}
11566 
11567   bool Success(const APValue &V, const Expr *e) {
11568     Result.setFrom(V);
11569     return true;
11570   }
11571 
11572   bool ZeroInitialization(const Expr *E);
11573 
11574   //===--------------------------------------------------------------------===//
11575   //                            Visitor Methods
11576   //===--------------------------------------------------------------------===//
11577 
11578   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11579   bool VisitCastExpr(const CastExpr *E);
11580   bool VisitBinaryOperator(const BinaryOperator *E);
11581   bool VisitUnaryOperator(const UnaryOperator *E);
11582   bool VisitInitListExpr(const InitListExpr *E);
11583 };
11584 } // end anonymous namespace
11585 
11586 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11587                             EvalInfo &Info) {
11588   assert(E->isRValue() && E->getType()->isAnyComplexType());
11589   return ComplexExprEvaluator(Info, Result).Visit(E);
11590 }
11591 
11592 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11593   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11594   if (ElemTy->isRealFloatingType()) {
11595     Result.makeComplexFloat();
11596     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11597     Result.FloatReal = Zero;
11598     Result.FloatImag = Zero;
11599   } else {
11600     Result.makeComplexInt();
11601     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11602     Result.IntReal = Zero;
11603     Result.IntImag = Zero;
11604   }
11605   return true;
11606 }
11607 
11608 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11609   const Expr* SubExpr = E->getSubExpr();
11610 
11611   if (SubExpr->getType()->isRealFloatingType()) {
11612     Result.makeComplexFloat();
11613     APFloat &Imag = Result.FloatImag;
11614     if (!EvaluateFloat(SubExpr, Imag, Info))
11615       return false;
11616 
11617     Result.FloatReal = APFloat(Imag.getSemantics());
11618     return true;
11619   } else {
11620     assert(SubExpr->getType()->isIntegerType() &&
11621            "Unexpected imaginary literal.");
11622 
11623     Result.makeComplexInt();
11624     APSInt &Imag = Result.IntImag;
11625     if (!EvaluateInteger(SubExpr, Imag, Info))
11626       return false;
11627 
11628     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11629     return true;
11630   }
11631 }
11632 
11633 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11634 
11635   switch (E->getCastKind()) {
11636   case CK_BitCast:
11637   case CK_BaseToDerived:
11638   case CK_DerivedToBase:
11639   case CK_UncheckedDerivedToBase:
11640   case CK_Dynamic:
11641   case CK_ToUnion:
11642   case CK_ArrayToPointerDecay:
11643   case CK_FunctionToPointerDecay:
11644   case CK_NullToPointer:
11645   case CK_NullToMemberPointer:
11646   case CK_BaseToDerivedMemberPointer:
11647   case CK_DerivedToBaseMemberPointer:
11648   case CK_MemberPointerToBoolean:
11649   case CK_ReinterpretMemberPointer:
11650   case CK_ConstructorConversion:
11651   case CK_IntegralToPointer:
11652   case CK_PointerToIntegral:
11653   case CK_PointerToBoolean:
11654   case CK_ToVoid:
11655   case CK_VectorSplat:
11656   case CK_IntegralCast:
11657   case CK_BooleanToSignedIntegral:
11658   case CK_IntegralToBoolean:
11659   case CK_IntegralToFloating:
11660   case CK_FloatingToIntegral:
11661   case CK_FloatingToBoolean:
11662   case CK_FloatingCast:
11663   case CK_CPointerToObjCPointerCast:
11664   case CK_BlockPointerToObjCPointerCast:
11665   case CK_AnyPointerToBlockPointerCast:
11666   case CK_ObjCObjectLValueCast:
11667   case CK_FloatingComplexToReal:
11668   case CK_FloatingComplexToBoolean:
11669   case CK_IntegralComplexToReal:
11670   case CK_IntegralComplexToBoolean:
11671   case CK_ARCProduceObject:
11672   case CK_ARCConsumeObject:
11673   case CK_ARCReclaimReturnedObject:
11674   case CK_ARCExtendBlockObject:
11675   case CK_CopyAndAutoreleaseBlockObject:
11676   case CK_BuiltinFnToFnPtr:
11677   case CK_ZeroToOCLOpaqueType:
11678   case CK_NonAtomicToAtomic:
11679   case CK_AddressSpaceConversion:
11680   case CK_IntToOCLSampler:
11681   case CK_FixedPointCast:
11682   case CK_FixedPointToBoolean:
11683   case CK_FixedPointToIntegral:
11684   case CK_IntegralToFixedPoint:
11685     llvm_unreachable("invalid cast kind for complex value");
11686 
11687   case CK_LValueToRValue:
11688   case CK_AtomicToNonAtomic:
11689   case CK_NoOp:
11690   case CK_LValueToRValueBitCast:
11691     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11692 
11693   case CK_Dependent:
11694   case CK_LValueBitCast:
11695   case CK_UserDefinedConversion:
11696     return Error(E);
11697 
11698   case CK_FloatingRealToComplex: {
11699     APFloat &Real = Result.FloatReal;
11700     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11701       return false;
11702 
11703     Result.makeComplexFloat();
11704     Result.FloatImag = APFloat(Real.getSemantics());
11705     return true;
11706   }
11707 
11708   case CK_FloatingComplexCast: {
11709     if (!Visit(E->getSubExpr()))
11710       return false;
11711 
11712     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11713     QualType From
11714       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11715 
11716     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11717            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11718   }
11719 
11720   case CK_FloatingComplexToIntegralComplex: {
11721     if (!Visit(E->getSubExpr()))
11722       return false;
11723 
11724     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11725     QualType From
11726       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11727     Result.makeComplexInt();
11728     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11729                                 To, Result.IntReal) &&
11730            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11731                                 To, Result.IntImag);
11732   }
11733 
11734   case CK_IntegralRealToComplex: {
11735     APSInt &Real = Result.IntReal;
11736     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11737       return false;
11738 
11739     Result.makeComplexInt();
11740     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11741     return true;
11742   }
11743 
11744   case CK_IntegralComplexCast: {
11745     if (!Visit(E->getSubExpr()))
11746       return false;
11747 
11748     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11749     QualType From
11750       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11751 
11752     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11753     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11754     return true;
11755   }
11756 
11757   case CK_IntegralComplexToFloatingComplex: {
11758     if (!Visit(E->getSubExpr()))
11759       return false;
11760 
11761     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11762     QualType From
11763       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11764     Result.makeComplexFloat();
11765     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11766                                 To, Result.FloatReal) &&
11767            HandleIntToFloatCast(Info, E, From, Result.IntImag,
11768                                 To, Result.FloatImag);
11769   }
11770   }
11771 
11772   llvm_unreachable("unknown cast resulting in complex value");
11773 }
11774 
11775 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11776   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11777     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11778 
11779   // Track whether the LHS or RHS is real at the type system level. When this is
11780   // the case we can simplify our evaluation strategy.
11781   bool LHSReal = false, RHSReal = false;
11782 
11783   bool LHSOK;
11784   if (E->getLHS()->getType()->isRealFloatingType()) {
11785     LHSReal = true;
11786     APFloat &Real = Result.FloatReal;
11787     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11788     if (LHSOK) {
11789       Result.makeComplexFloat();
11790       Result.FloatImag = APFloat(Real.getSemantics());
11791     }
11792   } else {
11793     LHSOK = Visit(E->getLHS());
11794   }
11795   if (!LHSOK && !Info.noteFailure())
11796     return false;
11797 
11798   ComplexValue RHS;
11799   if (E->getRHS()->getType()->isRealFloatingType()) {
11800     RHSReal = true;
11801     APFloat &Real = RHS.FloatReal;
11802     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11803       return false;
11804     RHS.makeComplexFloat();
11805     RHS.FloatImag = APFloat(Real.getSemantics());
11806   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11807     return false;
11808 
11809   assert(!(LHSReal && RHSReal) &&
11810          "Cannot have both operands of a complex operation be real.");
11811   switch (E->getOpcode()) {
11812   default: return Error(E);
11813   case BO_Add:
11814     if (Result.isComplexFloat()) {
11815       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11816                                        APFloat::rmNearestTiesToEven);
11817       if (LHSReal)
11818         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11819       else if (!RHSReal)
11820         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11821                                          APFloat::rmNearestTiesToEven);
11822     } else {
11823       Result.getComplexIntReal() += RHS.getComplexIntReal();
11824       Result.getComplexIntImag() += RHS.getComplexIntImag();
11825     }
11826     break;
11827   case BO_Sub:
11828     if (Result.isComplexFloat()) {
11829       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11830                                             APFloat::rmNearestTiesToEven);
11831       if (LHSReal) {
11832         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11833         Result.getComplexFloatImag().changeSign();
11834       } else if (!RHSReal) {
11835         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11836                                               APFloat::rmNearestTiesToEven);
11837       }
11838     } else {
11839       Result.getComplexIntReal() -= RHS.getComplexIntReal();
11840       Result.getComplexIntImag() -= RHS.getComplexIntImag();
11841     }
11842     break;
11843   case BO_Mul:
11844     if (Result.isComplexFloat()) {
11845       // This is an implementation of complex multiplication according to the
11846       // constraints laid out in C11 Annex G. The implementation uses the
11847       // following naming scheme:
11848       //   (a + ib) * (c + id)
11849       ComplexValue LHS = Result;
11850       APFloat &A = LHS.getComplexFloatReal();
11851       APFloat &B = LHS.getComplexFloatImag();
11852       APFloat &C = RHS.getComplexFloatReal();
11853       APFloat &D = RHS.getComplexFloatImag();
11854       APFloat &ResR = Result.getComplexFloatReal();
11855       APFloat &ResI = Result.getComplexFloatImag();
11856       if (LHSReal) {
11857         assert(!RHSReal && "Cannot have two real operands for a complex op!");
11858         ResR = A * C;
11859         ResI = A * D;
11860       } else if (RHSReal) {
11861         ResR = C * A;
11862         ResI = C * B;
11863       } else {
11864         // In the fully general case, we need to handle NaNs and infinities
11865         // robustly.
11866         APFloat AC = A * C;
11867         APFloat BD = B * D;
11868         APFloat AD = A * D;
11869         APFloat BC = B * C;
11870         ResR = AC - BD;
11871         ResI = AD + BC;
11872         if (ResR.isNaN() && ResI.isNaN()) {
11873           bool Recalc = false;
11874           if (A.isInfinity() || B.isInfinity()) {
11875             A = APFloat::copySign(
11876                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11877             B = APFloat::copySign(
11878                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11879             if (C.isNaN())
11880               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11881             if (D.isNaN())
11882               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11883             Recalc = true;
11884           }
11885           if (C.isInfinity() || D.isInfinity()) {
11886             C = APFloat::copySign(
11887                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11888             D = APFloat::copySign(
11889                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11890             if (A.isNaN())
11891               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11892             if (B.isNaN())
11893               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11894             Recalc = true;
11895           }
11896           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11897                           AD.isInfinity() || BC.isInfinity())) {
11898             if (A.isNaN())
11899               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11900             if (B.isNaN())
11901               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11902             if (C.isNaN())
11903               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11904             if (D.isNaN())
11905               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11906             Recalc = true;
11907           }
11908           if (Recalc) {
11909             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11910             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11911           }
11912         }
11913       }
11914     } else {
11915       ComplexValue LHS = Result;
11916       Result.getComplexIntReal() =
11917         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11918          LHS.getComplexIntImag() * RHS.getComplexIntImag());
11919       Result.getComplexIntImag() =
11920         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11921          LHS.getComplexIntImag() * RHS.getComplexIntReal());
11922     }
11923     break;
11924   case BO_Div:
11925     if (Result.isComplexFloat()) {
11926       // This is an implementation of complex division according to the
11927       // constraints laid out in C11 Annex G. The implementation uses the
11928       // following naming scheme:
11929       //   (a + ib) / (c + id)
11930       ComplexValue LHS = Result;
11931       APFloat &A = LHS.getComplexFloatReal();
11932       APFloat &B = LHS.getComplexFloatImag();
11933       APFloat &C = RHS.getComplexFloatReal();
11934       APFloat &D = RHS.getComplexFloatImag();
11935       APFloat &ResR = Result.getComplexFloatReal();
11936       APFloat &ResI = Result.getComplexFloatImag();
11937       if (RHSReal) {
11938         ResR = A / C;
11939         ResI = B / C;
11940       } else {
11941         if (LHSReal) {
11942           // No real optimizations we can do here, stub out with zero.
11943           B = APFloat::getZero(A.getSemantics());
11944         }
11945         int DenomLogB = 0;
11946         APFloat MaxCD = maxnum(abs(C), abs(D));
11947         if (MaxCD.isFinite()) {
11948           DenomLogB = ilogb(MaxCD);
11949           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11950           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11951         }
11952         APFloat Denom = C * C + D * D;
11953         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11954                       APFloat::rmNearestTiesToEven);
11955         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11956                       APFloat::rmNearestTiesToEven);
11957         if (ResR.isNaN() && ResI.isNaN()) {
11958           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11959             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11960             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11961           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11962                      D.isFinite()) {
11963             A = APFloat::copySign(
11964                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11965             B = APFloat::copySign(
11966                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11967             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11968             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11969           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11970             C = APFloat::copySign(
11971                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11972             D = APFloat::copySign(
11973                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11974             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11975             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11976           }
11977         }
11978       }
11979     } else {
11980       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11981         return Error(E, diag::note_expr_divide_by_zero);
11982 
11983       ComplexValue LHS = Result;
11984       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11985         RHS.getComplexIntImag() * RHS.getComplexIntImag();
11986       Result.getComplexIntReal() =
11987         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11988          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11989       Result.getComplexIntImag() =
11990         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11991          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11992     }
11993     break;
11994   }
11995 
11996   return true;
11997 }
11998 
11999 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12000   // Get the operand value into 'Result'.
12001   if (!Visit(E->getSubExpr()))
12002     return false;
12003 
12004   switch (E->getOpcode()) {
12005   default:
12006     return Error(E);
12007   case UO_Extension:
12008     return true;
12009   case UO_Plus:
12010     // The result is always just the subexpr.
12011     return true;
12012   case UO_Minus:
12013     if (Result.isComplexFloat()) {
12014       Result.getComplexFloatReal().changeSign();
12015       Result.getComplexFloatImag().changeSign();
12016     }
12017     else {
12018       Result.getComplexIntReal() = -Result.getComplexIntReal();
12019       Result.getComplexIntImag() = -Result.getComplexIntImag();
12020     }
12021     return true;
12022   case UO_Not:
12023     if (Result.isComplexFloat())
12024       Result.getComplexFloatImag().changeSign();
12025     else
12026       Result.getComplexIntImag() = -Result.getComplexIntImag();
12027     return true;
12028   }
12029 }
12030 
12031 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12032   if (E->getNumInits() == 2) {
12033     if (E->getType()->isComplexType()) {
12034       Result.makeComplexFloat();
12035       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12036         return false;
12037       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12038         return false;
12039     } else {
12040       Result.makeComplexInt();
12041       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12042         return false;
12043       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12044         return false;
12045     }
12046     return true;
12047   }
12048   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12049 }
12050 
12051 //===----------------------------------------------------------------------===//
12052 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12053 // implicit conversion.
12054 //===----------------------------------------------------------------------===//
12055 
12056 namespace {
12057 class AtomicExprEvaluator :
12058     public ExprEvaluatorBase<AtomicExprEvaluator> {
12059   const LValue *This;
12060   APValue &Result;
12061 public:
12062   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12063       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12064 
12065   bool Success(const APValue &V, const Expr *E) {
12066     Result = V;
12067     return true;
12068   }
12069 
12070   bool ZeroInitialization(const Expr *E) {
12071     ImplicitValueInitExpr VIE(
12072         E->getType()->castAs<AtomicType>()->getValueType());
12073     // For atomic-qualified class (and array) types in C++, initialize the
12074     // _Atomic-wrapped subobject directly, in-place.
12075     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12076                 : Evaluate(Result, Info, &VIE);
12077   }
12078 
12079   bool VisitCastExpr(const CastExpr *E) {
12080     switch (E->getCastKind()) {
12081     default:
12082       return ExprEvaluatorBaseTy::VisitCastExpr(E);
12083     case CK_NonAtomicToAtomic:
12084       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12085                   : Evaluate(Result, Info, E->getSubExpr());
12086     }
12087   }
12088 };
12089 } // end anonymous namespace
12090 
12091 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12092                            EvalInfo &Info) {
12093   assert(E->isRValue() && E->getType()->isAtomicType());
12094   return AtomicExprEvaluator(Info, This, Result).Visit(E);
12095 }
12096 
12097 //===----------------------------------------------------------------------===//
12098 // Void expression evaluation, primarily for a cast to void on the LHS of a
12099 // comma operator
12100 //===----------------------------------------------------------------------===//
12101 
12102 namespace {
12103 class VoidExprEvaluator
12104   : public ExprEvaluatorBase<VoidExprEvaluator> {
12105 public:
12106   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12107 
12108   bool Success(const APValue &V, const Expr *e) { return true; }
12109 
12110   bool ZeroInitialization(const Expr *E) { return true; }
12111 
12112   bool VisitCastExpr(const CastExpr *E) {
12113     switch (E->getCastKind()) {
12114     default:
12115       return ExprEvaluatorBaseTy::VisitCastExpr(E);
12116     case CK_ToVoid:
12117       VisitIgnoredValue(E->getSubExpr());
12118       return true;
12119     }
12120   }
12121 
12122   bool VisitCallExpr(const CallExpr *E) {
12123     switch (E->getBuiltinCallee()) {
12124     default:
12125       return ExprEvaluatorBaseTy::VisitCallExpr(E);
12126     case Builtin::BI__assume:
12127     case Builtin::BI__builtin_assume:
12128       // The argument is not evaluated!
12129       return true;
12130     }
12131   }
12132 };
12133 } // end anonymous namespace
12134 
12135 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12136   assert(E->isRValue() && E->getType()->isVoidType());
12137   return VoidExprEvaluator(Info).Visit(E);
12138 }
12139 
12140 //===----------------------------------------------------------------------===//
12141 // Top level Expr::EvaluateAsRValue method.
12142 //===----------------------------------------------------------------------===//
12143 
12144 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
12145   // In C, function designators are not lvalues, but we evaluate them as if they
12146   // are.
12147   QualType T = E->getType();
12148   if (E->isGLValue() || T->isFunctionType()) {
12149     LValue LV;
12150     if (!EvaluateLValue(E, LV, Info))
12151       return false;
12152     LV.moveInto(Result);
12153   } else if (T->isVectorType()) {
12154     if (!EvaluateVector(E, Result, Info))
12155       return false;
12156   } else if (T->isIntegralOrEnumerationType()) {
12157     if (!IntExprEvaluator(Info, Result).Visit(E))
12158       return false;
12159   } else if (T->hasPointerRepresentation()) {
12160     LValue LV;
12161     if (!EvaluatePointer(E, LV, Info))
12162       return false;
12163     LV.moveInto(Result);
12164   } else if (T->isRealFloatingType()) {
12165     llvm::APFloat F(0.0);
12166     if (!EvaluateFloat(E, F, Info))
12167       return false;
12168     Result = APValue(F);
12169   } else if (T->isAnyComplexType()) {
12170     ComplexValue C;
12171     if (!EvaluateComplex(E, C, Info))
12172       return false;
12173     C.moveInto(Result);
12174   } else if (T->isFixedPointType()) {
12175     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
12176   } else if (T->isMemberPointerType()) {
12177     MemberPtr P;
12178     if (!EvaluateMemberPointer(E, P, Info))
12179       return false;
12180     P.moveInto(Result);
12181     return true;
12182   } else if (T->isArrayType()) {
12183     LValue LV;
12184     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12185     if (!EvaluateArray(E, LV, Value, Info))
12186       return false;
12187     Result = Value;
12188   } else if (T->isRecordType()) {
12189     LValue LV;
12190     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12191     if (!EvaluateRecord(E, LV, Value, Info))
12192       return false;
12193     Result = Value;
12194   } else if (T->isVoidType()) {
12195     if (!Info.getLangOpts().CPlusPlus11)
12196       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
12197         << E->getType();
12198     if (!EvaluateVoid(E, Info))
12199       return false;
12200   } else if (T->isAtomicType()) {
12201     QualType Unqual = T.getAtomicUnqualifiedType();
12202     if (Unqual->isArrayType() || Unqual->isRecordType()) {
12203       LValue LV;
12204       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12205       if (!EvaluateAtomic(E, &LV, Value, Info))
12206         return false;
12207     } else {
12208       if (!EvaluateAtomic(E, nullptr, Result, Info))
12209         return false;
12210     }
12211   } else if (Info.getLangOpts().CPlusPlus11) {
12212     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
12213     return false;
12214   } else {
12215     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12216     return false;
12217   }
12218 
12219   return true;
12220 }
12221 
12222 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12223 /// cases, the in-place evaluation is essential, since later initializers for
12224 /// an object can indirectly refer to subobjects which were initialized earlier.
12225 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
12226                             const Expr *E, bool AllowNonLiteralTypes) {
12227   assert(!E->isValueDependent());
12228 
12229   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
12230     return false;
12231 
12232   if (E->isRValue()) {
12233     // Evaluate arrays and record types in-place, so that later initializers can
12234     // refer to earlier-initialized members of the object.
12235     QualType T = E->getType();
12236     if (T->isArrayType())
12237       return EvaluateArray(E, This, Result, Info);
12238     else if (T->isRecordType())
12239       return EvaluateRecord(E, This, Result, Info);
12240     else if (T->isAtomicType()) {
12241       QualType Unqual = T.getAtomicUnqualifiedType();
12242       if (Unqual->isArrayType() || Unqual->isRecordType())
12243         return EvaluateAtomic(E, &This, Result, Info);
12244     }
12245   }
12246 
12247   // For any other type, in-place evaluation is unimportant.
12248   return Evaluate(Result, Info, E);
12249 }
12250 
12251 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12252 /// lvalue-to-rvalue cast if it is an lvalue.
12253 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
12254   if (E->getType().isNull())
12255     return false;
12256 
12257   if (!CheckLiteralType(Info, E))
12258     return false;
12259 
12260   if (!::Evaluate(Result, Info, E))
12261     return false;
12262 
12263   if (E->isGLValue()) {
12264     LValue LV;
12265     LV.setFrom(Info.Ctx, Result);
12266     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12267       return false;
12268   }
12269 
12270   // Check this core constant expression is a constant expression.
12271   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12272 }
12273 
12274 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
12275                                  const ASTContext &Ctx, bool &IsConst) {
12276   // Fast-path evaluations of integer literals, since we sometimes see files
12277   // containing vast quantities of these.
12278   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12279     Result.Val = APValue(APSInt(L->getValue(),
12280                                 L->getType()->isUnsignedIntegerType()));
12281     IsConst = true;
12282     return true;
12283   }
12284 
12285   // This case should be rare, but we need to check it before we check on
12286   // the type below.
12287   if (Exp->getType().isNull()) {
12288     IsConst = false;
12289     return true;
12290   }
12291 
12292   // FIXME: Evaluating values of large array and record types can cause
12293   // performance problems. Only do so in C++11 for now.
12294   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12295                           Exp->getType()->isRecordType()) &&
12296       !Ctx.getLangOpts().CPlusPlus11) {
12297     IsConst = false;
12298     return true;
12299   }
12300   return false;
12301 }
12302 
12303 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12304                                       Expr::SideEffectsKind SEK) {
12305   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12306          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12307 }
12308 
12309 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12310                              const ASTContext &Ctx, EvalInfo &Info) {
12311   bool IsConst;
12312   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12313     return IsConst;
12314 
12315   return EvaluateAsRValue(Info, E, Result.Val);
12316 }
12317 
12318 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12319                           const ASTContext &Ctx,
12320                           Expr::SideEffectsKind AllowSideEffects,
12321                           EvalInfo &Info) {
12322   if (!E->getType()->isIntegralOrEnumerationType())
12323     return false;
12324 
12325   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12326       !ExprResult.Val.isInt() ||
12327       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12328     return false;
12329 
12330   return true;
12331 }
12332 
12333 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12334                                  const ASTContext &Ctx,
12335                                  Expr::SideEffectsKind AllowSideEffects,
12336                                  EvalInfo &Info) {
12337   if (!E->getType()->isFixedPointType())
12338     return false;
12339 
12340   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12341     return false;
12342 
12343   if (!ExprResult.Val.isFixedPoint() ||
12344       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12345     return false;
12346 
12347   return true;
12348 }
12349 
12350 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
12351 /// any crazy technique (that has nothing to do with language standards) that
12352 /// we want to.  If this function returns true, it returns the folded constant
12353 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12354 /// will be applied to the result.
12355 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12356                             bool InConstantContext) const {
12357   assert(!isValueDependent() &&
12358          "Expression evaluator can't be called on a dependent expression.");
12359   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12360   Info.InConstantContext = InConstantContext;
12361   return ::EvaluateAsRValue(this, Result, Ctx, Info);
12362 }
12363 
12364 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12365                                       bool InConstantContext) const {
12366   assert(!isValueDependent() &&
12367          "Expression evaluator can't be called on a dependent expression.");
12368   EvalResult Scratch;
12369   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
12370          HandleConversionToBool(Scratch.Val, Result);
12371 }
12372 
12373 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
12374                          SideEffectsKind AllowSideEffects,
12375                          bool InConstantContext) const {
12376   assert(!isValueDependent() &&
12377          "Expression evaluator can't be called on a dependent expression.");
12378   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12379   Info.InConstantContext = InConstantContext;
12380   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
12381 }
12382 
12383 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
12384                                 SideEffectsKind AllowSideEffects,
12385                                 bool InConstantContext) const {
12386   assert(!isValueDependent() &&
12387          "Expression evaluator can't be called on a dependent expression.");
12388   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12389   Info.InConstantContext = InConstantContext;
12390   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12391 }
12392 
12393 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
12394                            SideEffectsKind AllowSideEffects,
12395                            bool InConstantContext) const {
12396   assert(!isValueDependent() &&
12397          "Expression evaluator can't be called on a dependent expression.");
12398 
12399   if (!getType()->isRealFloatingType())
12400     return false;
12401 
12402   EvalResult ExprResult;
12403   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12404       !ExprResult.Val.isFloat() ||
12405       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12406     return false;
12407 
12408   Result = ExprResult.Val.getFloat();
12409   return true;
12410 }
12411 
12412 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12413                             bool InConstantContext) const {
12414   assert(!isValueDependent() &&
12415          "Expression evaluator can't be called on a dependent expression.");
12416 
12417   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
12418   Info.InConstantContext = InConstantContext;
12419   LValue LV;
12420   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12421       !CheckLValueConstantExpression(Info, getExprLoc(),
12422                                      Ctx.getLValueReferenceType(getType()), LV,
12423                                      Expr::EvaluateForCodeGen))
12424     return false;
12425 
12426   LV.moveInto(Result.Val);
12427   return true;
12428 }
12429 
12430 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12431                                   const ASTContext &Ctx) const {
12432   assert(!isValueDependent() &&
12433          "Expression evaluator can't be called on a dependent expression.");
12434 
12435   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12436   EvalInfo Info(Ctx, Result, EM);
12437   Info.InConstantContext = true;
12438 
12439   if (!::Evaluate(Result.Val, Info, this))
12440     return false;
12441 
12442   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12443                                  Usage);
12444 }
12445 
12446 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12447                                  const VarDecl *VD,
12448                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
12449   assert(!isValueDependent() &&
12450          "Expression evaluator can't be called on a dependent expression.");
12451 
12452   // FIXME: Evaluating initializers for large array and record types can cause
12453   // performance problems. Only do so in C++11 for now.
12454   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
12455       !Ctx.getLangOpts().CPlusPlus11)
12456     return false;
12457 
12458   Expr::EvalStatus EStatus;
12459   EStatus.Diag = &Notes;
12460 
12461   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12462                                       ? EvalInfo::EM_ConstantExpression
12463                                       : EvalInfo::EM_ConstantFold);
12464   InitInfo.setEvaluatingDecl(VD, Value);
12465   InitInfo.InConstantContext = true;
12466 
12467   LValue LVal;
12468   LVal.set(VD);
12469 
12470   // C++11 [basic.start.init]p2:
12471   //  Variables with static storage duration or thread storage duration shall be
12472   //  zero-initialized before any other initialization takes place.
12473   // This behavior is not present in C.
12474   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
12475       !VD->getType()->isReferenceType()) {
12476     ImplicitValueInitExpr VIE(VD->getType());
12477     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
12478                          /*AllowNonLiteralTypes=*/true))
12479       return false;
12480   }
12481 
12482   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12483                        /*AllowNonLiteralTypes=*/true) ||
12484       EStatus.HasSideEffects)
12485     return false;
12486 
12487   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12488                                  Value);
12489 }
12490 
12491 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12492 /// constant folded, but discard the result.
12493 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12494   assert(!isValueDependent() &&
12495          "Expression evaluator can't be called on a dependent expression.");
12496 
12497   EvalResult Result;
12498   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12499          !hasUnacceptableSideEffect(Result, SEK);
12500 }
12501 
12502 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
12503                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12504   assert(!isValueDependent() &&
12505          "Expression evaluator can't be called on a dependent expression.");
12506 
12507   EvalResult EVResult;
12508   EVResult.Diag = Diag;
12509   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12510   Info.InConstantContext = true;
12511 
12512   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12513   (void)Result;
12514   assert(Result && "Could not evaluate expression");
12515   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12516 
12517   return EVResult.Val.getInt();
12518 }
12519 
12520 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12521     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12522   assert(!isValueDependent() &&
12523          "Expression evaluator can't be called on a dependent expression.");
12524 
12525   EvalResult EVResult;
12526   EVResult.Diag = Diag;
12527   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12528   Info.InConstantContext = true;
12529   Info.CheckingForUndefinedBehavior = true;
12530 
12531   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12532   (void)Result;
12533   assert(Result && "Could not evaluate expression");
12534   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12535 
12536   return EVResult.Val.getInt();
12537 }
12538 
12539 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12540   assert(!isValueDependent() &&
12541          "Expression evaluator can't be called on a dependent expression.");
12542 
12543   bool IsConst;
12544   EvalResult EVResult;
12545   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12546     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12547     Info.CheckingForUndefinedBehavior = true;
12548     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12549   }
12550 }
12551 
12552 bool Expr::EvalResult::isGlobalLValue() const {
12553   assert(Val.isLValue());
12554   return IsGlobalLValue(Val.getLValueBase());
12555 }
12556 
12557 
12558 /// isIntegerConstantExpr - this recursive routine will test if an expression is
12559 /// an integer constant expression.
12560 
12561 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12562 /// comma, etc
12563 
12564 // CheckICE - This function does the fundamental ICE checking: the returned
12565 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12566 // and a (possibly null) SourceLocation indicating the location of the problem.
12567 //
12568 // Note that to reduce code duplication, this helper does no evaluation
12569 // itself; the caller checks whether the expression is evaluatable, and
12570 // in the rare cases where CheckICE actually cares about the evaluated
12571 // value, it calls into Evaluate.
12572 
12573 namespace {
12574 
12575 enum ICEKind {
12576   /// This expression is an ICE.
12577   IK_ICE,
12578   /// This expression is not an ICE, but if it isn't evaluated, it's
12579   /// a legal subexpression for an ICE. This return value is used to handle
12580   /// the comma operator in C99 mode, and non-constant subexpressions.
12581   IK_ICEIfUnevaluated,
12582   /// This expression is not an ICE, and is not a legal subexpression for one.
12583   IK_NotICE
12584 };
12585 
12586 struct ICEDiag {
12587   ICEKind Kind;
12588   SourceLocation Loc;
12589 
12590   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12591 };
12592 
12593 }
12594 
12595 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12596 
12597 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12598 
12599 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12600   Expr::EvalResult EVResult;
12601   Expr::EvalStatus Status;
12602   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12603 
12604   Info.InConstantContext = true;
12605   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12606       !EVResult.Val.isInt())
12607     return ICEDiag(IK_NotICE, E->getBeginLoc());
12608 
12609   return NoDiag();
12610 }
12611 
12612 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12613   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12614   if (!E->getType()->isIntegralOrEnumerationType())
12615     return ICEDiag(IK_NotICE, E->getBeginLoc());
12616 
12617   switch (E->getStmtClass()) {
12618 #define ABSTRACT_STMT(Node)
12619 #define STMT(Node, Base) case Expr::Node##Class:
12620 #define EXPR(Node, Base)
12621 #include "clang/AST/StmtNodes.inc"
12622   case Expr::PredefinedExprClass:
12623   case Expr::FloatingLiteralClass:
12624   case Expr::ImaginaryLiteralClass:
12625   case Expr::StringLiteralClass:
12626   case Expr::ArraySubscriptExprClass:
12627   case Expr::OMPArraySectionExprClass:
12628   case Expr::MemberExprClass:
12629   case Expr::CompoundAssignOperatorClass:
12630   case Expr::CompoundLiteralExprClass:
12631   case Expr::ExtVectorElementExprClass:
12632   case Expr::DesignatedInitExprClass:
12633   case Expr::ArrayInitLoopExprClass:
12634   case Expr::ArrayInitIndexExprClass:
12635   case Expr::NoInitExprClass:
12636   case Expr::DesignatedInitUpdateExprClass:
12637   case Expr::ImplicitValueInitExprClass:
12638   case Expr::ParenListExprClass:
12639   case Expr::VAArgExprClass:
12640   case Expr::AddrLabelExprClass:
12641   case Expr::StmtExprClass:
12642   case Expr::CXXMemberCallExprClass:
12643   case Expr::CUDAKernelCallExprClass:
12644   case Expr::CXXDynamicCastExprClass:
12645   case Expr::CXXTypeidExprClass:
12646   case Expr::CXXUuidofExprClass:
12647   case Expr::MSPropertyRefExprClass:
12648   case Expr::MSPropertySubscriptExprClass:
12649   case Expr::CXXNullPtrLiteralExprClass:
12650   case Expr::UserDefinedLiteralClass:
12651   case Expr::CXXThisExprClass:
12652   case Expr::CXXThrowExprClass:
12653   case Expr::CXXNewExprClass:
12654   case Expr::CXXDeleteExprClass:
12655   case Expr::CXXPseudoDestructorExprClass:
12656   case Expr::UnresolvedLookupExprClass:
12657   case Expr::TypoExprClass:
12658   case Expr::DependentScopeDeclRefExprClass:
12659   case Expr::CXXConstructExprClass:
12660   case Expr::CXXInheritedCtorInitExprClass:
12661   case Expr::CXXStdInitializerListExprClass:
12662   case Expr::CXXBindTemporaryExprClass:
12663   case Expr::ExprWithCleanupsClass:
12664   case Expr::CXXTemporaryObjectExprClass:
12665   case Expr::CXXUnresolvedConstructExprClass:
12666   case Expr::CXXDependentScopeMemberExprClass:
12667   case Expr::UnresolvedMemberExprClass:
12668   case Expr::ObjCStringLiteralClass:
12669   case Expr::ObjCBoxedExprClass:
12670   case Expr::ObjCArrayLiteralClass:
12671   case Expr::ObjCDictionaryLiteralClass:
12672   case Expr::ObjCEncodeExprClass:
12673   case Expr::ObjCMessageExprClass:
12674   case Expr::ObjCSelectorExprClass:
12675   case Expr::ObjCProtocolExprClass:
12676   case Expr::ObjCIvarRefExprClass:
12677   case Expr::ObjCPropertyRefExprClass:
12678   case Expr::ObjCSubscriptRefExprClass:
12679   case Expr::ObjCIsaExprClass:
12680   case Expr::ObjCAvailabilityCheckExprClass:
12681   case Expr::ShuffleVectorExprClass:
12682   case Expr::ConvertVectorExprClass:
12683   case Expr::BlockExprClass:
12684   case Expr::NoStmtClass:
12685   case Expr::OpaqueValueExprClass:
12686   case Expr::PackExpansionExprClass:
12687   case Expr::SubstNonTypeTemplateParmPackExprClass:
12688   case Expr::FunctionParmPackExprClass:
12689   case Expr::AsTypeExprClass:
12690   case Expr::ObjCIndirectCopyRestoreExprClass:
12691   case Expr::MaterializeTemporaryExprClass:
12692   case Expr::PseudoObjectExprClass:
12693   case Expr::AtomicExprClass:
12694   case Expr::LambdaExprClass:
12695   case Expr::CXXFoldExprClass:
12696   case Expr::CoawaitExprClass:
12697   case Expr::DependentCoawaitExprClass:
12698   case Expr::CoyieldExprClass:
12699     return ICEDiag(IK_NotICE, E->getBeginLoc());
12700 
12701   case Expr::InitListExprClass: {
12702     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12703     // form "T x = { a };" is equivalent to "T x = a;".
12704     // Unless we're initializing a reference, T is a scalar as it is known to be
12705     // of integral or enumeration type.
12706     if (E->isRValue())
12707       if (cast<InitListExpr>(E)->getNumInits() == 1)
12708         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12709     return ICEDiag(IK_NotICE, E->getBeginLoc());
12710   }
12711 
12712   case Expr::SizeOfPackExprClass:
12713   case Expr::GNUNullExprClass:
12714   case Expr::SourceLocExprClass:
12715     return NoDiag();
12716 
12717   case Expr::SubstNonTypeTemplateParmExprClass:
12718     return
12719       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12720 
12721   case Expr::ConstantExprClass:
12722     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12723 
12724   case Expr::ParenExprClass:
12725     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12726   case Expr::GenericSelectionExprClass:
12727     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12728   case Expr::IntegerLiteralClass:
12729   case Expr::FixedPointLiteralClass:
12730   case Expr::CharacterLiteralClass:
12731   case Expr::ObjCBoolLiteralExprClass:
12732   case Expr::CXXBoolLiteralExprClass:
12733   case Expr::CXXScalarValueInitExprClass:
12734   case Expr::TypeTraitExprClass:
12735   case Expr::ArrayTypeTraitExprClass:
12736   case Expr::ExpressionTraitExprClass:
12737   case Expr::CXXNoexceptExprClass:
12738     return NoDiag();
12739   case Expr::CallExprClass:
12740   case Expr::CXXOperatorCallExprClass: {
12741     // C99 6.6/3 allows function calls within unevaluated subexpressions of
12742     // constant expressions, but they can never be ICEs because an ICE cannot
12743     // contain an operand of (pointer to) function type.
12744     const CallExpr *CE = cast<CallExpr>(E);
12745     if (CE->getBuiltinCallee())
12746       return CheckEvalInICE(E, Ctx);
12747     return ICEDiag(IK_NotICE, E->getBeginLoc());
12748   }
12749   case Expr::DeclRefExprClass: {
12750     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12751       return NoDiag();
12752     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12753     if (Ctx.getLangOpts().CPlusPlus &&
12754         D && IsConstNonVolatile(D->getType())) {
12755       // Parameter variables are never constants.  Without this check,
12756       // getAnyInitializer() can find a default argument, which leads
12757       // to chaos.
12758       if (isa<ParmVarDecl>(D))
12759         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12760 
12761       // C++ 7.1.5.1p2
12762       //   A variable of non-volatile const-qualified integral or enumeration
12763       //   type initialized by an ICE can be used in ICEs.
12764       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12765         if (!Dcl->getType()->isIntegralOrEnumerationType())
12766           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12767 
12768         const VarDecl *VD;
12769         // Look for a declaration of this variable that has an initializer, and
12770         // check whether it is an ICE.
12771         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12772           return NoDiag();
12773         else
12774           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12775       }
12776     }
12777     return ICEDiag(IK_NotICE, E->getBeginLoc());
12778   }
12779   case Expr::UnaryOperatorClass: {
12780     const UnaryOperator *Exp = cast<UnaryOperator>(E);
12781     switch (Exp->getOpcode()) {
12782     case UO_PostInc:
12783     case UO_PostDec:
12784     case UO_PreInc:
12785     case UO_PreDec:
12786     case UO_AddrOf:
12787     case UO_Deref:
12788     case UO_Coawait:
12789       // C99 6.6/3 allows increment and decrement within unevaluated
12790       // subexpressions of constant expressions, but they can never be ICEs
12791       // because an ICE cannot contain an lvalue operand.
12792       return ICEDiag(IK_NotICE, E->getBeginLoc());
12793     case UO_Extension:
12794     case UO_LNot:
12795     case UO_Plus:
12796     case UO_Minus:
12797     case UO_Not:
12798     case UO_Real:
12799     case UO_Imag:
12800       return CheckICE(Exp->getSubExpr(), Ctx);
12801     }
12802     llvm_unreachable("invalid unary operator class");
12803   }
12804   case Expr::OffsetOfExprClass: {
12805     // Note that per C99, offsetof must be an ICE. And AFAIK, using
12806     // EvaluateAsRValue matches the proposed gcc behavior for cases like
12807     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
12808     // compliance: we should warn earlier for offsetof expressions with
12809     // array subscripts that aren't ICEs, and if the array subscripts
12810     // are ICEs, the value of the offsetof must be an integer constant.
12811     return CheckEvalInICE(E, Ctx);
12812   }
12813   case Expr::UnaryExprOrTypeTraitExprClass: {
12814     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12815     if ((Exp->getKind() ==  UETT_SizeOf) &&
12816         Exp->getTypeOfArgument()->isVariableArrayType())
12817       return ICEDiag(IK_NotICE, E->getBeginLoc());
12818     return NoDiag();
12819   }
12820   case Expr::BinaryOperatorClass: {
12821     const BinaryOperator *Exp = cast<BinaryOperator>(E);
12822     switch (Exp->getOpcode()) {
12823     case BO_PtrMemD:
12824     case BO_PtrMemI:
12825     case BO_Assign:
12826     case BO_MulAssign:
12827     case BO_DivAssign:
12828     case BO_RemAssign:
12829     case BO_AddAssign:
12830     case BO_SubAssign:
12831     case BO_ShlAssign:
12832     case BO_ShrAssign:
12833     case BO_AndAssign:
12834     case BO_XorAssign:
12835     case BO_OrAssign:
12836       // C99 6.6/3 allows assignments within unevaluated subexpressions of
12837       // constant expressions, but they can never be ICEs because an ICE cannot
12838       // contain an lvalue operand.
12839       return ICEDiag(IK_NotICE, E->getBeginLoc());
12840 
12841     case BO_Mul:
12842     case BO_Div:
12843     case BO_Rem:
12844     case BO_Add:
12845     case BO_Sub:
12846     case BO_Shl:
12847     case BO_Shr:
12848     case BO_LT:
12849     case BO_GT:
12850     case BO_LE:
12851     case BO_GE:
12852     case BO_EQ:
12853     case BO_NE:
12854     case BO_And:
12855     case BO_Xor:
12856     case BO_Or:
12857     case BO_Comma:
12858     case BO_Cmp: {
12859       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12860       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12861       if (Exp->getOpcode() == BO_Div ||
12862           Exp->getOpcode() == BO_Rem) {
12863         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12864         // we don't evaluate one.
12865         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12866           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12867           if (REval == 0)
12868             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12869           if (REval.isSigned() && REval.isAllOnesValue()) {
12870             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12871             if (LEval.isMinSignedValue())
12872               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12873           }
12874         }
12875       }
12876       if (Exp->getOpcode() == BO_Comma) {
12877         if (Ctx.getLangOpts().C99) {
12878           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12879           // if it isn't evaluated.
12880           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12881             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12882         } else {
12883           // In both C89 and C++, commas in ICEs are illegal.
12884           return ICEDiag(IK_NotICE, E->getBeginLoc());
12885         }
12886       }
12887       return Worst(LHSResult, RHSResult);
12888     }
12889     case BO_LAnd:
12890     case BO_LOr: {
12891       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12892       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12893       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12894         // Rare case where the RHS has a comma "side-effect"; we need
12895         // to actually check the condition to see whether the side
12896         // with the comma is evaluated.
12897         if ((Exp->getOpcode() == BO_LAnd) !=
12898             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12899           return RHSResult;
12900         return NoDiag();
12901       }
12902 
12903       return Worst(LHSResult, RHSResult);
12904     }
12905     }
12906     llvm_unreachable("invalid binary operator kind");
12907   }
12908   case Expr::ImplicitCastExprClass:
12909   case Expr::CStyleCastExprClass:
12910   case Expr::CXXFunctionalCastExprClass:
12911   case Expr::CXXStaticCastExprClass:
12912   case Expr::CXXReinterpretCastExprClass:
12913   case Expr::CXXConstCastExprClass:
12914   case Expr::ObjCBridgedCastExprClass: {
12915     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12916     if (isa<ExplicitCastExpr>(E)) {
12917       if (const FloatingLiteral *FL
12918             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12919         unsigned DestWidth = Ctx.getIntWidth(E->getType());
12920         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12921         APSInt IgnoredVal(DestWidth, !DestSigned);
12922         bool Ignored;
12923         // If the value does not fit in the destination type, the behavior is
12924         // undefined, so we are not required to treat it as a constant
12925         // expression.
12926         if (FL->getValue().convertToInteger(IgnoredVal,
12927                                             llvm::APFloat::rmTowardZero,
12928                                             &Ignored) & APFloat::opInvalidOp)
12929           return ICEDiag(IK_NotICE, E->getBeginLoc());
12930         return NoDiag();
12931       }
12932     }
12933     switch (cast<CastExpr>(E)->getCastKind()) {
12934     case CK_LValueToRValue:
12935     case CK_AtomicToNonAtomic:
12936     case CK_NonAtomicToAtomic:
12937     case CK_NoOp:
12938     case CK_IntegralToBoolean:
12939     case CK_IntegralCast:
12940       return CheckICE(SubExpr, Ctx);
12941     default:
12942       return ICEDiag(IK_NotICE, E->getBeginLoc());
12943     }
12944   }
12945   case Expr::BinaryConditionalOperatorClass: {
12946     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12947     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12948     if (CommonResult.Kind == IK_NotICE) return CommonResult;
12949     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12950     if (FalseResult.Kind == IK_NotICE) return FalseResult;
12951     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12952     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12953         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12954     return FalseResult;
12955   }
12956   case Expr::ConditionalOperatorClass: {
12957     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12958     // If the condition (ignoring parens) is a __builtin_constant_p call,
12959     // then only the true side is actually considered in an integer constant
12960     // expression, and it is fully evaluated.  This is an important GNU
12961     // extension.  See GCC PR38377 for discussion.
12962     if (const CallExpr *CallCE
12963         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12964       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12965         return CheckEvalInICE(E, Ctx);
12966     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12967     if (CondResult.Kind == IK_NotICE)
12968       return CondResult;
12969 
12970     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12971     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12972 
12973     if (TrueResult.Kind == IK_NotICE)
12974       return TrueResult;
12975     if (FalseResult.Kind == IK_NotICE)
12976       return FalseResult;
12977     if (CondResult.Kind == IK_ICEIfUnevaluated)
12978       return CondResult;
12979     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
12980       return NoDiag();
12981     // Rare case where the diagnostics depend on which side is evaluated
12982     // Note that if we get here, CondResult is 0, and at least one of
12983     // TrueResult and FalseResult is non-zero.
12984     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
12985       return FalseResult;
12986     return TrueResult;
12987   }
12988   case Expr::CXXDefaultArgExprClass:
12989     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
12990   case Expr::CXXDefaultInitExprClass:
12991     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
12992   case Expr::ChooseExprClass: {
12993     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
12994   }
12995   case Expr::BuiltinBitCastExprClass: {
12996     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
12997       return ICEDiag(IK_NotICE, E->getBeginLoc());
12998     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
12999   }
13000   }
13001 
13002   llvm_unreachable("Invalid StmtClass!");
13003 }
13004 
13005 /// Evaluate an expression as a C++11 integral constant expression.
13006 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
13007                                                     const Expr *E,
13008                                                     llvm::APSInt *Value,
13009                                                     SourceLocation *Loc) {
13010   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13011     if (Loc) *Loc = E->getExprLoc();
13012     return false;
13013   }
13014 
13015   APValue Result;
13016   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
13017     return false;
13018 
13019   if (!Result.isInt()) {
13020     if (Loc) *Loc = E->getExprLoc();
13021     return false;
13022   }
13023 
13024   if (Value) *Value = Result.getInt();
13025   return true;
13026 }
13027 
13028 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13029                                  SourceLocation *Loc) const {
13030   assert(!isValueDependent() &&
13031          "Expression evaluator can't be called on a dependent expression.");
13032 
13033   if (Ctx.getLangOpts().CPlusPlus11)
13034     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
13035 
13036   ICEDiag D = CheckICE(this, Ctx);
13037   if (D.Kind != IK_ICE) {
13038     if (Loc) *Loc = D.Loc;
13039     return false;
13040   }
13041   return true;
13042 }
13043 
13044 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
13045                                  SourceLocation *Loc, bool isEvaluated) const {
13046   assert(!isValueDependent() &&
13047          "Expression evaluator can't be called on a dependent expression.");
13048 
13049   if (Ctx.getLangOpts().CPlusPlus11)
13050     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13051 
13052   if (!isIntegerConstantExpr(Ctx, Loc))
13053     return false;
13054 
13055   // The only possible side-effects here are due to UB discovered in the
13056   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13057   // required to treat the expression as an ICE, so we produce the folded
13058   // value.
13059   EvalResult ExprResult;
13060   Expr::EvalStatus Status;
13061   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13062   Info.InConstantContext = true;
13063 
13064   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
13065     llvm_unreachable("ICE cannot be evaluated!");
13066 
13067   Value = ExprResult.Val.getInt();
13068   return true;
13069 }
13070 
13071 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
13072   assert(!isValueDependent() &&
13073          "Expression evaluator can't be called on a dependent expression.");
13074 
13075   return CheckICE(this, Ctx).Kind == IK_ICE;
13076 }
13077 
13078 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
13079                                SourceLocation *Loc) const {
13080   assert(!isValueDependent() &&
13081          "Expression evaluator can't be called on a dependent expression.");
13082 
13083   // We support this checking in C++98 mode in order to diagnose compatibility
13084   // issues.
13085   assert(Ctx.getLangOpts().CPlusPlus);
13086 
13087   // Build evaluation settings.
13088   Expr::EvalStatus Status;
13089   SmallVector<PartialDiagnosticAt, 8> Diags;
13090   Status.Diag = &Diags;
13091   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13092 
13093   APValue Scratch;
13094   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13095 
13096   if (!Diags.empty()) {
13097     IsConstExpr = false;
13098     if (Loc) *Loc = Diags[0].first;
13099   } else if (!IsConstExpr) {
13100     // FIXME: This shouldn't happen.
13101     if (Loc) *Loc = getExprLoc();
13102   }
13103 
13104   return IsConstExpr;
13105 }
13106 
13107 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13108                                     const FunctionDecl *Callee,
13109                                     ArrayRef<const Expr*> Args,
13110                                     const Expr *This) const {
13111   assert(!isValueDependent() &&
13112          "Expression evaluator can't be called on a dependent expression.");
13113 
13114   Expr::EvalStatus Status;
13115   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
13116   Info.InConstantContext = true;
13117 
13118   LValue ThisVal;
13119   const LValue *ThisPtr = nullptr;
13120   if (This) {
13121 #ifndef NDEBUG
13122     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13123     assert(MD && "Don't provide `this` for non-methods.");
13124     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13125 #endif
13126     if (EvaluateObjectArgument(Info, This, ThisVal))
13127       ThisPtr = &ThisVal;
13128     if (Info.EvalStatus.HasSideEffects)
13129       return false;
13130   }
13131 
13132   ArgVector ArgValues(Args.size());
13133   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13134        I != E; ++I) {
13135     if ((*I)->isValueDependent() ||
13136         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
13137       // If evaluation fails, throw away the argument entirely.
13138       ArgValues[I - Args.begin()] = APValue();
13139     if (Info.EvalStatus.HasSideEffects)
13140       return false;
13141   }
13142 
13143   // Build fake call to Callee.
13144   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
13145                        ArgValues.data());
13146   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13147 }
13148 
13149 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
13150                                    SmallVectorImpl<
13151                                      PartialDiagnosticAt> &Diags) {
13152   // FIXME: It would be useful to check constexpr function templates, but at the
13153   // moment the constant expression evaluator cannot cope with the non-rigorous
13154   // ASTs which we build for dependent expressions.
13155   if (FD->isDependentContext())
13156     return true;
13157 
13158   Expr::EvalStatus Status;
13159   Status.Diag = &Diags;
13160 
13161   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
13162   Info.InConstantContext = true;
13163   Info.CheckingPotentialConstantExpression = true;
13164 
13165   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
13166   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
13167 
13168   // Fabricate an arbitrary expression on the stack and pretend that it
13169   // is a temporary being used as the 'this' pointer.
13170   LValue This;
13171   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
13172   This.set({&VIE, Info.CurrentCall->Index});
13173 
13174   ArrayRef<const Expr*> Args;
13175 
13176   APValue Scratch;
13177   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13178     // Evaluate the call as a constant initializer, to allow the construction
13179     // of objects of non-literal types.
13180     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
13181     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13182   } else {
13183     SourceLocation Loc = FD->getLocation();
13184     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
13185                        Args, FD->getBody(), Info, Scratch, nullptr);
13186   }
13187 
13188   return Diags.empty();
13189 }
13190 
13191 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13192                                               const FunctionDecl *FD,
13193                                               SmallVectorImpl<
13194                                                 PartialDiagnosticAt> &Diags) {
13195   assert(!E->isValueDependent() &&
13196          "Expression evaluator can't be called on a dependent expression.");
13197 
13198   Expr::EvalStatus Status;
13199   Status.Diag = &Diags;
13200 
13201   EvalInfo Info(FD->getASTContext(), Status,
13202                 EvalInfo::EM_ConstantExpressionUnevaluated);
13203   Info.InConstantContext = true;
13204   Info.CheckingPotentialConstantExpression = true;
13205 
13206   // Fabricate a call stack frame to give the arguments a plausible cover story.
13207   ArrayRef<const Expr*> Args;
13208   ArgVector ArgValues(0);
13209   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
13210   (void)Success;
13211   assert(Success &&
13212          "Failed to set up arguments for potential constant evaluation");
13213   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
13214 
13215   APValue ResultScratch;
13216   Evaluate(ResultScratch, Info, E);
13217   return Diags.empty();
13218 }
13219 
13220 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13221                                  unsigned Type) const {
13222   if (!getType()->isPointerType())
13223     return false;
13224 
13225   Expr::EvalStatus Status;
13226   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
13227   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
13228 }
13229