xref: /freebsd/contrib/llvm-project/clang/lib/AST/ExprConstant.cpp (revision 6966ac055c3b7a39266fb982493330df7a097997)
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/CharUnits.h"
40 #include "clang/AST/CurrentSourceLocExprScope.h"
41 #include "clang/AST/CXXInheritance.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       return GCCTypeClass::None;
8990 
8991     case BuiltinType::Dependent:
8992       llvm_unreachable("unexpected dependent type");
8993     };
8994     llvm_unreachable("unexpected placeholder type");
8995 
8996   case Type::Enum:
8997     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
8998 
8999   case Type::Pointer:
9000   case Type::ConstantArray:
9001   case Type::VariableArray:
9002   case Type::IncompleteArray:
9003   case Type::FunctionNoProto:
9004   case Type::FunctionProto:
9005     return GCCTypeClass::Pointer;
9006 
9007   case Type::MemberPointer:
9008     return CanTy->isMemberDataPointerType()
9009                ? GCCTypeClass::PointerToDataMember
9010                : GCCTypeClass::PointerToMemberFunction;
9011 
9012   case Type::Complex:
9013     return GCCTypeClass::Complex;
9014 
9015   case Type::Record:
9016     return CanTy->isUnionType() ? GCCTypeClass::Union
9017                                 : GCCTypeClass::ClassOrStruct;
9018 
9019   case Type::Atomic:
9020     // GCC classifies _Atomic T the same as T.
9021     return EvaluateBuiltinClassifyType(
9022         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
9023 
9024   case Type::BlockPointer:
9025   case Type::Vector:
9026   case Type::ExtVector:
9027   case Type::ObjCObject:
9028   case Type::ObjCInterface:
9029   case Type::ObjCObjectPointer:
9030   case Type::Pipe:
9031     // GCC classifies vectors as None. We follow its lead and classify all
9032     // other types that don't fit into the regular classification the same way.
9033     return GCCTypeClass::None;
9034 
9035   case Type::LValueReference:
9036   case Type::RValueReference:
9037     llvm_unreachable("invalid type for expression");
9038   }
9039 
9040   llvm_unreachable("unexpected type class");
9041 }
9042 
9043 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
9044 /// as GCC.
9045 static GCCTypeClass
9046 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
9047   // If no argument was supplied, default to None. This isn't
9048   // ideal, however it is what gcc does.
9049   if (E->getNumArgs() == 0)
9050     return GCCTypeClass::None;
9051 
9052   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
9053   // being an ICE, but still folds it to a constant using the type of the first
9054   // argument.
9055   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
9056 }
9057 
9058 /// EvaluateBuiltinConstantPForLValue - Determine the result of
9059 /// __builtin_constant_p when applied to the given pointer.
9060 ///
9061 /// A pointer is only "constant" if it is null (or a pointer cast to integer)
9062 /// or it points to the first character of a string literal.
9063 static bool EvaluateBuiltinConstantPForLValue(const APValue &LV) {
9064   APValue::LValueBase Base = LV.getLValueBase();
9065   if (Base.isNull()) {
9066     // A null base is acceptable.
9067     return true;
9068   } else if (const Expr *E = Base.dyn_cast<const Expr *>()) {
9069     if (!isa<StringLiteral>(E))
9070       return false;
9071     return LV.getLValueOffset().isZero();
9072   } else if (Base.is<TypeInfoLValue>()) {
9073     // Surprisingly, GCC considers __builtin_constant_p(&typeid(int)) to
9074     // evaluate to true.
9075     return true;
9076   } else {
9077     // Any other base is not constant enough for GCC.
9078     return false;
9079   }
9080 }
9081 
9082 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
9083 /// GCC as we can manage.
9084 static bool EvaluateBuiltinConstantP(EvalInfo &Info, const Expr *Arg) {
9085   // This evaluation is not permitted to have side-effects, so evaluate it in
9086   // a speculative evaluation context.
9087   SpeculativeEvaluationRAII SpeculativeEval(Info);
9088 
9089   // Constant-folding is always enabled for the operand of __builtin_constant_p
9090   // (even when the enclosing evaluation context otherwise requires a strict
9091   // language-specific constant expression).
9092   FoldConstant Fold(Info, true);
9093 
9094   QualType ArgType = Arg->getType();
9095 
9096   // __builtin_constant_p always has one operand. The rules which gcc follows
9097   // are not precisely documented, but are as follows:
9098   //
9099   //  - If the operand is of integral, floating, complex or enumeration type,
9100   //    and can be folded to a known value of that type, it returns 1.
9101   //  - If the operand can be folded to a pointer to the first character
9102   //    of a string literal (or such a pointer cast to an integral type)
9103   //    or to a null pointer or an integer cast to a pointer, it returns 1.
9104   //
9105   // Otherwise, it returns 0.
9106   //
9107   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
9108   // its support for this did not work prior to GCC 9 and is not yet well
9109   // understood.
9110   if (ArgType->isIntegralOrEnumerationType() || ArgType->isFloatingType() ||
9111       ArgType->isAnyComplexType() || ArgType->isPointerType() ||
9112       ArgType->isNullPtrType()) {
9113     APValue V;
9114     if (!::EvaluateAsRValue(Info, Arg, V)) {
9115       Fold.keepDiagnostics();
9116       return false;
9117     }
9118 
9119     // For a pointer (possibly cast to integer), there are special rules.
9120     if (V.getKind() == APValue::LValue)
9121       return EvaluateBuiltinConstantPForLValue(V);
9122 
9123     // Otherwise, any constant value is good enough.
9124     return V.hasValue();
9125   }
9126 
9127   // Anything else isn't considered to be sufficiently constant.
9128   return false;
9129 }
9130 
9131 /// Retrieves the "underlying object type" of the given expression,
9132 /// as used by __builtin_object_size.
9133 static QualType getObjectType(APValue::LValueBase B) {
9134   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
9135     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
9136       return VD->getType();
9137   } else if (const Expr *E = B.get<const Expr*>()) {
9138     if (isa<CompoundLiteralExpr>(E))
9139       return E->getType();
9140   } else if (B.is<TypeInfoLValue>()) {
9141     return B.getTypeInfoType();
9142   }
9143 
9144   return QualType();
9145 }
9146 
9147 /// A more selective version of E->IgnoreParenCasts for
9148 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
9149 /// to change the type of E.
9150 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
9151 ///
9152 /// Always returns an RValue with a pointer representation.
9153 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
9154   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
9155 
9156   auto *NoParens = E->IgnoreParens();
9157   auto *Cast = dyn_cast<CastExpr>(NoParens);
9158   if (Cast == nullptr)
9159     return NoParens;
9160 
9161   // We only conservatively allow a few kinds of casts, because this code is
9162   // inherently a simple solution that seeks to support the common case.
9163   auto CastKind = Cast->getCastKind();
9164   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
9165       CastKind != CK_AddressSpaceConversion)
9166     return NoParens;
9167 
9168   auto *SubExpr = Cast->getSubExpr();
9169   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
9170     return NoParens;
9171   return ignorePointerCastsAndParens(SubExpr);
9172 }
9173 
9174 /// Checks to see if the given LValue's Designator is at the end of the LValue's
9175 /// record layout. e.g.
9176 ///   struct { struct { int a, b; } fst, snd; } obj;
9177 ///   obj.fst   // no
9178 ///   obj.snd   // yes
9179 ///   obj.fst.a // no
9180 ///   obj.fst.b // no
9181 ///   obj.snd.a // no
9182 ///   obj.snd.b // yes
9183 ///
9184 /// Please note: this function is specialized for how __builtin_object_size
9185 /// views "objects".
9186 ///
9187 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
9188 /// correct result, it will always return true.
9189 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
9190   assert(!LVal.Designator.Invalid);
9191 
9192   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
9193     const RecordDecl *Parent = FD->getParent();
9194     Invalid = Parent->isInvalidDecl();
9195     if (Invalid || Parent->isUnion())
9196       return true;
9197     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
9198     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
9199   };
9200 
9201   auto &Base = LVal.getLValueBase();
9202   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
9203     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
9204       bool Invalid;
9205       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9206         return Invalid;
9207     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
9208       for (auto *FD : IFD->chain()) {
9209         bool Invalid;
9210         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
9211           return Invalid;
9212       }
9213     }
9214   }
9215 
9216   unsigned I = 0;
9217   QualType BaseType = getType(Base);
9218   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
9219     // If we don't know the array bound, conservatively assume we're looking at
9220     // the final array element.
9221     ++I;
9222     if (BaseType->isIncompleteArrayType())
9223       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
9224     else
9225       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
9226   }
9227 
9228   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
9229     const auto &Entry = LVal.Designator.Entries[I];
9230     if (BaseType->isArrayType()) {
9231       // Because __builtin_object_size treats arrays as objects, we can ignore
9232       // the index iff this is the last array in the Designator.
9233       if (I + 1 == E)
9234         return true;
9235       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
9236       uint64_t Index = Entry.getAsArrayIndex();
9237       if (Index + 1 != CAT->getSize())
9238         return false;
9239       BaseType = CAT->getElementType();
9240     } else if (BaseType->isAnyComplexType()) {
9241       const auto *CT = BaseType->castAs<ComplexType>();
9242       uint64_t Index = Entry.getAsArrayIndex();
9243       if (Index != 1)
9244         return false;
9245       BaseType = CT->getElementType();
9246     } else if (auto *FD = getAsField(Entry)) {
9247       bool Invalid;
9248       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
9249         return Invalid;
9250       BaseType = FD->getType();
9251     } else {
9252       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
9253       return false;
9254     }
9255   }
9256   return true;
9257 }
9258 
9259 /// Tests to see if the LValue has a user-specified designator (that isn't
9260 /// necessarily valid). Note that this always returns 'true' if the LValue has
9261 /// an unsized array as its first designator entry, because there's currently no
9262 /// way to tell if the user typed *foo or foo[0].
9263 static bool refersToCompleteObject(const LValue &LVal) {
9264   if (LVal.Designator.Invalid)
9265     return false;
9266 
9267   if (!LVal.Designator.Entries.empty())
9268     return LVal.Designator.isMostDerivedAnUnsizedArray();
9269 
9270   if (!LVal.InvalidBase)
9271     return true;
9272 
9273   // If `E` is a MemberExpr, then the first part of the designator is hiding in
9274   // the LValueBase.
9275   const auto *E = LVal.Base.dyn_cast<const Expr *>();
9276   return !E || !isa<MemberExpr>(E);
9277 }
9278 
9279 /// Attempts to detect a user writing into a piece of memory that's impossible
9280 /// to figure out the size of by just using types.
9281 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
9282   const SubobjectDesignator &Designator = LVal.Designator;
9283   // Notes:
9284   // - Users can only write off of the end when we have an invalid base. Invalid
9285   //   bases imply we don't know where the memory came from.
9286   // - We used to be a bit more aggressive here; we'd only be conservative if
9287   //   the array at the end was flexible, or if it had 0 or 1 elements. This
9288   //   broke some common standard library extensions (PR30346), but was
9289   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
9290   //   with some sort of whitelist. OTOH, it seems that GCC is always
9291   //   conservative with the last element in structs (if it's an array), so our
9292   //   current behavior is more compatible than a whitelisting approach would
9293   //   be.
9294   return LVal.InvalidBase &&
9295          Designator.Entries.size() == Designator.MostDerivedPathLength &&
9296          Designator.MostDerivedIsArrayElement &&
9297          isDesignatorAtObjectEnd(Ctx, LVal);
9298 }
9299 
9300 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
9301 /// Fails if the conversion would cause loss of precision.
9302 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
9303                                             CharUnits &Result) {
9304   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
9305   if (Int.ugt(CharUnitsMax))
9306     return false;
9307   Result = CharUnits::fromQuantity(Int.getZExtValue());
9308   return true;
9309 }
9310 
9311 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
9312 /// determine how many bytes exist from the beginning of the object to either
9313 /// the end of the current subobject, or the end of the object itself, depending
9314 /// on what the LValue looks like + the value of Type.
9315 ///
9316 /// If this returns false, the value of Result is undefined.
9317 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
9318                                unsigned Type, const LValue &LVal,
9319                                CharUnits &EndOffset) {
9320   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
9321 
9322   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
9323     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
9324       return false;
9325     return HandleSizeof(Info, ExprLoc, Ty, Result);
9326   };
9327 
9328   // We want to evaluate the size of the entire object. This is a valid fallback
9329   // for when Type=1 and the designator is invalid, because we're asked for an
9330   // upper-bound.
9331   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
9332     // Type=3 wants a lower bound, so we can't fall back to this.
9333     if (Type == 3 && !DetermineForCompleteObject)
9334       return false;
9335 
9336     llvm::APInt APEndOffset;
9337     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9338         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9339       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9340 
9341     if (LVal.InvalidBase)
9342       return false;
9343 
9344     QualType BaseTy = getObjectType(LVal.getLValueBase());
9345     return CheckedHandleSizeof(BaseTy, EndOffset);
9346   }
9347 
9348   // We want to evaluate the size of a subobject.
9349   const SubobjectDesignator &Designator = LVal.Designator;
9350 
9351   // The following is a moderately common idiom in C:
9352   //
9353   // struct Foo { int a; char c[1]; };
9354   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
9355   // strcpy(&F->c[0], Bar);
9356   //
9357   // In order to not break too much legacy code, we need to support it.
9358   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
9359     // If we can resolve this to an alloc_size call, we can hand that back,
9360     // because we know for certain how many bytes there are to write to.
9361     llvm::APInt APEndOffset;
9362     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
9363         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
9364       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
9365 
9366     // If we cannot determine the size of the initial allocation, then we can't
9367     // given an accurate upper-bound. However, we are still able to give
9368     // conservative lower-bounds for Type=3.
9369     if (Type == 1)
9370       return false;
9371   }
9372 
9373   CharUnits BytesPerElem;
9374   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
9375     return false;
9376 
9377   // According to the GCC documentation, we want the size of the subobject
9378   // denoted by the pointer. But that's not quite right -- what we actually
9379   // want is the size of the immediately-enclosing array, if there is one.
9380   int64_t ElemsRemaining;
9381   if (Designator.MostDerivedIsArrayElement &&
9382       Designator.Entries.size() == Designator.MostDerivedPathLength) {
9383     uint64_t ArraySize = Designator.getMostDerivedArraySize();
9384     uint64_t ArrayIndex = Designator.Entries.back().getAsArrayIndex();
9385     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
9386   } else {
9387     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
9388   }
9389 
9390   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
9391   return true;
9392 }
9393 
9394 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
9395 /// returns true and stores the result in @p Size.
9396 ///
9397 /// If @p WasError is non-null, this will report whether the failure to evaluate
9398 /// is to be treated as an Error in IntExprEvaluator.
9399 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
9400                                          EvalInfo &Info, uint64_t &Size) {
9401   // Determine the denoted object.
9402   LValue LVal;
9403   {
9404     // The operand of __builtin_object_size is never evaluated for side-effects.
9405     // If there are any, but we can determine the pointed-to object anyway, then
9406     // ignore the side-effects.
9407     SpeculativeEvaluationRAII SpeculativeEval(Info);
9408     IgnoreSideEffectsRAII Fold(Info);
9409 
9410     if (E->isGLValue()) {
9411       // It's possible for us to be given GLValues if we're called via
9412       // Expr::tryEvaluateObjectSize.
9413       APValue RVal;
9414       if (!EvaluateAsRValue(Info, E, RVal))
9415         return false;
9416       LVal.setFrom(Info.Ctx, RVal);
9417     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
9418                                 /*InvalidBaseOK=*/true))
9419       return false;
9420   }
9421 
9422   // If we point to before the start of the object, there are no accessible
9423   // bytes.
9424   if (LVal.getLValueOffset().isNegative()) {
9425     Size = 0;
9426     return true;
9427   }
9428 
9429   CharUnits EndOffset;
9430   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
9431     return false;
9432 
9433   // If we've fallen outside of the end offset, just pretend there's nothing to
9434   // write to/read from.
9435   if (EndOffset <= LVal.getLValueOffset())
9436     Size = 0;
9437   else
9438     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
9439   return true;
9440 }
9441 
9442 bool IntExprEvaluator::VisitConstantExpr(const ConstantExpr *E) {
9443   llvm::SaveAndRestore<bool> InConstantContext(Info.InConstantContext, true);
9444   if (E->getResultAPValueKind() != APValue::None)
9445     return Success(E->getAPValueResult(), E);
9446   return ExprEvaluatorBaseTy::VisitConstantExpr(E);
9447 }
9448 
9449 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
9450   if (unsigned BuiltinOp = E->getBuiltinCallee())
9451     return VisitBuiltinCallExpr(E, BuiltinOp);
9452 
9453   return ExprEvaluatorBaseTy::VisitCallExpr(E);
9454 }
9455 
9456 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
9457                                             unsigned BuiltinOp) {
9458   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
9459   default:
9460     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9461 
9462   case Builtin::BI__builtin_dynamic_object_size:
9463   case Builtin::BI__builtin_object_size: {
9464     // The type was checked when we built the expression.
9465     unsigned Type =
9466         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9467     assert(Type <= 3 && "unexpected type");
9468 
9469     uint64_t Size;
9470     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
9471       return Success(Size, E);
9472 
9473     if (E->getArg(0)->HasSideEffects(Info.Ctx))
9474       return Success((Type & 2) ? 0 : -1, E);
9475 
9476     // Expression had no side effects, but we couldn't statically determine the
9477     // size of the referenced object.
9478     switch (Info.EvalMode) {
9479     case EvalInfo::EM_ConstantExpression:
9480     case EvalInfo::EM_ConstantFold:
9481     case EvalInfo::EM_IgnoreSideEffects:
9482       // Leave it to IR generation.
9483       return Error(E);
9484     case EvalInfo::EM_ConstantExpressionUnevaluated:
9485       // Reduce it to a constant now.
9486       return Success((Type & 2) ? 0 : -1, E);
9487     }
9488 
9489     llvm_unreachable("unexpected EvalMode");
9490   }
9491 
9492   case Builtin::BI__builtin_os_log_format_buffer_size: {
9493     analyze_os_log::OSLogBufferLayout Layout;
9494     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
9495     return Success(Layout.size().getQuantity(), E);
9496   }
9497 
9498   case Builtin::BI__builtin_bswap16:
9499   case Builtin::BI__builtin_bswap32:
9500   case Builtin::BI__builtin_bswap64: {
9501     APSInt Val;
9502     if (!EvaluateInteger(E->getArg(0), Val, Info))
9503       return false;
9504 
9505     return Success(Val.byteSwap(), E);
9506   }
9507 
9508   case Builtin::BI__builtin_classify_type:
9509     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
9510 
9511   case Builtin::BI__builtin_clrsb:
9512   case Builtin::BI__builtin_clrsbl:
9513   case Builtin::BI__builtin_clrsbll: {
9514     APSInt Val;
9515     if (!EvaluateInteger(E->getArg(0), Val, Info))
9516       return false;
9517 
9518     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
9519   }
9520 
9521   case Builtin::BI__builtin_clz:
9522   case Builtin::BI__builtin_clzl:
9523   case Builtin::BI__builtin_clzll:
9524   case Builtin::BI__builtin_clzs: {
9525     APSInt Val;
9526     if (!EvaluateInteger(E->getArg(0), Val, Info))
9527       return false;
9528     if (!Val)
9529       return Error(E);
9530 
9531     return Success(Val.countLeadingZeros(), E);
9532   }
9533 
9534   case Builtin::BI__builtin_constant_p: {
9535     const Expr *Arg = E->getArg(0);
9536     if (EvaluateBuiltinConstantP(Info, Arg))
9537       return Success(true, E);
9538     if (Info.InConstantContext || Arg->HasSideEffects(Info.Ctx)) {
9539       // Outside a constant context, eagerly evaluate to false in the presence
9540       // of side-effects in order to avoid -Wunsequenced false-positives in
9541       // a branch on __builtin_constant_p(expr).
9542       return Success(false, E);
9543     }
9544     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
9545     return false;
9546   }
9547 
9548   case Builtin::BI__builtin_is_constant_evaluated:
9549     return Success(Info.InConstantContext, E);
9550 
9551   case Builtin::BI__builtin_ctz:
9552   case Builtin::BI__builtin_ctzl:
9553   case Builtin::BI__builtin_ctzll:
9554   case Builtin::BI__builtin_ctzs: {
9555     APSInt Val;
9556     if (!EvaluateInteger(E->getArg(0), Val, Info))
9557       return false;
9558     if (!Val)
9559       return Error(E);
9560 
9561     return Success(Val.countTrailingZeros(), E);
9562   }
9563 
9564   case Builtin::BI__builtin_eh_return_data_regno: {
9565     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
9566     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
9567     return Success(Operand, E);
9568   }
9569 
9570   case Builtin::BI__builtin_expect:
9571     return Visit(E->getArg(0));
9572 
9573   case Builtin::BI__builtin_ffs:
9574   case Builtin::BI__builtin_ffsl:
9575   case Builtin::BI__builtin_ffsll: {
9576     APSInt Val;
9577     if (!EvaluateInteger(E->getArg(0), Val, Info))
9578       return false;
9579 
9580     unsigned N = Val.countTrailingZeros();
9581     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
9582   }
9583 
9584   case Builtin::BI__builtin_fpclassify: {
9585     APFloat Val(0.0);
9586     if (!EvaluateFloat(E->getArg(5), Val, Info))
9587       return false;
9588     unsigned Arg;
9589     switch (Val.getCategory()) {
9590     case APFloat::fcNaN: Arg = 0; break;
9591     case APFloat::fcInfinity: Arg = 1; break;
9592     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
9593     case APFloat::fcZero: Arg = 4; break;
9594     }
9595     return Visit(E->getArg(Arg));
9596   }
9597 
9598   case Builtin::BI__builtin_isinf_sign: {
9599     APFloat Val(0.0);
9600     return EvaluateFloat(E->getArg(0), Val, Info) &&
9601            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
9602   }
9603 
9604   case Builtin::BI__builtin_isinf: {
9605     APFloat Val(0.0);
9606     return EvaluateFloat(E->getArg(0), Val, Info) &&
9607            Success(Val.isInfinity() ? 1 : 0, E);
9608   }
9609 
9610   case Builtin::BI__builtin_isfinite: {
9611     APFloat Val(0.0);
9612     return EvaluateFloat(E->getArg(0), Val, Info) &&
9613            Success(Val.isFinite() ? 1 : 0, E);
9614   }
9615 
9616   case Builtin::BI__builtin_isnan: {
9617     APFloat Val(0.0);
9618     return EvaluateFloat(E->getArg(0), Val, Info) &&
9619            Success(Val.isNaN() ? 1 : 0, E);
9620   }
9621 
9622   case Builtin::BI__builtin_isnormal: {
9623     APFloat Val(0.0);
9624     return EvaluateFloat(E->getArg(0), Val, Info) &&
9625            Success(Val.isNormal() ? 1 : 0, E);
9626   }
9627 
9628   case Builtin::BI__builtin_parity:
9629   case Builtin::BI__builtin_parityl:
9630   case Builtin::BI__builtin_parityll: {
9631     APSInt Val;
9632     if (!EvaluateInteger(E->getArg(0), Val, Info))
9633       return false;
9634 
9635     return Success(Val.countPopulation() % 2, E);
9636   }
9637 
9638   case Builtin::BI__builtin_popcount:
9639   case Builtin::BI__builtin_popcountl:
9640   case Builtin::BI__builtin_popcountll: {
9641     APSInt Val;
9642     if (!EvaluateInteger(E->getArg(0), Val, Info))
9643       return false;
9644 
9645     return Success(Val.countPopulation(), E);
9646   }
9647 
9648   case Builtin::BIstrlen:
9649   case Builtin::BIwcslen:
9650     // A call to strlen is not a constant expression.
9651     if (Info.getLangOpts().CPlusPlus11)
9652       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9653         << /*isConstexpr*/0 << /*isConstructor*/0
9654         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9655     else
9656       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9657     LLVM_FALLTHROUGH;
9658   case Builtin::BI__builtin_strlen:
9659   case Builtin::BI__builtin_wcslen: {
9660     // As an extension, we support __builtin_strlen() as a constant expression,
9661     // and support folding strlen() to a constant.
9662     LValue String;
9663     if (!EvaluatePointer(E->getArg(0), String, Info))
9664       return false;
9665 
9666     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
9667 
9668     // Fast path: if it's a string literal, search the string value.
9669     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
9670             String.getLValueBase().dyn_cast<const Expr *>())) {
9671       // The string literal may have embedded null characters. Find the first
9672       // one and truncate there.
9673       StringRef Str = S->getBytes();
9674       int64_t Off = String.Offset.getQuantity();
9675       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
9676           S->getCharByteWidth() == 1 &&
9677           // FIXME: Add fast-path for wchar_t too.
9678           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
9679         Str = Str.substr(Off);
9680 
9681         StringRef::size_type Pos = Str.find(0);
9682         if (Pos != StringRef::npos)
9683           Str = Str.substr(0, Pos);
9684 
9685         return Success(Str.size(), E);
9686       }
9687 
9688       // Fall through to slow path to issue appropriate diagnostic.
9689     }
9690 
9691     // Slow path: scan the bytes of the string looking for the terminating 0.
9692     for (uint64_t Strlen = 0; /**/; ++Strlen) {
9693       APValue Char;
9694       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
9695           !Char.isInt())
9696         return false;
9697       if (!Char.getInt())
9698         return Success(Strlen, E);
9699       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
9700         return false;
9701     }
9702   }
9703 
9704   case Builtin::BIstrcmp:
9705   case Builtin::BIwcscmp:
9706   case Builtin::BIstrncmp:
9707   case Builtin::BIwcsncmp:
9708   case Builtin::BImemcmp:
9709   case Builtin::BIbcmp:
9710   case Builtin::BIwmemcmp:
9711     // A call to strlen is not a constant expression.
9712     if (Info.getLangOpts().CPlusPlus11)
9713       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
9714         << /*isConstexpr*/0 << /*isConstructor*/0
9715         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
9716     else
9717       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
9718     LLVM_FALLTHROUGH;
9719   case Builtin::BI__builtin_strcmp:
9720   case Builtin::BI__builtin_wcscmp:
9721   case Builtin::BI__builtin_strncmp:
9722   case Builtin::BI__builtin_wcsncmp:
9723   case Builtin::BI__builtin_memcmp:
9724   case Builtin::BI__builtin_bcmp:
9725   case Builtin::BI__builtin_wmemcmp: {
9726     LValue String1, String2;
9727     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
9728         !EvaluatePointer(E->getArg(1), String2, Info))
9729       return false;
9730 
9731     uint64_t MaxLength = uint64_t(-1);
9732     if (BuiltinOp != Builtin::BIstrcmp &&
9733         BuiltinOp != Builtin::BIwcscmp &&
9734         BuiltinOp != Builtin::BI__builtin_strcmp &&
9735         BuiltinOp != Builtin::BI__builtin_wcscmp) {
9736       APSInt N;
9737       if (!EvaluateInteger(E->getArg(2), N, Info))
9738         return false;
9739       MaxLength = N.getExtValue();
9740     }
9741 
9742     // Empty substrings compare equal by definition.
9743     if (MaxLength == 0u)
9744       return Success(0, E);
9745 
9746     if (!String1.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9747         !String2.checkNullPointerForFoldAccess(Info, E, AK_Read) ||
9748         String1.Designator.Invalid || String2.Designator.Invalid)
9749       return false;
9750 
9751     QualType CharTy1 = String1.Designator.getType(Info.Ctx);
9752     QualType CharTy2 = String2.Designator.getType(Info.Ctx);
9753 
9754     bool IsRawByte = BuiltinOp == Builtin::BImemcmp ||
9755                      BuiltinOp == Builtin::BIbcmp ||
9756                      BuiltinOp == Builtin::BI__builtin_memcmp ||
9757                      BuiltinOp == Builtin::BI__builtin_bcmp;
9758 
9759     assert(IsRawByte ||
9760            (Info.Ctx.hasSameUnqualifiedType(
9761                 CharTy1, E->getArg(0)->getType()->getPointeeType()) &&
9762             Info.Ctx.hasSameUnqualifiedType(CharTy1, CharTy2)));
9763 
9764     const auto &ReadCurElems = [&](APValue &Char1, APValue &Char2) {
9765       return handleLValueToRValueConversion(Info, E, CharTy1, String1, Char1) &&
9766              handleLValueToRValueConversion(Info, E, CharTy2, String2, Char2) &&
9767              Char1.isInt() && Char2.isInt();
9768     };
9769     const auto &AdvanceElems = [&] {
9770       return HandleLValueArrayAdjustment(Info, E, String1, CharTy1, 1) &&
9771              HandleLValueArrayAdjustment(Info, E, String2, CharTy2, 1);
9772     };
9773 
9774     if (IsRawByte) {
9775       uint64_t BytesRemaining = MaxLength;
9776       // Pointers to const void may point to objects of incomplete type.
9777       if (CharTy1->isIncompleteType()) {
9778         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy1;
9779         return false;
9780       }
9781       if (CharTy2->isIncompleteType()) {
9782         Info.FFDiag(E, diag::note_constexpr_ltor_incomplete_type) << CharTy2;
9783         return false;
9784       }
9785       uint64_t CharTy1Width{Info.Ctx.getTypeSize(CharTy1)};
9786       CharUnits CharTy1Size = Info.Ctx.toCharUnitsFromBits(CharTy1Width);
9787       // Give up on comparing between elements with disparate widths.
9788       if (CharTy1Size != Info.Ctx.getTypeSizeInChars(CharTy2))
9789         return false;
9790       uint64_t BytesPerElement = CharTy1Size.getQuantity();
9791       assert(BytesRemaining && "BytesRemaining should not be zero: the "
9792                                "following loop considers at least one element");
9793       while (true) {
9794         APValue Char1, Char2;
9795         if (!ReadCurElems(Char1, Char2))
9796           return false;
9797         // We have compatible in-memory widths, but a possible type and
9798         // (for `bool`) internal representation mismatch.
9799         // Assuming two's complement representation, including 0 for `false` and
9800         // 1 for `true`, we can check an appropriate number of elements for
9801         // equality even if they are not byte-sized.
9802         APSInt Char1InMem = Char1.getInt().extOrTrunc(CharTy1Width);
9803         APSInt Char2InMem = Char2.getInt().extOrTrunc(CharTy1Width);
9804         if (Char1InMem.ne(Char2InMem)) {
9805           // If the elements are byte-sized, then we can produce a three-way
9806           // comparison result in a straightforward manner.
9807           if (BytesPerElement == 1u) {
9808             // memcmp always compares unsigned chars.
9809             return Success(Char1InMem.ult(Char2InMem) ? -1 : 1, E);
9810           }
9811           // The result is byte-order sensitive, and we have multibyte elements.
9812           // FIXME: We can compare the remaining bytes in the correct order.
9813           return false;
9814         }
9815         if (!AdvanceElems())
9816           return false;
9817         if (BytesRemaining <= BytesPerElement)
9818           break;
9819         BytesRemaining -= BytesPerElement;
9820       }
9821       // Enough elements are equal to account for the memcmp limit.
9822       return Success(0, E);
9823     }
9824 
9825     bool StopAtNull =
9826         (BuiltinOp != Builtin::BImemcmp && BuiltinOp != Builtin::BIbcmp &&
9827          BuiltinOp != Builtin::BIwmemcmp &&
9828          BuiltinOp != Builtin::BI__builtin_memcmp &&
9829          BuiltinOp != Builtin::BI__builtin_bcmp &&
9830          BuiltinOp != Builtin::BI__builtin_wmemcmp);
9831     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
9832                   BuiltinOp == Builtin::BIwcsncmp ||
9833                   BuiltinOp == Builtin::BIwmemcmp ||
9834                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
9835                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
9836                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
9837 
9838     for (; MaxLength; --MaxLength) {
9839       APValue Char1, Char2;
9840       if (!ReadCurElems(Char1, Char2))
9841         return false;
9842       if (Char1.getInt() != Char2.getInt()) {
9843         if (IsWide) // wmemcmp compares with wchar_t signedness.
9844           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
9845         // memcmp always compares unsigned chars.
9846         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
9847       }
9848       if (StopAtNull && !Char1.getInt())
9849         return Success(0, E);
9850       assert(!(StopAtNull && !Char2.getInt()));
9851       if (!AdvanceElems())
9852         return false;
9853     }
9854     // We hit the strncmp / memcmp limit.
9855     return Success(0, E);
9856   }
9857 
9858   case Builtin::BI__atomic_always_lock_free:
9859   case Builtin::BI__atomic_is_lock_free:
9860   case Builtin::BI__c11_atomic_is_lock_free: {
9861     APSInt SizeVal;
9862     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
9863       return false;
9864 
9865     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
9866     // of two less than the maximum inline atomic width, we know it is
9867     // lock-free.  If the size isn't a power of two, or greater than the
9868     // maximum alignment where we promote atomics, we know it is not lock-free
9869     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
9870     // the answer can only be determined at runtime; for example, 16-byte
9871     // atomics have lock-free implementations on some, but not all,
9872     // x86-64 processors.
9873 
9874     // Check power-of-two.
9875     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
9876     if (Size.isPowerOfTwo()) {
9877       // Check against inlining width.
9878       unsigned InlineWidthBits =
9879           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
9880       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
9881         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
9882             Size == CharUnits::One() ||
9883             E->getArg(1)->isNullPointerConstant(Info.Ctx,
9884                                                 Expr::NPC_NeverValueDependent))
9885           // OK, we will inline appropriately-aligned operations of this size,
9886           // and _Atomic(T) is appropriately-aligned.
9887           return Success(1, E);
9888 
9889         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
9890           castAs<PointerType>()->getPointeeType();
9891         if (!PointeeType->isIncompleteType() &&
9892             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
9893           // OK, we will inline operations on this object.
9894           return Success(1, E);
9895         }
9896       }
9897     }
9898 
9899     // Avoid emiting call for runtime decision on PowerPC 32-bit
9900     // The lock free possibilities on this platform are covered by the lines
9901     // above and we know in advance other cases require lock
9902     if (Info.Ctx.getTargetInfo().getTriple().getArch() == llvm::Triple::ppc) {
9903         return Success(0, E);
9904     }
9905 
9906     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
9907         Success(0, E) : Error(E);
9908   }
9909   case Builtin::BIomp_is_initial_device:
9910     // We can decide statically which value the runtime would return if called.
9911     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
9912   case Builtin::BI__builtin_add_overflow:
9913   case Builtin::BI__builtin_sub_overflow:
9914   case Builtin::BI__builtin_mul_overflow:
9915   case Builtin::BI__builtin_sadd_overflow:
9916   case Builtin::BI__builtin_uadd_overflow:
9917   case Builtin::BI__builtin_uaddl_overflow:
9918   case Builtin::BI__builtin_uaddll_overflow:
9919   case Builtin::BI__builtin_usub_overflow:
9920   case Builtin::BI__builtin_usubl_overflow:
9921   case Builtin::BI__builtin_usubll_overflow:
9922   case Builtin::BI__builtin_umul_overflow:
9923   case Builtin::BI__builtin_umull_overflow:
9924   case Builtin::BI__builtin_umulll_overflow:
9925   case Builtin::BI__builtin_saddl_overflow:
9926   case Builtin::BI__builtin_saddll_overflow:
9927   case Builtin::BI__builtin_ssub_overflow:
9928   case Builtin::BI__builtin_ssubl_overflow:
9929   case Builtin::BI__builtin_ssubll_overflow:
9930   case Builtin::BI__builtin_smul_overflow:
9931   case Builtin::BI__builtin_smull_overflow:
9932   case Builtin::BI__builtin_smulll_overflow: {
9933     LValue ResultLValue;
9934     APSInt LHS, RHS;
9935 
9936     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
9937     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
9938         !EvaluateInteger(E->getArg(1), RHS, Info) ||
9939         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
9940       return false;
9941 
9942     APSInt Result;
9943     bool DidOverflow = false;
9944 
9945     // If the types don't have to match, enlarge all 3 to the largest of them.
9946     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
9947         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
9948         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
9949       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
9950                       ResultType->isSignedIntegerOrEnumerationType();
9951       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
9952                       ResultType->isSignedIntegerOrEnumerationType();
9953       uint64_t LHSSize = LHS.getBitWidth();
9954       uint64_t RHSSize = RHS.getBitWidth();
9955       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
9956       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
9957 
9958       // Add an additional bit if the signedness isn't uniformly agreed to. We
9959       // could do this ONLY if there is a signed and an unsigned that both have
9960       // MaxBits, but the code to check that is pretty nasty.  The issue will be
9961       // caught in the shrink-to-result later anyway.
9962       if (IsSigned && !AllSigned)
9963         ++MaxBits;
9964 
9965       LHS = APSInt(LHS.extOrTrunc(MaxBits), !IsSigned);
9966       RHS = APSInt(RHS.extOrTrunc(MaxBits), !IsSigned);
9967       Result = APSInt(MaxBits, !IsSigned);
9968     }
9969 
9970     // Find largest int.
9971     switch (BuiltinOp) {
9972     default:
9973       llvm_unreachable("Invalid value for BuiltinOp");
9974     case Builtin::BI__builtin_add_overflow:
9975     case Builtin::BI__builtin_sadd_overflow:
9976     case Builtin::BI__builtin_saddl_overflow:
9977     case Builtin::BI__builtin_saddll_overflow:
9978     case Builtin::BI__builtin_uadd_overflow:
9979     case Builtin::BI__builtin_uaddl_overflow:
9980     case Builtin::BI__builtin_uaddll_overflow:
9981       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
9982                               : LHS.uadd_ov(RHS, DidOverflow);
9983       break;
9984     case Builtin::BI__builtin_sub_overflow:
9985     case Builtin::BI__builtin_ssub_overflow:
9986     case Builtin::BI__builtin_ssubl_overflow:
9987     case Builtin::BI__builtin_ssubll_overflow:
9988     case Builtin::BI__builtin_usub_overflow:
9989     case Builtin::BI__builtin_usubl_overflow:
9990     case Builtin::BI__builtin_usubll_overflow:
9991       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
9992                               : LHS.usub_ov(RHS, DidOverflow);
9993       break;
9994     case Builtin::BI__builtin_mul_overflow:
9995     case Builtin::BI__builtin_smul_overflow:
9996     case Builtin::BI__builtin_smull_overflow:
9997     case Builtin::BI__builtin_smulll_overflow:
9998     case Builtin::BI__builtin_umul_overflow:
9999     case Builtin::BI__builtin_umull_overflow:
10000     case Builtin::BI__builtin_umulll_overflow:
10001       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
10002                               : LHS.umul_ov(RHS, DidOverflow);
10003       break;
10004     }
10005 
10006     // In the case where multiple sizes are allowed, truncate and see if
10007     // the values are the same.
10008     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
10009         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
10010         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
10011       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
10012       // since it will give us the behavior of a TruncOrSelf in the case where
10013       // its parameter <= its size.  We previously set Result to be at least the
10014       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
10015       // will work exactly like TruncOrSelf.
10016       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
10017       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
10018 
10019       if (!APSInt::isSameValue(Temp, Result))
10020         DidOverflow = true;
10021       Result = Temp;
10022     }
10023 
10024     APValue APV{Result};
10025     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
10026       return false;
10027     return Success(DidOverflow, E);
10028   }
10029   }
10030 }
10031 
10032 /// Determine whether this is a pointer past the end of the complete
10033 /// object referred to by the lvalue.
10034 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
10035                                             const LValue &LV) {
10036   // A null pointer can be viewed as being "past the end" but we don't
10037   // choose to look at it that way here.
10038   if (!LV.getLValueBase())
10039     return false;
10040 
10041   // If the designator is valid and refers to a subobject, we're not pointing
10042   // past the end.
10043   if (!LV.getLValueDesignator().Invalid &&
10044       !LV.getLValueDesignator().isOnePastTheEnd())
10045     return false;
10046 
10047   // A pointer to an incomplete type might be past-the-end if the type's size is
10048   // zero.  We cannot tell because the type is incomplete.
10049   QualType Ty = getType(LV.getLValueBase());
10050   if (Ty->isIncompleteType())
10051     return true;
10052 
10053   // We're a past-the-end pointer if we point to the byte after the object,
10054   // no matter what our type or path is.
10055   auto Size = Ctx.getTypeSizeInChars(Ty);
10056   return LV.getLValueOffset() == Size;
10057 }
10058 
10059 namespace {
10060 
10061 /// Data recursive integer evaluator of certain binary operators.
10062 ///
10063 /// We use a data recursive algorithm for binary operators so that we are able
10064 /// to handle extreme cases of chained binary operators without causing stack
10065 /// overflow.
10066 class DataRecursiveIntBinOpEvaluator {
10067   struct EvalResult {
10068     APValue Val;
10069     bool Failed;
10070 
10071     EvalResult() : Failed(false) { }
10072 
10073     void swap(EvalResult &RHS) {
10074       Val.swap(RHS.Val);
10075       Failed = RHS.Failed;
10076       RHS.Failed = false;
10077     }
10078   };
10079 
10080   struct Job {
10081     const Expr *E;
10082     EvalResult LHSResult; // meaningful only for binary operator expression.
10083     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
10084 
10085     Job() = default;
10086     Job(Job &&) = default;
10087 
10088     void startSpeculativeEval(EvalInfo &Info) {
10089       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
10090     }
10091 
10092   private:
10093     SpeculativeEvaluationRAII SpecEvalRAII;
10094   };
10095 
10096   SmallVector<Job, 16> Queue;
10097 
10098   IntExprEvaluator &IntEval;
10099   EvalInfo &Info;
10100   APValue &FinalResult;
10101 
10102 public:
10103   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
10104     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
10105 
10106   /// True if \param E is a binary operator that we are going to handle
10107   /// data recursively.
10108   /// We handle binary operators that are comma, logical, or that have operands
10109   /// with integral or enumeration type.
10110   static bool shouldEnqueue(const BinaryOperator *E) {
10111     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
10112            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
10113             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10114             E->getRHS()->getType()->isIntegralOrEnumerationType());
10115   }
10116 
10117   bool Traverse(const BinaryOperator *E) {
10118     enqueue(E);
10119     EvalResult PrevResult;
10120     while (!Queue.empty())
10121       process(PrevResult);
10122 
10123     if (PrevResult.Failed) return false;
10124 
10125     FinalResult.swap(PrevResult.Val);
10126     return true;
10127   }
10128 
10129 private:
10130   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
10131     return IntEval.Success(Value, E, Result);
10132   }
10133   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
10134     return IntEval.Success(Value, E, Result);
10135   }
10136   bool Error(const Expr *E) {
10137     return IntEval.Error(E);
10138   }
10139   bool Error(const Expr *E, diag::kind D) {
10140     return IntEval.Error(E, D);
10141   }
10142 
10143   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
10144     return Info.CCEDiag(E, D);
10145   }
10146 
10147   // Returns true if visiting the RHS is necessary, false otherwise.
10148   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10149                          bool &SuppressRHSDiags);
10150 
10151   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10152                   const BinaryOperator *E, APValue &Result);
10153 
10154   void EvaluateExpr(const Expr *E, EvalResult &Result) {
10155     Result.Failed = !Evaluate(Result.Val, Info, E);
10156     if (Result.Failed)
10157       Result.Val = APValue();
10158   }
10159 
10160   void process(EvalResult &Result);
10161 
10162   void enqueue(const Expr *E) {
10163     E = E->IgnoreParens();
10164     Queue.resize(Queue.size()+1);
10165     Queue.back().E = E;
10166     Queue.back().Kind = Job::AnyExprKind;
10167   }
10168 };
10169 
10170 }
10171 
10172 bool DataRecursiveIntBinOpEvaluator::
10173        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
10174                          bool &SuppressRHSDiags) {
10175   if (E->getOpcode() == BO_Comma) {
10176     // Ignore LHS but note if we could not evaluate it.
10177     if (LHSResult.Failed)
10178       return Info.noteSideEffect();
10179     return true;
10180   }
10181 
10182   if (E->isLogicalOp()) {
10183     bool LHSAsBool;
10184     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
10185       // We were able to evaluate the LHS, see if we can get away with not
10186       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
10187       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
10188         Success(LHSAsBool, E, LHSResult.Val);
10189         return false; // Ignore RHS
10190       }
10191     } else {
10192       LHSResult.Failed = true;
10193 
10194       // Since we weren't able to evaluate the left hand side, it
10195       // might have had side effects.
10196       if (!Info.noteSideEffect())
10197         return false;
10198 
10199       // We can't evaluate the LHS; however, sometimes the result
10200       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10201       // Don't ignore RHS and suppress diagnostics from this arm.
10202       SuppressRHSDiags = true;
10203     }
10204 
10205     return true;
10206   }
10207 
10208   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10209          E->getRHS()->getType()->isIntegralOrEnumerationType());
10210 
10211   if (LHSResult.Failed && !Info.noteFailure())
10212     return false; // Ignore RHS;
10213 
10214   return true;
10215 }
10216 
10217 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
10218                                     bool IsSub) {
10219   // Compute the new offset in the appropriate width, wrapping at 64 bits.
10220   // FIXME: When compiling for a 32-bit target, we should use 32-bit
10221   // offsets.
10222   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
10223   CharUnits &Offset = LVal.getLValueOffset();
10224   uint64_t Offset64 = Offset.getQuantity();
10225   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
10226   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
10227                                          : Offset64 + Index64);
10228 }
10229 
10230 bool DataRecursiveIntBinOpEvaluator::
10231        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
10232                   const BinaryOperator *E, APValue &Result) {
10233   if (E->getOpcode() == BO_Comma) {
10234     if (RHSResult.Failed)
10235       return false;
10236     Result = RHSResult.Val;
10237     return true;
10238   }
10239 
10240   if (E->isLogicalOp()) {
10241     bool lhsResult, rhsResult;
10242     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
10243     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
10244 
10245     if (LHSIsOK) {
10246       if (RHSIsOK) {
10247         if (E->getOpcode() == BO_LOr)
10248           return Success(lhsResult || rhsResult, E, Result);
10249         else
10250           return Success(lhsResult && rhsResult, E, Result);
10251       }
10252     } else {
10253       if (RHSIsOK) {
10254         // We can't evaluate the LHS; however, sometimes the result
10255         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
10256         if (rhsResult == (E->getOpcode() == BO_LOr))
10257           return Success(rhsResult, E, Result);
10258       }
10259     }
10260 
10261     return false;
10262   }
10263 
10264   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
10265          E->getRHS()->getType()->isIntegralOrEnumerationType());
10266 
10267   if (LHSResult.Failed || RHSResult.Failed)
10268     return false;
10269 
10270   const APValue &LHSVal = LHSResult.Val;
10271   const APValue &RHSVal = RHSResult.Val;
10272 
10273   // Handle cases like (unsigned long)&a + 4.
10274   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
10275     Result = LHSVal;
10276     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
10277     return true;
10278   }
10279 
10280   // Handle cases like 4 + (unsigned long)&a
10281   if (E->getOpcode() == BO_Add &&
10282       RHSVal.isLValue() && LHSVal.isInt()) {
10283     Result = RHSVal;
10284     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
10285     return true;
10286   }
10287 
10288   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
10289     // Handle (intptr_t)&&A - (intptr_t)&&B.
10290     if (!LHSVal.getLValueOffset().isZero() ||
10291         !RHSVal.getLValueOffset().isZero())
10292       return false;
10293     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
10294     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
10295     if (!LHSExpr || !RHSExpr)
10296       return false;
10297     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10298     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10299     if (!LHSAddrExpr || !RHSAddrExpr)
10300       return false;
10301     // Make sure both labels come from the same function.
10302     if (LHSAddrExpr->getLabel()->getDeclContext() !=
10303         RHSAddrExpr->getLabel()->getDeclContext())
10304       return false;
10305     Result = APValue(LHSAddrExpr, RHSAddrExpr);
10306     return true;
10307   }
10308 
10309   // All the remaining cases expect both operands to be an integer
10310   if (!LHSVal.isInt() || !RHSVal.isInt())
10311     return Error(E);
10312 
10313   // Set up the width and signedness manually, in case it can't be deduced
10314   // from the operation we're performing.
10315   // FIXME: Don't do this in the cases where we can deduce it.
10316   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
10317                E->getType()->isUnsignedIntegerOrEnumerationType());
10318   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
10319                          RHSVal.getInt(), Value))
10320     return false;
10321   return Success(Value, E, Result);
10322 }
10323 
10324 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
10325   Job &job = Queue.back();
10326 
10327   switch (job.Kind) {
10328     case Job::AnyExprKind: {
10329       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
10330         if (shouldEnqueue(Bop)) {
10331           job.Kind = Job::BinOpKind;
10332           enqueue(Bop->getLHS());
10333           return;
10334         }
10335       }
10336 
10337       EvaluateExpr(job.E, Result);
10338       Queue.pop_back();
10339       return;
10340     }
10341 
10342     case Job::BinOpKind: {
10343       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10344       bool SuppressRHSDiags = false;
10345       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
10346         Queue.pop_back();
10347         return;
10348       }
10349       if (SuppressRHSDiags)
10350         job.startSpeculativeEval(Info);
10351       job.LHSResult.swap(Result);
10352       job.Kind = Job::BinOpVisitedLHSKind;
10353       enqueue(Bop->getRHS());
10354       return;
10355     }
10356 
10357     case Job::BinOpVisitedLHSKind: {
10358       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
10359       EvalResult RHS;
10360       RHS.swap(Result);
10361       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
10362       Queue.pop_back();
10363       return;
10364     }
10365   }
10366 
10367   llvm_unreachable("Invalid Job::Kind!");
10368 }
10369 
10370 namespace {
10371 /// Used when we determine that we should fail, but can keep evaluating prior to
10372 /// noting that we had a failure.
10373 class DelayedNoteFailureRAII {
10374   EvalInfo &Info;
10375   bool NoteFailure;
10376 
10377 public:
10378   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
10379       : Info(Info), NoteFailure(NoteFailure) {}
10380   ~DelayedNoteFailureRAII() {
10381     if (NoteFailure) {
10382       bool ContinueAfterFailure = Info.noteFailure();
10383       (void)ContinueAfterFailure;
10384       assert(ContinueAfterFailure &&
10385              "Shouldn't have kept evaluating on failure.");
10386     }
10387   }
10388 };
10389 }
10390 
10391 template <class SuccessCB, class AfterCB>
10392 static bool
10393 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
10394                                  SuccessCB &&Success, AfterCB &&DoAfter) {
10395   assert(E->isComparisonOp() && "expected comparison operator");
10396   assert((E->getOpcode() == BO_Cmp ||
10397           E->getType()->isIntegralOrEnumerationType()) &&
10398          "unsupported binary expression evaluation");
10399   auto Error = [&](const Expr *E) {
10400     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10401     return false;
10402   };
10403 
10404   using CCR = ComparisonCategoryResult;
10405   bool IsRelational = E->isRelationalOp();
10406   bool IsEquality = E->isEqualityOp();
10407   if (E->getOpcode() == BO_Cmp) {
10408     const ComparisonCategoryInfo &CmpInfo =
10409         Info.Ctx.CompCategories.getInfoForType(E->getType());
10410     IsRelational = CmpInfo.isOrdered();
10411     IsEquality = CmpInfo.isEquality();
10412   }
10413 
10414   QualType LHSTy = E->getLHS()->getType();
10415   QualType RHSTy = E->getRHS()->getType();
10416 
10417   if (LHSTy->isIntegralOrEnumerationType() &&
10418       RHSTy->isIntegralOrEnumerationType()) {
10419     APSInt LHS, RHS;
10420     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
10421     if (!LHSOK && !Info.noteFailure())
10422       return false;
10423     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
10424       return false;
10425     if (LHS < RHS)
10426       return Success(CCR::Less, E);
10427     if (LHS > RHS)
10428       return Success(CCR::Greater, E);
10429     return Success(CCR::Equal, E);
10430   }
10431 
10432   if (LHSTy->isFixedPointType() || RHSTy->isFixedPointType()) {
10433     APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHSTy));
10434     APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHSTy));
10435 
10436     bool LHSOK = EvaluateFixedPointOrInteger(E->getLHS(), LHSFX, Info);
10437     if (!LHSOK && !Info.noteFailure())
10438       return false;
10439     if (!EvaluateFixedPointOrInteger(E->getRHS(), RHSFX, Info) || !LHSOK)
10440       return false;
10441     if (LHSFX < RHSFX)
10442       return Success(CCR::Less, E);
10443     if (LHSFX > RHSFX)
10444       return Success(CCR::Greater, E);
10445     return Success(CCR::Equal, E);
10446   }
10447 
10448   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
10449     ComplexValue LHS, RHS;
10450     bool LHSOK;
10451     if (E->isAssignmentOp()) {
10452       LValue LV;
10453       EvaluateLValue(E->getLHS(), LV, Info);
10454       LHSOK = false;
10455     } else if (LHSTy->isRealFloatingType()) {
10456       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
10457       if (LHSOK) {
10458         LHS.makeComplexFloat();
10459         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
10460       }
10461     } else {
10462       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
10463     }
10464     if (!LHSOK && !Info.noteFailure())
10465       return false;
10466 
10467     if (E->getRHS()->getType()->isRealFloatingType()) {
10468       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
10469         return false;
10470       RHS.makeComplexFloat();
10471       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
10472     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10473       return false;
10474 
10475     if (LHS.isComplexFloat()) {
10476       APFloat::cmpResult CR_r =
10477         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
10478       APFloat::cmpResult CR_i =
10479         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
10480       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
10481       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10482     } else {
10483       assert(IsEquality && "invalid complex comparison");
10484       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
10485                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
10486       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
10487     }
10488   }
10489 
10490   if (LHSTy->isRealFloatingType() &&
10491       RHSTy->isRealFloatingType()) {
10492     APFloat RHS(0.0), LHS(0.0);
10493 
10494     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
10495     if (!LHSOK && !Info.noteFailure())
10496       return false;
10497 
10498     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
10499       return false;
10500 
10501     assert(E->isComparisonOp() && "Invalid binary operator!");
10502     auto GetCmpRes = [&]() {
10503       switch (LHS.compare(RHS)) {
10504       case APFloat::cmpEqual:
10505         return CCR::Equal;
10506       case APFloat::cmpLessThan:
10507         return CCR::Less;
10508       case APFloat::cmpGreaterThan:
10509         return CCR::Greater;
10510       case APFloat::cmpUnordered:
10511         return CCR::Unordered;
10512       }
10513       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
10514     };
10515     return Success(GetCmpRes(), E);
10516   }
10517 
10518   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
10519     LValue LHSValue, RHSValue;
10520 
10521     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10522     if (!LHSOK && !Info.noteFailure())
10523       return false;
10524 
10525     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10526       return false;
10527 
10528     // Reject differing bases from the normal codepath; we special-case
10529     // comparisons to null.
10530     if (!HasSameBase(LHSValue, RHSValue)) {
10531       // Inequalities and subtractions between unrelated pointers have
10532       // unspecified or undefined behavior.
10533       if (!IsEquality)
10534         return Error(E);
10535       // A constant address may compare equal to the address of a symbol.
10536       // The one exception is that address of an object cannot compare equal
10537       // to a null pointer constant.
10538       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
10539           (!RHSValue.Base && !RHSValue.Offset.isZero()))
10540         return Error(E);
10541       // It's implementation-defined whether distinct literals will have
10542       // distinct addresses. In clang, the result of such a comparison is
10543       // unspecified, so it is not a constant expression. However, we do know
10544       // that the address of a literal will be non-null.
10545       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
10546           LHSValue.Base && RHSValue.Base)
10547         return Error(E);
10548       // We can't tell whether weak symbols will end up pointing to the same
10549       // object.
10550       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
10551         return Error(E);
10552       // We can't compare the address of the start of one object with the
10553       // past-the-end address of another object, per C++ DR1652.
10554       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
10555            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
10556           (RHSValue.Base && RHSValue.Offset.isZero() &&
10557            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
10558         return Error(E);
10559       // We can't tell whether an object is at the same address as another
10560       // zero sized object.
10561       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
10562           (LHSValue.Base && isZeroSized(RHSValue)))
10563         return Error(E);
10564       return Success(CCR::Nonequal, E);
10565     }
10566 
10567     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10568     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10569 
10570     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10571     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10572 
10573     // C++11 [expr.rel]p3:
10574     //   Pointers to void (after pointer conversions) can be compared, with a
10575     //   result defined as follows: If both pointers represent the same
10576     //   address or are both the null pointer value, the result is true if the
10577     //   operator is <= or >= and false otherwise; otherwise the result is
10578     //   unspecified.
10579     // We interpret this as applying to pointers to *cv* void.
10580     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
10581       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
10582 
10583     // C++11 [expr.rel]p2:
10584     // - If two pointers point to non-static data members of the same object,
10585     //   or to subobjects or array elements fo such members, recursively, the
10586     //   pointer to the later declared member compares greater provided the
10587     //   two members have the same access control and provided their class is
10588     //   not a union.
10589     //   [...]
10590     // - Otherwise pointer comparisons are unspecified.
10591     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
10592       bool WasArrayIndex;
10593       unsigned Mismatch = FindDesignatorMismatch(
10594           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
10595       // At the point where the designators diverge, the comparison has a
10596       // specified value if:
10597       //  - we are comparing array indices
10598       //  - we are comparing fields of a union, or fields with the same access
10599       // Otherwise, the result is unspecified and thus the comparison is not a
10600       // constant expression.
10601       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
10602           Mismatch < RHSDesignator.Entries.size()) {
10603         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
10604         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
10605         if (!LF && !RF)
10606           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
10607         else if (!LF)
10608           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10609               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
10610               << RF->getParent() << RF;
10611         else if (!RF)
10612           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
10613               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
10614               << LF->getParent() << LF;
10615         else if (!LF->getParent()->isUnion() &&
10616                  LF->getAccess() != RF->getAccess())
10617           Info.CCEDiag(E,
10618                        diag::note_constexpr_pointer_comparison_differing_access)
10619               << LF << LF->getAccess() << RF << RF->getAccess()
10620               << LF->getParent();
10621       }
10622     }
10623 
10624     // The comparison here must be unsigned, and performed with the same
10625     // width as the pointer.
10626     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
10627     uint64_t CompareLHS = LHSOffset.getQuantity();
10628     uint64_t CompareRHS = RHSOffset.getQuantity();
10629     assert(PtrSize <= 64 && "Unexpected pointer width");
10630     uint64_t Mask = ~0ULL >> (64 - PtrSize);
10631     CompareLHS &= Mask;
10632     CompareRHS &= Mask;
10633 
10634     // If there is a base and this is a relational operator, we can only
10635     // compare pointers within the object in question; otherwise, the result
10636     // depends on where the object is located in memory.
10637     if (!LHSValue.Base.isNull() && IsRelational) {
10638       QualType BaseTy = getType(LHSValue.Base);
10639       if (BaseTy->isIncompleteType())
10640         return Error(E);
10641       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
10642       uint64_t OffsetLimit = Size.getQuantity();
10643       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
10644         return Error(E);
10645     }
10646 
10647     if (CompareLHS < CompareRHS)
10648       return Success(CCR::Less, E);
10649     if (CompareLHS > CompareRHS)
10650       return Success(CCR::Greater, E);
10651     return Success(CCR::Equal, E);
10652   }
10653 
10654   if (LHSTy->isMemberPointerType()) {
10655     assert(IsEquality && "unexpected member pointer operation");
10656     assert(RHSTy->isMemberPointerType() && "invalid comparison");
10657 
10658     MemberPtr LHSValue, RHSValue;
10659 
10660     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
10661     if (!LHSOK && !Info.noteFailure())
10662       return false;
10663 
10664     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10665       return false;
10666 
10667     // C++11 [expr.eq]p2:
10668     //   If both operands are null, they compare equal. Otherwise if only one is
10669     //   null, they compare unequal.
10670     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
10671       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
10672       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10673     }
10674 
10675     //   Otherwise if either is a pointer to a virtual member function, the
10676     //   result is unspecified.
10677     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
10678       if (MD->isVirtual())
10679         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10680     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
10681       if (MD->isVirtual())
10682         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
10683 
10684     //   Otherwise they compare equal if and only if they would refer to the
10685     //   same member of the same most derived object or the same subobject if
10686     //   they were dereferenced with a hypothetical object of the associated
10687     //   class type.
10688     bool Equal = LHSValue == RHSValue;
10689     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
10690   }
10691 
10692   if (LHSTy->isNullPtrType()) {
10693     assert(E->isComparisonOp() && "unexpected nullptr operation");
10694     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
10695     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
10696     // are compared, the result is true of the operator is <=, >= or ==, and
10697     // false otherwise.
10698     return Success(CCR::Equal, E);
10699   }
10700 
10701   return DoAfter();
10702 }
10703 
10704 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
10705   if (!CheckLiteralType(Info, E))
10706     return false;
10707 
10708   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10709                        const BinaryOperator *E) {
10710     // Evaluation succeeded. Lookup the information for the comparison category
10711     // type and fetch the VarDecl for the result.
10712     const ComparisonCategoryInfo &CmpInfo =
10713         Info.Ctx.CompCategories.getInfoForType(E->getType());
10714     const VarDecl *VD =
10715         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
10716     // Check and evaluate the result as a constant expression.
10717     LValue LV;
10718     LV.set(VD);
10719     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10720       return false;
10721     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10722   };
10723   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10724     return ExprEvaluatorBaseTy::VisitBinCmp(E);
10725   });
10726 }
10727 
10728 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10729   // We don't call noteFailure immediately because the assignment happens after
10730   // we evaluate LHS and RHS.
10731   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
10732     return Error(E);
10733 
10734   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
10735   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
10736     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
10737 
10738   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
10739           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
10740          "DataRecursiveIntBinOpEvaluator should have handled integral types");
10741 
10742   if (E->isComparisonOp()) {
10743     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
10744     // comparisons and then translating the result.
10745     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
10746                          const BinaryOperator *E) {
10747       using CCR = ComparisonCategoryResult;
10748       bool IsEqual   = ResKind == CCR::Equal,
10749            IsLess    = ResKind == CCR::Less,
10750            IsGreater = ResKind == CCR::Greater;
10751       auto Op = E->getOpcode();
10752       switch (Op) {
10753       default:
10754         llvm_unreachable("unsupported binary operator");
10755       case BO_EQ:
10756       case BO_NE:
10757         return Success(IsEqual == (Op == BO_EQ), E);
10758       case BO_LT: return Success(IsLess, E);
10759       case BO_GT: return Success(IsGreater, E);
10760       case BO_LE: return Success(IsEqual || IsLess, E);
10761       case BO_GE: return Success(IsEqual || IsGreater, E);
10762       }
10763     };
10764     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
10765       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10766     });
10767   }
10768 
10769   QualType LHSTy = E->getLHS()->getType();
10770   QualType RHSTy = E->getRHS()->getType();
10771 
10772   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
10773       E->getOpcode() == BO_Sub) {
10774     LValue LHSValue, RHSValue;
10775 
10776     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
10777     if (!LHSOK && !Info.noteFailure())
10778       return false;
10779 
10780     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
10781       return false;
10782 
10783     // Reject differing bases from the normal codepath; we special-case
10784     // comparisons to null.
10785     if (!HasSameBase(LHSValue, RHSValue)) {
10786       // Handle &&A - &&B.
10787       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
10788         return Error(E);
10789       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
10790       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
10791       if (!LHSExpr || !RHSExpr)
10792         return Error(E);
10793       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
10794       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
10795       if (!LHSAddrExpr || !RHSAddrExpr)
10796         return Error(E);
10797       // Make sure both labels come from the same function.
10798       if (LHSAddrExpr->getLabel()->getDeclContext() !=
10799           RHSAddrExpr->getLabel()->getDeclContext())
10800         return Error(E);
10801       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
10802     }
10803     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
10804     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
10805 
10806     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
10807     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
10808 
10809     // C++11 [expr.add]p6:
10810     //   Unless both pointers point to elements of the same array object, or
10811     //   one past the last element of the array object, the behavior is
10812     //   undefined.
10813     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
10814         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
10815                                 RHSDesignator))
10816       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
10817 
10818     QualType Type = E->getLHS()->getType();
10819     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
10820 
10821     CharUnits ElementSize;
10822     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
10823       return false;
10824 
10825     // As an extension, a type may have zero size (empty struct or union in
10826     // C, array of zero length). Pointer subtraction in such cases has
10827     // undefined behavior, so is not constant.
10828     if (ElementSize.isZero()) {
10829       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
10830           << ElementType;
10831       return false;
10832     }
10833 
10834     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
10835     // and produce incorrect results when it overflows. Such behavior
10836     // appears to be non-conforming, but is common, so perhaps we should
10837     // assume the standard intended for such cases to be undefined behavior
10838     // and check for them.
10839 
10840     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
10841     // overflow in the final conversion to ptrdiff_t.
10842     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
10843     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
10844     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
10845                     false);
10846     APSInt TrueResult = (LHS - RHS) / ElemSize;
10847     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
10848 
10849     if (Result.extend(65) != TrueResult &&
10850         !HandleOverflow(Info, E, TrueResult, E->getType()))
10851       return false;
10852     return Success(Result, E);
10853   }
10854 
10855   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10856 }
10857 
10858 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
10859 /// a result as the expression's type.
10860 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
10861                                     const UnaryExprOrTypeTraitExpr *E) {
10862   switch(E->getKind()) {
10863   case UETT_PreferredAlignOf:
10864   case UETT_AlignOf: {
10865     if (E->isArgumentType())
10866       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
10867                      E);
10868     else
10869       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
10870                      E);
10871   }
10872 
10873   case UETT_VecStep: {
10874     QualType Ty = E->getTypeOfArgument();
10875 
10876     if (Ty->isVectorType()) {
10877       unsigned n = Ty->castAs<VectorType>()->getNumElements();
10878 
10879       // The vec_step built-in functions that take a 3-component
10880       // vector return 4. (OpenCL 1.1 spec 6.11.12)
10881       if (n == 3)
10882         n = 4;
10883 
10884       return Success(n, E);
10885     } else
10886       return Success(1, E);
10887   }
10888 
10889   case UETT_SizeOf: {
10890     QualType SrcTy = E->getTypeOfArgument();
10891     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
10892     //   the result is the size of the referenced type."
10893     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
10894       SrcTy = Ref->getPointeeType();
10895 
10896     CharUnits Sizeof;
10897     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
10898       return false;
10899     return Success(Sizeof, E);
10900   }
10901   case UETT_OpenMPRequiredSimdAlign:
10902     assert(E->isArgumentType());
10903     return Success(
10904         Info.Ctx.toCharUnitsFromBits(
10905                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
10906             .getQuantity(),
10907         E);
10908   }
10909 
10910   llvm_unreachable("unknown expr/type trait");
10911 }
10912 
10913 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
10914   CharUnits Result;
10915   unsigned n = OOE->getNumComponents();
10916   if (n == 0)
10917     return Error(OOE);
10918   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
10919   for (unsigned i = 0; i != n; ++i) {
10920     OffsetOfNode ON = OOE->getComponent(i);
10921     switch (ON.getKind()) {
10922     case OffsetOfNode::Array: {
10923       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
10924       APSInt IdxResult;
10925       if (!EvaluateInteger(Idx, IdxResult, Info))
10926         return false;
10927       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
10928       if (!AT)
10929         return Error(OOE);
10930       CurrentType = AT->getElementType();
10931       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
10932       Result += IdxResult.getSExtValue() * ElementSize;
10933       break;
10934     }
10935 
10936     case OffsetOfNode::Field: {
10937       FieldDecl *MemberDecl = ON.getField();
10938       const RecordType *RT = CurrentType->getAs<RecordType>();
10939       if (!RT)
10940         return Error(OOE);
10941       RecordDecl *RD = RT->getDecl();
10942       if (RD->isInvalidDecl()) return false;
10943       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10944       unsigned i = MemberDecl->getFieldIndex();
10945       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
10946       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
10947       CurrentType = MemberDecl->getType().getNonReferenceType();
10948       break;
10949     }
10950 
10951     case OffsetOfNode::Identifier:
10952       llvm_unreachable("dependent __builtin_offsetof");
10953 
10954     case OffsetOfNode::Base: {
10955       CXXBaseSpecifier *BaseSpec = ON.getBase();
10956       if (BaseSpec->isVirtual())
10957         return Error(OOE);
10958 
10959       // Find the layout of the class whose base we are looking into.
10960       const RecordType *RT = CurrentType->getAs<RecordType>();
10961       if (!RT)
10962         return Error(OOE);
10963       RecordDecl *RD = RT->getDecl();
10964       if (RD->isInvalidDecl()) return false;
10965       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
10966 
10967       // Find the base class itself.
10968       CurrentType = BaseSpec->getType();
10969       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
10970       if (!BaseRT)
10971         return Error(OOE);
10972 
10973       // Add the offset to the base.
10974       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
10975       break;
10976     }
10977     }
10978   }
10979   return Success(Result, OOE);
10980 }
10981 
10982 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10983   switch (E->getOpcode()) {
10984   default:
10985     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
10986     // See C99 6.6p3.
10987     return Error(E);
10988   case UO_Extension:
10989     // FIXME: Should extension allow i-c-e extension expressions in its scope?
10990     // If so, we could clear the diagnostic ID.
10991     return Visit(E->getSubExpr());
10992   case UO_Plus:
10993     // The result is just the value.
10994     return Visit(E->getSubExpr());
10995   case UO_Minus: {
10996     if (!Visit(E->getSubExpr()))
10997       return false;
10998     if (!Result.isInt()) return Error(E);
10999     const APSInt &Value = Result.getInt();
11000     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
11001         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
11002                         E->getType()))
11003       return false;
11004     return Success(-Value, E);
11005   }
11006   case UO_Not: {
11007     if (!Visit(E->getSubExpr()))
11008       return false;
11009     if (!Result.isInt()) return Error(E);
11010     return Success(~Result.getInt(), E);
11011   }
11012   case UO_LNot: {
11013     bool bres;
11014     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11015       return false;
11016     return Success(!bres, E);
11017   }
11018   }
11019 }
11020 
11021 /// HandleCast - This is used to evaluate implicit or explicit casts where the
11022 /// result type is integer.
11023 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
11024   const Expr *SubExpr = E->getSubExpr();
11025   QualType DestType = E->getType();
11026   QualType SrcType = SubExpr->getType();
11027 
11028   switch (E->getCastKind()) {
11029   case CK_BaseToDerived:
11030   case CK_DerivedToBase:
11031   case CK_UncheckedDerivedToBase:
11032   case CK_Dynamic:
11033   case CK_ToUnion:
11034   case CK_ArrayToPointerDecay:
11035   case CK_FunctionToPointerDecay:
11036   case CK_NullToPointer:
11037   case CK_NullToMemberPointer:
11038   case CK_BaseToDerivedMemberPointer:
11039   case CK_DerivedToBaseMemberPointer:
11040   case CK_ReinterpretMemberPointer:
11041   case CK_ConstructorConversion:
11042   case CK_IntegralToPointer:
11043   case CK_ToVoid:
11044   case CK_VectorSplat:
11045   case CK_IntegralToFloating:
11046   case CK_FloatingCast:
11047   case CK_CPointerToObjCPointerCast:
11048   case CK_BlockPointerToObjCPointerCast:
11049   case CK_AnyPointerToBlockPointerCast:
11050   case CK_ObjCObjectLValueCast:
11051   case CK_FloatingRealToComplex:
11052   case CK_FloatingComplexToReal:
11053   case CK_FloatingComplexCast:
11054   case CK_FloatingComplexToIntegralComplex:
11055   case CK_IntegralRealToComplex:
11056   case CK_IntegralComplexCast:
11057   case CK_IntegralComplexToFloatingComplex:
11058   case CK_BuiltinFnToFnPtr:
11059   case CK_ZeroToOCLOpaqueType:
11060   case CK_NonAtomicToAtomic:
11061   case CK_AddressSpaceConversion:
11062   case CK_IntToOCLSampler:
11063   case CK_FixedPointCast:
11064   case CK_IntegralToFixedPoint:
11065     llvm_unreachable("invalid cast kind for integral value");
11066 
11067   case CK_BitCast:
11068   case CK_Dependent:
11069   case CK_LValueBitCast:
11070   case CK_ARCProduceObject:
11071   case CK_ARCConsumeObject:
11072   case CK_ARCReclaimReturnedObject:
11073   case CK_ARCExtendBlockObject:
11074   case CK_CopyAndAutoreleaseBlockObject:
11075     return Error(E);
11076 
11077   case CK_UserDefinedConversion:
11078   case CK_LValueToRValue:
11079   case CK_AtomicToNonAtomic:
11080   case CK_NoOp:
11081   case CK_LValueToRValueBitCast:
11082     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11083 
11084   case CK_MemberPointerToBoolean:
11085   case CK_PointerToBoolean:
11086   case CK_IntegralToBoolean:
11087   case CK_FloatingToBoolean:
11088   case CK_BooleanToSignedIntegral:
11089   case CK_FloatingComplexToBoolean:
11090   case CK_IntegralComplexToBoolean: {
11091     bool BoolResult;
11092     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
11093       return false;
11094     uint64_t IntResult = BoolResult;
11095     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
11096       IntResult = (uint64_t)-1;
11097     return Success(IntResult, E);
11098   }
11099 
11100   case CK_FixedPointToIntegral: {
11101     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SrcType));
11102     if (!EvaluateFixedPoint(SubExpr, Src, Info))
11103       return false;
11104     bool Overflowed;
11105     llvm::APSInt Result = Src.convertToInt(
11106         Info.Ctx.getIntWidth(DestType),
11107         DestType->isSignedIntegerOrEnumerationType(), &Overflowed);
11108     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11109       return false;
11110     return Success(Result, E);
11111   }
11112 
11113   case CK_FixedPointToBoolean: {
11114     // Unsigned padding does not affect this.
11115     APValue Val;
11116     if (!Evaluate(Val, Info, SubExpr))
11117       return false;
11118     return Success(Val.getFixedPoint().getBoolValue(), E);
11119   }
11120 
11121   case CK_IntegralCast: {
11122     if (!Visit(SubExpr))
11123       return false;
11124 
11125     if (!Result.isInt()) {
11126       // Allow casts of address-of-label differences if they are no-ops
11127       // or narrowing.  (The narrowing case isn't actually guaranteed to
11128       // be constant-evaluatable except in some narrow cases which are hard
11129       // to detect here.  We let it through on the assumption the user knows
11130       // what they are doing.)
11131       if (Result.isAddrLabelDiff())
11132         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
11133       // Only allow casts of lvalues if they are lossless.
11134       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
11135     }
11136 
11137     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
11138                                       Result.getInt()), E);
11139   }
11140 
11141   case CK_PointerToIntegral: {
11142     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
11143 
11144     LValue LV;
11145     if (!EvaluatePointer(SubExpr, LV, Info))
11146       return false;
11147 
11148     if (LV.getLValueBase()) {
11149       // Only allow based lvalue casts if they are lossless.
11150       // FIXME: Allow a larger integer size than the pointer size, and allow
11151       // narrowing back down to pointer width in subsequent integral casts.
11152       // FIXME: Check integer type's active bits, not its type size.
11153       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
11154         return Error(E);
11155 
11156       LV.Designator.setInvalid();
11157       LV.moveInto(Result);
11158       return true;
11159     }
11160 
11161     APSInt AsInt;
11162     APValue V;
11163     LV.moveInto(V);
11164     if (!V.toIntegralConstant(AsInt, SrcType, Info.Ctx))
11165       llvm_unreachable("Can't cast this!");
11166 
11167     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
11168   }
11169 
11170   case CK_IntegralComplexToReal: {
11171     ComplexValue C;
11172     if (!EvaluateComplex(SubExpr, C, Info))
11173       return false;
11174     return Success(C.getComplexIntReal(), E);
11175   }
11176 
11177   case CK_FloatingToIntegral: {
11178     APFloat F(0.0);
11179     if (!EvaluateFloat(SubExpr, F, Info))
11180       return false;
11181 
11182     APSInt Value;
11183     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
11184       return false;
11185     return Success(Value, E);
11186   }
11187   }
11188 
11189   llvm_unreachable("unknown cast resulting in integral value");
11190 }
11191 
11192 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11193   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11194     ComplexValue LV;
11195     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11196       return false;
11197     if (!LV.isComplexInt())
11198       return Error(E);
11199     return Success(LV.getComplexIntReal(), E);
11200   }
11201 
11202   return Visit(E->getSubExpr());
11203 }
11204 
11205 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11206   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
11207     ComplexValue LV;
11208     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
11209       return false;
11210     if (!LV.isComplexInt())
11211       return Error(E);
11212     return Success(LV.getComplexIntImag(), E);
11213   }
11214 
11215   VisitIgnoredValue(E->getSubExpr());
11216   return Success(0, E);
11217 }
11218 
11219 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
11220   return Success(E->getPackLength(), E);
11221 }
11222 
11223 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
11224   return Success(E->getValue(), E);
11225 }
11226 
11227 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11228   switch (E->getOpcode()) {
11229     default:
11230       // Invalid unary operators
11231       return Error(E);
11232     case UO_Plus:
11233       // The result is just the value.
11234       return Visit(E->getSubExpr());
11235     case UO_Minus: {
11236       if (!Visit(E->getSubExpr())) return false;
11237       if (!Result.isFixedPoint())
11238         return Error(E);
11239       bool Overflowed;
11240       APFixedPoint Negated = Result.getFixedPoint().negate(&Overflowed);
11241       if (Overflowed && !HandleOverflow(Info, E, Negated, E->getType()))
11242         return false;
11243       return Success(Negated, E);
11244     }
11245     case UO_LNot: {
11246       bool bres;
11247       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
11248         return false;
11249       return Success(!bres, E);
11250     }
11251   }
11252 }
11253 
11254 bool FixedPointExprEvaluator::VisitCastExpr(const CastExpr *E) {
11255   const Expr *SubExpr = E->getSubExpr();
11256   QualType DestType = E->getType();
11257   assert(DestType->isFixedPointType() &&
11258          "Expected destination type to be a fixed point type");
11259   auto DestFXSema = Info.Ctx.getFixedPointSemantics(DestType);
11260 
11261   switch (E->getCastKind()) {
11262   case CK_FixedPointCast: {
11263     APFixedPoint Src(Info.Ctx.getFixedPointSemantics(SubExpr->getType()));
11264     if (!EvaluateFixedPoint(SubExpr, Src, Info))
11265       return false;
11266     bool Overflowed;
11267     APFixedPoint Result = Src.convert(DestFXSema, &Overflowed);
11268     if (Overflowed && !HandleOverflow(Info, E, Result, DestType))
11269       return false;
11270     return Success(Result, E);
11271   }
11272   case CK_IntegralToFixedPoint: {
11273     APSInt Src;
11274     if (!EvaluateInteger(SubExpr, Src, Info))
11275       return false;
11276 
11277     bool Overflowed;
11278     APFixedPoint IntResult = APFixedPoint::getFromIntValue(
11279         Src, Info.Ctx.getFixedPointSemantics(DestType), &Overflowed);
11280 
11281     if (Overflowed && !HandleOverflow(Info, E, IntResult, DestType))
11282       return false;
11283 
11284     return Success(IntResult, E);
11285   }
11286   case CK_NoOp:
11287   case CK_LValueToRValue:
11288     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11289   default:
11290     return Error(E);
11291   }
11292 }
11293 
11294 bool FixedPointExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11295   const Expr *LHS = E->getLHS();
11296   const Expr *RHS = E->getRHS();
11297   FixedPointSemantics ResultFXSema =
11298       Info.Ctx.getFixedPointSemantics(E->getType());
11299 
11300   APFixedPoint LHSFX(Info.Ctx.getFixedPointSemantics(LHS->getType()));
11301   if (!EvaluateFixedPointOrInteger(LHS, LHSFX, Info))
11302     return false;
11303   APFixedPoint RHSFX(Info.Ctx.getFixedPointSemantics(RHS->getType()));
11304   if (!EvaluateFixedPointOrInteger(RHS, RHSFX, Info))
11305     return false;
11306 
11307   switch (E->getOpcode()) {
11308   case BO_Add: {
11309     bool AddOverflow, ConversionOverflow;
11310     APFixedPoint Result = LHSFX.add(RHSFX, &AddOverflow)
11311                               .convert(ResultFXSema, &ConversionOverflow);
11312     if ((AddOverflow || ConversionOverflow) &&
11313         !HandleOverflow(Info, E, Result, E->getType()))
11314       return false;
11315     return Success(Result, E);
11316   }
11317   default:
11318     return false;
11319   }
11320   llvm_unreachable("Should've exited before this");
11321 }
11322 
11323 //===----------------------------------------------------------------------===//
11324 // Float Evaluation
11325 //===----------------------------------------------------------------------===//
11326 
11327 namespace {
11328 class FloatExprEvaluator
11329   : public ExprEvaluatorBase<FloatExprEvaluator> {
11330   APFloat &Result;
11331 public:
11332   FloatExprEvaluator(EvalInfo &info, APFloat &result)
11333     : ExprEvaluatorBaseTy(info), Result(result) {}
11334 
11335   bool Success(const APValue &V, const Expr *e) {
11336     Result = V.getFloat();
11337     return true;
11338   }
11339 
11340   bool ZeroInitialization(const Expr *E) {
11341     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
11342     return true;
11343   }
11344 
11345   bool VisitCallExpr(const CallExpr *E);
11346 
11347   bool VisitUnaryOperator(const UnaryOperator *E);
11348   bool VisitBinaryOperator(const BinaryOperator *E);
11349   bool VisitFloatingLiteral(const FloatingLiteral *E);
11350   bool VisitCastExpr(const CastExpr *E);
11351 
11352   bool VisitUnaryReal(const UnaryOperator *E);
11353   bool VisitUnaryImag(const UnaryOperator *E);
11354 
11355   // FIXME: Missing: array subscript of vector, member of vector
11356 };
11357 } // end anonymous namespace
11358 
11359 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
11360   assert(E->isRValue() && E->getType()->isRealFloatingType());
11361   return FloatExprEvaluator(Info, Result).Visit(E);
11362 }
11363 
11364 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
11365                                   QualType ResultTy,
11366                                   const Expr *Arg,
11367                                   bool SNaN,
11368                                   llvm::APFloat &Result) {
11369   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
11370   if (!S) return false;
11371 
11372   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
11373 
11374   llvm::APInt fill;
11375 
11376   // Treat empty strings as if they were zero.
11377   if (S->getString().empty())
11378     fill = llvm::APInt(32, 0);
11379   else if (S->getString().getAsInteger(0, fill))
11380     return false;
11381 
11382   if (Context.getTargetInfo().isNan2008()) {
11383     if (SNaN)
11384       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11385     else
11386       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11387   } else {
11388     // Prior to IEEE 754-2008, architectures were allowed to choose whether
11389     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
11390     // a different encoding to what became a standard in 2008, and for pre-
11391     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
11392     // sNaN. This is now known as "legacy NaN" encoding.
11393     if (SNaN)
11394       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
11395     else
11396       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
11397   }
11398 
11399   return true;
11400 }
11401 
11402 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
11403   switch (E->getBuiltinCallee()) {
11404   default:
11405     return ExprEvaluatorBaseTy::VisitCallExpr(E);
11406 
11407   case Builtin::BI__builtin_huge_val:
11408   case Builtin::BI__builtin_huge_valf:
11409   case Builtin::BI__builtin_huge_vall:
11410   case Builtin::BI__builtin_huge_valf128:
11411   case Builtin::BI__builtin_inf:
11412   case Builtin::BI__builtin_inff:
11413   case Builtin::BI__builtin_infl:
11414   case Builtin::BI__builtin_inff128: {
11415     const llvm::fltSemantics &Sem =
11416       Info.Ctx.getFloatTypeSemantics(E->getType());
11417     Result = llvm::APFloat::getInf(Sem);
11418     return true;
11419   }
11420 
11421   case Builtin::BI__builtin_nans:
11422   case Builtin::BI__builtin_nansf:
11423   case Builtin::BI__builtin_nansl:
11424   case Builtin::BI__builtin_nansf128:
11425     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11426                                true, Result))
11427       return Error(E);
11428     return true;
11429 
11430   case Builtin::BI__builtin_nan:
11431   case Builtin::BI__builtin_nanf:
11432   case Builtin::BI__builtin_nanl:
11433   case Builtin::BI__builtin_nanf128:
11434     // If this is __builtin_nan() turn this into a nan, otherwise we
11435     // can't constant fold it.
11436     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
11437                                false, Result))
11438       return Error(E);
11439     return true;
11440 
11441   case Builtin::BI__builtin_fabs:
11442   case Builtin::BI__builtin_fabsf:
11443   case Builtin::BI__builtin_fabsl:
11444   case Builtin::BI__builtin_fabsf128:
11445     if (!EvaluateFloat(E->getArg(0), Result, Info))
11446       return false;
11447 
11448     if (Result.isNegative())
11449       Result.changeSign();
11450     return true;
11451 
11452   // FIXME: Builtin::BI__builtin_powi
11453   // FIXME: Builtin::BI__builtin_powif
11454   // FIXME: Builtin::BI__builtin_powil
11455 
11456   case Builtin::BI__builtin_copysign:
11457   case Builtin::BI__builtin_copysignf:
11458   case Builtin::BI__builtin_copysignl:
11459   case Builtin::BI__builtin_copysignf128: {
11460     APFloat RHS(0.);
11461     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
11462         !EvaluateFloat(E->getArg(1), RHS, Info))
11463       return false;
11464     Result.copySign(RHS);
11465     return true;
11466   }
11467   }
11468 }
11469 
11470 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
11471   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11472     ComplexValue CV;
11473     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11474       return false;
11475     Result = CV.FloatReal;
11476     return true;
11477   }
11478 
11479   return Visit(E->getSubExpr());
11480 }
11481 
11482 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
11483   if (E->getSubExpr()->getType()->isAnyComplexType()) {
11484     ComplexValue CV;
11485     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
11486       return false;
11487     Result = CV.FloatImag;
11488     return true;
11489   }
11490 
11491   VisitIgnoredValue(E->getSubExpr());
11492   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
11493   Result = llvm::APFloat::getZero(Sem);
11494   return true;
11495 }
11496 
11497 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
11498   switch (E->getOpcode()) {
11499   default: return Error(E);
11500   case UO_Plus:
11501     return EvaluateFloat(E->getSubExpr(), Result, Info);
11502   case UO_Minus:
11503     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
11504       return false;
11505     Result.changeSign();
11506     return true;
11507   }
11508 }
11509 
11510 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11511   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11512     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11513 
11514   APFloat RHS(0.0);
11515   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
11516   if (!LHSOK && !Info.noteFailure())
11517     return false;
11518   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
11519          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
11520 }
11521 
11522 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
11523   Result = E->getValue();
11524   return true;
11525 }
11526 
11527 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
11528   const Expr* SubExpr = E->getSubExpr();
11529 
11530   switch (E->getCastKind()) {
11531   default:
11532     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11533 
11534   case CK_IntegralToFloating: {
11535     APSInt IntResult;
11536     return EvaluateInteger(SubExpr, IntResult, Info) &&
11537            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
11538                                 E->getType(), Result);
11539   }
11540 
11541   case CK_FloatingCast: {
11542     if (!Visit(SubExpr))
11543       return false;
11544     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
11545                                   Result);
11546   }
11547 
11548   case CK_FloatingComplexToReal: {
11549     ComplexValue V;
11550     if (!EvaluateComplex(SubExpr, V, Info))
11551       return false;
11552     Result = V.getComplexFloatReal();
11553     return true;
11554   }
11555   }
11556 }
11557 
11558 //===----------------------------------------------------------------------===//
11559 // Complex Evaluation (for float and integer)
11560 //===----------------------------------------------------------------------===//
11561 
11562 namespace {
11563 class ComplexExprEvaluator
11564   : public ExprEvaluatorBase<ComplexExprEvaluator> {
11565   ComplexValue &Result;
11566 
11567 public:
11568   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
11569     : ExprEvaluatorBaseTy(info), Result(Result) {}
11570 
11571   bool Success(const APValue &V, const Expr *e) {
11572     Result.setFrom(V);
11573     return true;
11574   }
11575 
11576   bool ZeroInitialization(const Expr *E);
11577 
11578   //===--------------------------------------------------------------------===//
11579   //                            Visitor Methods
11580   //===--------------------------------------------------------------------===//
11581 
11582   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
11583   bool VisitCastExpr(const CastExpr *E);
11584   bool VisitBinaryOperator(const BinaryOperator *E);
11585   bool VisitUnaryOperator(const UnaryOperator *E);
11586   bool VisitInitListExpr(const InitListExpr *E);
11587 };
11588 } // end anonymous namespace
11589 
11590 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
11591                             EvalInfo &Info) {
11592   assert(E->isRValue() && E->getType()->isAnyComplexType());
11593   return ComplexExprEvaluator(Info, Result).Visit(E);
11594 }
11595 
11596 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
11597   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
11598   if (ElemTy->isRealFloatingType()) {
11599     Result.makeComplexFloat();
11600     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
11601     Result.FloatReal = Zero;
11602     Result.FloatImag = Zero;
11603   } else {
11604     Result.makeComplexInt();
11605     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
11606     Result.IntReal = Zero;
11607     Result.IntImag = Zero;
11608   }
11609   return true;
11610 }
11611 
11612 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
11613   const Expr* SubExpr = E->getSubExpr();
11614 
11615   if (SubExpr->getType()->isRealFloatingType()) {
11616     Result.makeComplexFloat();
11617     APFloat &Imag = Result.FloatImag;
11618     if (!EvaluateFloat(SubExpr, Imag, Info))
11619       return false;
11620 
11621     Result.FloatReal = APFloat(Imag.getSemantics());
11622     return true;
11623   } else {
11624     assert(SubExpr->getType()->isIntegerType() &&
11625            "Unexpected imaginary literal.");
11626 
11627     Result.makeComplexInt();
11628     APSInt &Imag = Result.IntImag;
11629     if (!EvaluateInteger(SubExpr, Imag, Info))
11630       return false;
11631 
11632     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
11633     return true;
11634   }
11635 }
11636 
11637 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
11638 
11639   switch (E->getCastKind()) {
11640   case CK_BitCast:
11641   case CK_BaseToDerived:
11642   case CK_DerivedToBase:
11643   case CK_UncheckedDerivedToBase:
11644   case CK_Dynamic:
11645   case CK_ToUnion:
11646   case CK_ArrayToPointerDecay:
11647   case CK_FunctionToPointerDecay:
11648   case CK_NullToPointer:
11649   case CK_NullToMemberPointer:
11650   case CK_BaseToDerivedMemberPointer:
11651   case CK_DerivedToBaseMemberPointer:
11652   case CK_MemberPointerToBoolean:
11653   case CK_ReinterpretMemberPointer:
11654   case CK_ConstructorConversion:
11655   case CK_IntegralToPointer:
11656   case CK_PointerToIntegral:
11657   case CK_PointerToBoolean:
11658   case CK_ToVoid:
11659   case CK_VectorSplat:
11660   case CK_IntegralCast:
11661   case CK_BooleanToSignedIntegral:
11662   case CK_IntegralToBoolean:
11663   case CK_IntegralToFloating:
11664   case CK_FloatingToIntegral:
11665   case CK_FloatingToBoolean:
11666   case CK_FloatingCast:
11667   case CK_CPointerToObjCPointerCast:
11668   case CK_BlockPointerToObjCPointerCast:
11669   case CK_AnyPointerToBlockPointerCast:
11670   case CK_ObjCObjectLValueCast:
11671   case CK_FloatingComplexToReal:
11672   case CK_FloatingComplexToBoolean:
11673   case CK_IntegralComplexToReal:
11674   case CK_IntegralComplexToBoolean:
11675   case CK_ARCProduceObject:
11676   case CK_ARCConsumeObject:
11677   case CK_ARCReclaimReturnedObject:
11678   case CK_ARCExtendBlockObject:
11679   case CK_CopyAndAutoreleaseBlockObject:
11680   case CK_BuiltinFnToFnPtr:
11681   case CK_ZeroToOCLOpaqueType:
11682   case CK_NonAtomicToAtomic:
11683   case CK_AddressSpaceConversion:
11684   case CK_IntToOCLSampler:
11685   case CK_FixedPointCast:
11686   case CK_FixedPointToBoolean:
11687   case CK_FixedPointToIntegral:
11688   case CK_IntegralToFixedPoint:
11689     llvm_unreachable("invalid cast kind for complex value");
11690 
11691   case CK_LValueToRValue:
11692   case CK_AtomicToNonAtomic:
11693   case CK_NoOp:
11694   case CK_LValueToRValueBitCast:
11695     return ExprEvaluatorBaseTy::VisitCastExpr(E);
11696 
11697   case CK_Dependent:
11698   case CK_LValueBitCast:
11699   case CK_UserDefinedConversion:
11700     return Error(E);
11701 
11702   case CK_FloatingRealToComplex: {
11703     APFloat &Real = Result.FloatReal;
11704     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
11705       return false;
11706 
11707     Result.makeComplexFloat();
11708     Result.FloatImag = APFloat(Real.getSemantics());
11709     return true;
11710   }
11711 
11712   case CK_FloatingComplexCast: {
11713     if (!Visit(E->getSubExpr()))
11714       return false;
11715 
11716     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11717     QualType From
11718       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11719 
11720     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
11721            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
11722   }
11723 
11724   case CK_FloatingComplexToIntegralComplex: {
11725     if (!Visit(E->getSubExpr()))
11726       return false;
11727 
11728     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11729     QualType From
11730       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11731     Result.makeComplexInt();
11732     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
11733                                 To, Result.IntReal) &&
11734            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
11735                                 To, Result.IntImag);
11736   }
11737 
11738   case CK_IntegralRealToComplex: {
11739     APSInt &Real = Result.IntReal;
11740     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
11741       return false;
11742 
11743     Result.makeComplexInt();
11744     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
11745     return true;
11746   }
11747 
11748   case CK_IntegralComplexCast: {
11749     if (!Visit(E->getSubExpr()))
11750       return false;
11751 
11752     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
11753     QualType From
11754       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
11755 
11756     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
11757     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
11758     return true;
11759   }
11760 
11761   case CK_IntegralComplexToFloatingComplex: {
11762     if (!Visit(E->getSubExpr()))
11763       return false;
11764 
11765     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
11766     QualType From
11767       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
11768     Result.makeComplexFloat();
11769     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
11770                                 To, Result.FloatReal) &&
11771            HandleIntToFloatCast(Info, E, From, Result.IntImag,
11772                                 To, Result.FloatImag);
11773   }
11774   }
11775 
11776   llvm_unreachable("unknown cast resulting in complex value");
11777 }
11778 
11779 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
11780   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
11781     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
11782 
11783   // Track whether the LHS or RHS is real at the type system level. When this is
11784   // the case we can simplify our evaluation strategy.
11785   bool LHSReal = false, RHSReal = false;
11786 
11787   bool LHSOK;
11788   if (E->getLHS()->getType()->isRealFloatingType()) {
11789     LHSReal = true;
11790     APFloat &Real = Result.FloatReal;
11791     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
11792     if (LHSOK) {
11793       Result.makeComplexFloat();
11794       Result.FloatImag = APFloat(Real.getSemantics());
11795     }
11796   } else {
11797     LHSOK = Visit(E->getLHS());
11798   }
11799   if (!LHSOK && !Info.noteFailure())
11800     return false;
11801 
11802   ComplexValue RHS;
11803   if (E->getRHS()->getType()->isRealFloatingType()) {
11804     RHSReal = true;
11805     APFloat &Real = RHS.FloatReal;
11806     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
11807       return false;
11808     RHS.makeComplexFloat();
11809     RHS.FloatImag = APFloat(Real.getSemantics());
11810   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
11811     return false;
11812 
11813   assert(!(LHSReal && RHSReal) &&
11814          "Cannot have both operands of a complex operation be real.");
11815   switch (E->getOpcode()) {
11816   default: return Error(E);
11817   case BO_Add:
11818     if (Result.isComplexFloat()) {
11819       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
11820                                        APFloat::rmNearestTiesToEven);
11821       if (LHSReal)
11822         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11823       else if (!RHSReal)
11824         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
11825                                          APFloat::rmNearestTiesToEven);
11826     } else {
11827       Result.getComplexIntReal() += RHS.getComplexIntReal();
11828       Result.getComplexIntImag() += RHS.getComplexIntImag();
11829     }
11830     break;
11831   case BO_Sub:
11832     if (Result.isComplexFloat()) {
11833       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
11834                                             APFloat::rmNearestTiesToEven);
11835       if (LHSReal) {
11836         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
11837         Result.getComplexFloatImag().changeSign();
11838       } else if (!RHSReal) {
11839         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
11840                                               APFloat::rmNearestTiesToEven);
11841       }
11842     } else {
11843       Result.getComplexIntReal() -= RHS.getComplexIntReal();
11844       Result.getComplexIntImag() -= RHS.getComplexIntImag();
11845     }
11846     break;
11847   case BO_Mul:
11848     if (Result.isComplexFloat()) {
11849       // This is an implementation of complex multiplication according to the
11850       // constraints laid out in C11 Annex G. The implementation uses the
11851       // following naming scheme:
11852       //   (a + ib) * (c + id)
11853       ComplexValue LHS = Result;
11854       APFloat &A = LHS.getComplexFloatReal();
11855       APFloat &B = LHS.getComplexFloatImag();
11856       APFloat &C = RHS.getComplexFloatReal();
11857       APFloat &D = RHS.getComplexFloatImag();
11858       APFloat &ResR = Result.getComplexFloatReal();
11859       APFloat &ResI = Result.getComplexFloatImag();
11860       if (LHSReal) {
11861         assert(!RHSReal && "Cannot have two real operands for a complex op!");
11862         ResR = A * C;
11863         ResI = A * D;
11864       } else if (RHSReal) {
11865         ResR = C * A;
11866         ResI = C * B;
11867       } else {
11868         // In the fully general case, we need to handle NaNs and infinities
11869         // robustly.
11870         APFloat AC = A * C;
11871         APFloat BD = B * D;
11872         APFloat AD = A * D;
11873         APFloat BC = B * C;
11874         ResR = AC - BD;
11875         ResI = AD + BC;
11876         if (ResR.isNaN() && ResI.isNaN()) {
11877           bool Recalc = false;
11878           if (A.isInfinity() || B.isInfinity()) {
11879             A = APFloat::copySign(
11880                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11881             B = APFloat::copySign(
11882                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11883             if (C.isNaN())
11884               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11885             if (D.isNaN())
11886               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11887             Recalc = true;
11888           }
11889           if (C.isInfinity() || D.isInfinity()) {
11890             C = APFloat::copySign(
11891                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11892             D = APFloat::copySign(
11893                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11894             if (A.isNaN())
11895               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11896             if (B.isNaN())
11897               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11898             Recalc = true;
11899           }
11900           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
11901                           AD.isInfinity() || BC.isInfinity())) {
11902             if (A.isNaN())
11903               A = APFloat::copySign(APFloat(A.getSemantics()), A);
11904             if (B.isNaN())
11905               B = APFloat::copySign(APFloat(B.getSemantics()), B);
11906             if (C.isNaN())
11907               C = APFloat::copySign(APFloat(C.getSemantics()), C);
11908             if (D.isNaN())
11909               D = APFloat::copySign(APFloat(D.getSemantics()), D);
11910             Recalc = true;
11911           }
11912           if (Recalc) {
11913             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
11914             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
11915           }
11916         }
11917       }
11918     } else {
11919       ComplexValue LHS = Result;
11920       Result.getComplexIntReal() =
11921         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
11922          LHS.getComplexIntImag() * RHS.getComplexIntImag());
11923       Result.getComplexIntImag() =
11924         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
11925          LHS.getComplexIntImag() * RHS.getComplexIntReal());
11926     }
11927     break;
11928   case BO_Div:
11929     if (Result.isComplexFloat()) {
11930       // This is an implementation of complex division according to the
11931       // constraints laid out in C11 Annex G. The implementation uses the
11932       // following naming scheme:
11933       //   (a + ib) / (c + id)
11934       ComplexValue LHS = Result;
11935       APFloat &A = LHS.getComplexFloatReal();
11936       APFloat &B = LHS.getComplexFloatImag();
11937       APFloat &C = RHS.getComplexFloatReal();
11938       APFloat &D = RHS.getComplexFloatImag();
11939       APFloat &ResR = Result.getComplexFloatReal();
11940       APFloat &ResI = Result.getComplexFloatImag();
11941       if (RHSReal) {
11942         ResR = A / C;
11943         ResI = B / C;
11944       } else {
11945         if (LHSReal) {
11946           // No real optimizations we can do here, stub out with zero.
11947           B = APFloat::getZero(A.getSemantics());
11948         }
11949         int DenomLogB = 0;
11950         APFloat MaxCD = maxnum(abs(C), abs(D));
11951         if (MaxCD.isFinite()) {
11952           DenomLogB = ilogb(MaxCD);
11953           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
11954           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
11955         }
11956         APFloat Denom = C * C + D * D;
11957         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
11958                       APFloat::rmNearestTiesToEven);
11959         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
11960                       APFloat::rmNearestTiesToEven);
11961         if (ResR.isNaN() && ResI.isNaN()) {
11962           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
11963             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
11964             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
11965           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
11966                      D.isFinite()) {
11967             A = APFloat::copySign(
11968                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
11969             B = APFloat::copySign(
11970                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
11971             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
11972             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
11973           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
11974             C = APFloat::copySign(
11975                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
11976             D = APFloat::copySign(
11977                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
11978             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
11979             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
11980           }
11981         }
11982       }
11983     } else {
11984       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
11985         return Error(E, diag::note_expr_divide_by_zero);
11986 
11987       ComplexValue LHS = Result;
11988       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
11989         RHS.getComplexIntImag() * RHS.getComplexIntImag();
11990       Result.getComplexIntReal() =
11991         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
11992          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
11993       Result.getComplexIntImag() =
11994         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
11995          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
11996     }
11997     break;
11998   }
11999 
12000   return true;
12001 }
12002 
12003 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
12004   // Get the operand value into 'Result'.
12005   if (!Visit(E->getSubExpr()))
12006     return false;
12007 
12008   switch (E->getOpcode()) {
12009   default:
12010     return Error(E);
12011   case UO_Extension:
12012     return true;
12013   case UO_Plus:
12014     // The result is always just the subexpr.
12015     return true;
12016   case UO_Minus:
12017     if (Result.isComplexFloat()) {
12018       Result.getComplexFloatReal().changeSign();
12019       Result.getComplexFloatImag().changeSign();
12020     }
12021     else {
12022       Result.getComplexIntReal() = -Result.getComplexIntReal();
12023       Result.getComplexIntImag() = -Result.getComplexIntImag();
12024     }
12025     return true;
12026   case UO_Not:
12027     if (Result.isComplexFloat())
12028       Result.getComplexFloatImag().changeSign();
12029     else
12030       Result.getComplexIntImag() = -Result.getComplexIntImag();
12031     return true;
12032   }
12033 }
12034 
12035 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
12036   if (E->getNumInits() == 2) {
12037     if (E->getType()->isComplexType()) {
12038       Result.makeComplexFloat();
12039       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
12040         return false;
12041       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
12042         return false;
12043     } else {
12044       Result.makeComplexInt();
12045       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
12046         return false;
12047       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
12048         return false;
12049     }
12050     return true;
12051   }
12052   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
12053 }
12054 
12055 //===----------------------------------------------------------------------===//
12056 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
12057 // implicit conversion.
12058 //===----------------------------------------------------------------------===//
12059 
12060 namespace {
12061 class AtomicExprEvaluator :
12062     public ExprEvaluatorBase<AtomicExprEvaluator> {
12063   const LValue *This;
12064   APValue &Result;
12065 public:
12066   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
12067       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
12068 
12069   bool Success(const APValue &V, const Expr *E) {
12070     Result = V;
12071     return true;
12072   }
12073 
12074   bool ZeroInitialization(const Expr *E) {
12075     ImplicitValueInitExpr VIE(
12076         E->getType()->castAs<AtomicType>()->getValueType());
12077     // For atomic-qualified class (and array) types in C++, initialize the
12078     // _Atomic-wrapped subobject directly, in-place.
12079     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
12080                 : Evaluate(Result, Info, &VIE);
12081   }
12082 
12083   bool VisitCastExpr(const CastExpr *E) {
12084     switch (E->getCastKind()) {
12085     default:
12086       return ExprEvaluatorBaseTy::VisitCastExpr(E);
12087     case CK_NonAtomicToAtomic:
12088       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
12089                   : Evaluate(Result, Info, E->getSubExpr());
12090     }
12091   }
12092 };
12093 } // end anonymous namespace
12094 
12095 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
12096                            EvalInfo &Info) {
12097   assert(E->isRValue() && E->getType()->isAtomicType());
12098   return AtomicExprEvaluator(Info, This, Result).Visit(E);
12099 }
12100 
12101 //===----------------------------------------------------------------------===//
12102 // Void expression evaluation, primarily for a cast to void on the LHS of a
12103 // comma operator
12104 //===----------------------------------------------------------------------===//
12105 
12106 namespace {
12107 class VoidExprEvaluator
12108   : public ExprEvaluatorBase<VoidExprEvaluator> {
12109 public:
12110   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
12111 
12112   bool Success(const APValue &V, const Expr *e) { return true; }
12113 
12114   bool ZeroInitialization(const Expr *E) { return true; }
12115 
12116   bool VisitCastExpr(const CastExpr *E) {
12117     switch (E->getCastKind()) {
12118     default:
12119       return ExprEvaluatorBaseTy::VisitCastExpr(E);
12120     case CK_ToVoid:
12121       VisitIgnoredValue(E->getSubExpr());
12122       return true;
12123     }
12124   }
12125 
12126   bool VisitCallExpr(const CallExpr *E) {
12127     switch (E->getBuiltinCallee()) {
12128     default:
12129       return ExprEvaluatorBaseTy::VisitCallExpr(E);
12130     case Builtin::BI__assume:
12131     case Builtin::BI__builtin_assume:
12132       // The argument is not evaluated!
12133       return true;
12134     }
12135   }
12136 };
12137 } // end anonymous namespace
12138 
12139 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
12140   assert(E->isRValue() && E->getType()->isVoidType());
12141   return VoidExprEvaluator(Info).Visit(E);
12142 }
12143 
12144 //===----------------------------------------------------------------------===//
12145 // Top level Expr::EvaluateAsRValue method.
12146 //===----------------------------------------------------------------------===//
12147 
12148 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
12149   // In C, function designators are not lvalues, but we evaluate them as if they
12150   // are.
12151   QualType T = E->getType();
12152   if (E->isGLValue() || T->isFunctionType()) {
12153     LValue LV;
12154     if (!EvaluateLValue(E, LV, Info))
12155       return false;
12156     LV.moveInto(Result);
12157   } else if (T->isVectorType()) {
12158     if (!EvaluateVector(E, Result, Info))
12159       return false;
12160   } else if (T->isIntegralOrEnumerationType()) {
12161     if (!IntExprEvaluator(Info, Result).Visit(E))
12162       return false;
12163   } else if (T->hasPointerRepresentation()) {
12164     LValue LV;
12165     if (!EvaluatePointer(E, LV, Info))
12166       return false;
12167     LV.moveInto(Result);
12168   } else if (T->isRealFloatingType()) {
12169     llvm::APFloat F(0.0);
12170     if (!EvaluateFloat(E, F, Info))
12171       return false;
12172     Result = APValue(F);
12173   } else if (T->isAnyComplexType()) {
12174     ComplexValue C;
12175     if (!EvaluateComplex(E, C, Info))
12176       return false;
12177     C.moveInto(Result);
12178   } else if (T->isFixedPointType()) {
12179     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
12180   } else if (T->isMemberPointerType()) {
12181     MemberPtr P;
12182     if (!EvaluateMemberPointer(E, P, Info))
12183       return false;
12184     P.moveInto(Result);
12185     return true;
12186   } else if (T->isArrayType()) {
12187     LValue LV;
12188     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12189     if (!EvaluateArray(E, LV, Value, Info))
12190       return false;
12191     Result = Value;
12192   } else if (T->isRecordType()) {
12193     LValue LV;
12194     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12195     if (!EvaluateRecord(E, LV, Value, Info))
12196       return false;
12197     Result = Value;
12198   } else if (T->isVoidType()) {
12199     if (!Info.getLangOpts().CPlusPlus11)
12200       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
12201         << E->getType();
12202     if (!EvaluateVoid(E, Info))
12203       return false;
12204   } else if (T->isAtomicType()) {
12205     QualType Unqual = T.getAtomicUnqualifiedType();
12206     if (Unqual->isArrayType() || Unqual->isRecordType()) {
12207       LValue LV;
12208       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
12209       if (!EvaluateAtomic(E, &LV, Value, Info))
12210         return false;
12211     } else {
12212       if (!EvaluateAtomic(E, nullptr, Result, Info))
12213         return false;
12214     }
12215   } else if (Info.getLangOpts().CPlusPlus11) {
12216     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
12217     return false;
12218   } else {
12219     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
12220     return false;
12221   }
12222 
12223   return true;
12224 }
12225 
12226 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
12227 /// cases, the in-place evaluation is essential, since later initializers for
12228 /// an object can indirectly refer to subobjects which were initialized earlier.
12229 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
12230                             const Expr *E, bool AllowNonLiteralTypes) {
12231   assert(!E->isValueDependent());
12232 
12233   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
12234     return false;
12235 
12236   if (E->isRValue()) {
12237     // Evaluate arrays and record types in-place, so that later initializers can
12238     // refer to earlier-initialized members of the object.
12239     QualType T = E->getType();
12240     if (T->isArrayType())
12241       return EvaluateArray(E, This, Result, Info);
12242     else if (T->isRecordType())
12243       return EvaluateRecord(E, This, Result, Info);
12244     else if (T->isAtomicType()) {
12245       QualType Unqual = T.getAtomicUnqualifiedType();
12246       if (Unqual->isArrayType() || Unqual->isRecordType())
12247         return EvaluateAtomic(E, &This, Result, Info);
12248     }
12249   }
12250 
12251   // For any other type, in-place evaluation is unimportant.
12252   return Evaluate(Result, Info, E);
12253 }
12254 
12255 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
12256 /// lvalue-to-rvalue cast if it is an lvalue.
12257 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
12258   if (E->getType().isNull())
12259     return false;
12260 
12261   if (!CheckLiteralType(Info, E))
12262     return false;
12263 
12264   if (!::Evaluate(Result, Info, E))
12265     return false;
12266 
12267   if (E->isGLValue()) {
12268     LValue LV;
12269     LV.setFrom(Info.Ctx, Result);
12270     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
12271       return false;
12272   }
12273 
12274   // Check this core constant expression is a constant expression.
12275   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
12276 }
12277 
12278 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
12279                                  const ASTContext &Ctx, bool &IsConst) {
12280   // Fast-path evaluations of integer literals, since we sometimes see files
12281   // containing vast quantities of these.
12282   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
12283     Result.Val = APValue(APSInt(L->getValue(),
12284                                 L->getType()->isUnsignedIntegerType()));
12285     IsConst = true;
12286     return true;
12287   }
12288 
12289   // This case should be rare, but we need to check it before we check on
12290   // the type below.
12291   if (Exp->getType().isNull()) {
12292     IsConst = false;
12293     return true;
12294   }
12295 
12296   // FIXME: Evaluating values of large array and record types can cause
12297   // performance problems. Only do so in C++11 for now.
12298   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
12299                           Exp->getType()->isRecordType()) &&
12300       !Ctx.getLangOpts().CPlusPlus11) {
12301     IsConst = false;
12302     return true;
12303   }
12304   return false;
12305 }
12306 
12307 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
12308                                       Expr::SideEffectsKind SEK) {
12309   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
12310          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
12311 }
12312 
12313 static bool EvaluateAsRValue(const Expr *E, Expr::EvalResult &Result,
12314                              const ASTContext &Ctx, EvalInfo &Info) {
12315   bool IsConst;
12316   if (FastEvaluateAsRValue(E, Result, Ctx, IsConst))
12317     return IsConst;
12318 
12319   return EvaluateAsRValue(Info, E, Result.Val);
12320 }
12321 
12322 static bool EvaluateAsInt(const Expr *E, Expr::EvalResult &ExprResult,
12323                           const ASTContext &Ctx,
12324                           Expr::SideEffectsKind AllowSideEffects,
12325                           EvalInfo &Info) {
12326   if (!E->getType()->isIntegralOrEnumerationType())
12327     return false;
12328 
12329   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info) ||
12330       !ExprResult.Val.isInt() ||
12331       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12332     return false;
12333 
12334   return true;
12335 }
12336 
12337 static bool EvaluateAsFixedPoint(const Expr *E, Expr::EvalResult &ExprResult,
12338                                  const ASTContext &Ctx,
12339                                  Expr::SideEffectsKind AllowSideEffects,
12340                                  EvalInfo &Info) {
12341   if (!E->getType()->isFixedPointType())
12342     return false;
12343 
12344   if (!::EvaluateAsRValue(E, ExprResult, Ctx, Info))
12345     return false;
12346 
12347   if (!ExprResult.Val.isFixedPoint() ||
12348       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12349     return false;
12350 
12351   return true;
12352 }
12353 
12354 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
12355 /// any crazy technique (that has nothing to do with language standards) that
12356 /// we want to.  If this function returns true, it returns the folded constant
12357 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
12358 /// will be applied to the result.
12359 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
12360                             bool InConstantContext) const {
12361   assert(!isValueDependent() &&
12362          "Expression evaluator can't be called on a dependent expression.");
12363   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12364   Info.InConstantContext = InConstantContext;
12365   return ::EvaluateAsRValue(this, Result, Ctx, Info);
12366 }
12367 
12368 bool Expr::EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
12369                                       bool InConstantContext) const {
12370   assert(!isValueDependent() &&
12371          "Expression evaluator can't be called on a dependent expression.");
12372   EvalResult Scratch;
12373   return EvaluateAsRValue(Scratch, Ctx, InConstantContext) &&
12374          HandleConversionToBool(Scratch.Val, Result);
12375 }
12376 
12377 bool Expr::EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
12378                          SideEffectsKind AllowSideEffects,
12379                          bool InConstantContext) const {
12380   assert(!isValueDependent() &&
12381          "Expression evaluator can't be called on a dependent expression.");
12382   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12383   Info.InConstantContext = InConstantContext;
12384   return ::EvaluateAsInt(this, Result, Ctx, AllowSideEffects, Info);
12385 }
12386 
12387 bool Expr::EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
12388                                 SideEffectsKind AllowSideEffects,
12389                                 bool InConstantContext) const {
12390   assert(!isValueDependent() &&
12391          "Expression evaluator can't be called on a dependent expression.");
12392   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
12393   Info.InConstantContext = InConstantContext;
12394   return ::EvaluateAsFixedPoint(this, Result, Ctx, AllowSideEffects, Info);
12395 }
12396 
12397 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
12398                            SideEffectsKind AllowSideEffects,
12399                            bool InConstantContext) const {
12400   assert(!isValueDependent() &&
12401          "Expression evaluator can't be called on a dependent expression.");
12402 
12403   if (!getType()->isRealFloatingType())
12404     return false;
12405 
12406   EvalResult ExprResult;
12407   if (!EvaluateAsRValue(ExprResult, Ctx, InConstantContext) ||
12408       !ExprResult.Val.isFloat() ||
12409       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
12410     return false;
12411 
12412   Result = ExprResult.Val.getFloat();
12413   return true;
12414 }
12415 
12416 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
12417                             bool InConstantContext) const {
12418   assert(!isValueDependent() &&
12419          "Expression evaluator can't be called on a dependent expression.");
12420 
12421   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
12422   Info.InConstantContext = InConstantContext;
12423   LValue LV;
12424   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
12425       !CheckLValueConstantExpression(Info, getExprLoc(),
12426                                      Ctx.getLValueReferenceType(getType()), LV,
12427                                      Expr::EvaluateForCodeGen))
12428     return false;
12429 
12430   LV.moveInto(Result.Val);
12431   return true;
12432 }
12433 
12434 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
12435                                   const ASTContext &Ctx) const {
12436   assert(!isValueDependent() &&
12437          "Expression evaluator can't be called on a dependent expression.");
12438 
12439   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
12440   EvalInfo Info(Ctx, Result, EM);
12441   Info.InConstantContext = true;
12442 
12443   if (!::Evaluate(Result.Val, Info, this))
12444     return false;
12445 
12446   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
12447                                  Usage);
12448 }
12449 
12450 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
12451                                  const VarDecl *VD,
12452                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
12453   assert(!isValueDependent() &&
12454          "Expression evaluator can't be called on a dependent expression.");
12455 
12456   // FIXME: Evaluating initializers for large array and record types can cause
12457   // performance problems. Only do so in C++11 for now.
12458   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
12459       !Ctx.getLangOpts().CPlusPlus11)
12460     return false;
12461 
12462   Expr::EvalStatus EStatus;
12463   EStatus.Diag = &Notes;
12464 
12465   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
12466                                       ? EvalInfo::EM_ConstantExpression
12467                                       : EvalInfo::EM_ConstantFold);
12468   InitInfo.setEvaluatingDecl(VD, Value);
12469   InitInfo.InConstantContext = true;
12470 
12471   LValue LVal;
12472   LVal.set(VD);
12473 
12474   // C++11 [basic.start.init]p2:
12475   //  Variables with static storage duration or thread storage duration shall be
12476   //  zero-initialized before any other initialization takes place.
12477   // This behavior is not present in C.
12478   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
12479       !VD->getType()->isReferenceType()) {
12480     ImplicitValueInitExpr VIE(VD->getType());
12481     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
12482                          /*AllowNonLiteralTypes=*/true))
12483       return false;
12484   }
12485 
12486   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
12487                        /*AllowNonLiteralTypes=*/true) ||
12488       EStatus.HasSideEffects)
12489     return false;
12490 
12491   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
12492                                  Value);
12493 }
12494 
12495 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
12496 /// constant folded, but discard the result.
12497 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
12498   assert(!isValueDependent() &&
12499          "Expression evaluator can't be called on a dependent expression.");
12500 
12501   EvalResult Result;
12502   return EvaluateAsRValue(Result, Ctx, /* in constant context */ true) &&
12503          !hasUnacceptableSideEffect(Result, SEK);
12504 }
12505 
12506 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
12507                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12508   assert(!isValueDependent() &&
12509          "Expression evaluator can't be called on a dependent expression.");
12510 
12511   EvalResult EVResult;
12512   EVResult.Diag = Diag;
12513   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12514   Info.InConstantContext = true;
12515 
12516   bool Result = ::EvaluateAsRValue(this, EVResult, Ctx, Info);
12517   (void)Result;
12518   assert(Result && "Could not evaluate expression");
12519   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12520 
12521   return EVResult.Val.getInt();
12522 }
12523 
12524 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
12525     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
12526   assert(!isValueDependent() &&
12527          "Expression evaluator can't be called on a dependent expression.");
12528 
12529   EvalResult EVResult;
12530   EVResult.Diag = Diag;
12531   EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12532   Info.InConstantContext = true;
12533   Info.CheckingForUndefinedBehavior = true;
12534 
12535   bool Result = ::EvaluateAsRValue(Info, this, EVResult.Val);
12536   (void)Result;
12537   assert(Result && "Could not evaluate expression");
12538   assert(EVResult.Val.isInt() && "Expression did not evaluate to integer");
12539 
12540   return EVResult.Val.getInt();
12541 }
12542 
12543 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
12544   assert(!isValueDependent() &&
12545          "Expression evaluator can't be called on a dependent expression.");
12546 
12547   bool IsConst;
12548   EvalResult EVResult;
12549   if (!FastEvaluateAsRValue(this, EVResult, Ctx, IsConst)) {
12550     EvalInfo Info(Ctx, EVResult, EvalInfo::EM_IgnoreSideEffects);
12551     Info.CheckingForUndefinedBehavior = true;
12552     (void)::EvaluateAsRValue(Info, this, EVResult.Val);
12553   }
12554 }
12555 
12556 bool Expr::EvalResult::isGlobalLValue() const {
12557   assert(Val.isLValue());
12558   return IsGlobalLValue(Val.getLValueBase());
12559 }
12560 
12561 
12562 /// isIntegerConstantExpr - this recursive routine will test if an expression is
12563 /// an integer constant expression.
12564 
12565 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
12566 /// comma, etc
12567 
12568 // CheckICE - This function does the fundamental ICE checking: the returned
12569 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
12570 // and a (possibly null) SourceLocation indicating the location of the problem.
12571 //
12572 // Note that to reduce code duplication, this helper does no evaluation
12573 // itself; the caller checks whether the expression is evaluatable, and
12574 // in the rare cases where CheckICE actually cares about the evaluated
12575 // value, it calls into Evaluate.
12576 
12577 namespace {
12578 
12579 enum ICEKind {
12580   /// This expression is an ICE.
12581   IK_ICE,
12582   /// This expression is not an ICE, but if it isn't evaluated, it's
12583   /// a legal subexpression for an ICE. This return value is used to handle
12584   /// the comma operator in C99 mode, and non-constant subexpressions.
12585   IK_ICEIfUnevaluated,
12586   /// This expression is not an ICE, and is not a legal subexpression for one.
12587   IK_NotICE
12588 };
12589 
12590 struct ICEDiag {
12591   ICEKind Kind;
12592   SourceLocation Loc;
12593 
12594   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
12595 };
12596 
12597 }
12598 
12599 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
12600 
12601 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
12602 
12603 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
12604   Expr::EvalResult EVResult;
12605   Expr::EvalStatus Status;
12606   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
12607 
12608   Info.InConstantContext = true;
12609   if (!::EvaluateAsRValue(E, EVResult, Ctx, Info) || EVResult.HasSideEffects ||
12610       !EVResult.Val.isInt())
12611     return ICEDiag(IK_NotICE, E->getBeginLoc());
12612 
12613   return NoDiag();
12614 }
12615 
12616 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
12617   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
12618   if (!E->getType()->isIntegralOrEnumerationType())
12619     return ICEDiag(IK_NotICE, E->getBeginLoc());
12620 
12621   switch (E->getStmtClass()) {
12622 #define ABSTRACT_STMT(Node)
12623 #define STMT(Node, Base) case Expr::Node##Class:
12624 #define EXPR(Node, Base)
12625 #include "clang/AST/StmtNodes.inc"
12626   case Expr::PredefinedExprClass:
12627   case Expr::FloatingLiteralClass:
12628   case Expr::ImaginaryLiteralClass:
12629   case Expr::StringLiteralClass:
12630   case Expr::ArraySubscriptExprClass:
12631   case Expr::OMPArraySectionExprClass:
12632   case Expr::MemberExprClass:
12633   case Expr::CompoundAssignOperatorClass:
12634   case Expr::CompoundLiteralExprClass:
12635   case Expr::ExtVectorElementExprClass:
12636   case Expr::DesignatedInitExprClass:
12637   case Expr::ArrayInitLoopExprClass:
12638   case Expr::ArrayInitIndexExprClass:
12639   case Expr::NoInitExprClass:
12640   case Expr::DesignatedInitUpdateExprClass:
12641   case Expr::ImplicitValueInitExprClass:
12642   case Expr::ParenListExprClass:
12643   case Expr::VAArgExprClass:
12644   case Expr::AddrLabelExprClass:
12645   case Expr::StmtExprClass:
12646   case Expr::CXXMemberCallExprClass:
12647   case Expr::CUDAKernelCallExprClass:
12648   case Expr::CXXDynamicCastExprClass:
12649   case Expr::CXXTypeidExprClass:
12650   case Expr::CXXUuidofExprClass:
12651   case Expr::MSPropertyRefExprClass:
12652   case Expr::MSPropertySubscriptExprClass:
12653   case Expr::CXXNullPtrLiteralExprClass:
12654   case Expr::UserDefinedLiteralClass:
12655   case Expr::CXXThisExprClass:
12656   case Expr::CXXThrowExprClass:
12657   case Expr::CXXNewExprClass:
12658   case Expr::CXXDeleteExprClass:
12659   case Expr::CXXPseudoDestructorExprClass:
12660   case Expr::UnresolvedLookupExprClass:
12661   case Expr::TypoExprClass:
12662   case Expr::DependentScopeDeclRefExprClass:
12663   case Expr::CXXConstructExprClass:
12664   case Expr::CXXInheritedCtorInitExprClass:
12665   case Expr::CXXStdInitializerListExprClass:
12666   case Expr::CXXBindTemporaryExprClass:
12667   case Expr::ExprWithCleanupsClass:
12668   case Expr::CXXTemporaryObjectExprClass:
12669   case Expr::CXXUnresolvedConstructExprClass:
12670   case Expr::CXXDependentScopeMemberExprClass:
12671   case Expr::UnresolvedMemberExprClass:
12672   case Expr::ObjCStringLiteralClass:
12673   case Expr::ObjCBoxedExprClass:
12674   case Expr::ObjCArrayLiteralClass:
12675   case Expr::ObjCDictionaryLiteralClass:
12676   case Expr::ObjCEncodeExprClass:
12677   case Expr::ObjCMessageExprClass:
12678   case Expr::ObjCSelectorExprClass:
12679   case Expr::ObjCProtocolExprClass:
12680   case Expr::ObjCIvarRefExprClass:
12681   case Expr::ObjCPropertyRefExprClass:
12682   case Expr::ObjCSubscriptRefExprClass:
12683   case Expr::ObjCIsaExprClass:
12684   case Expr::ObjCAvailabilityCheckExprClass:
12685   case Expr::ShuffleVectorExprClass:
12686   case Expr::ConvertVectorExprClass:
12687   case Expr::BlockExprClass:
12688   case Expr::NoStmtClass:
12689   case Expr::OpaqueValueExprClass:
12690   case Expr::PackExpansionExprClass:
12691   case Expr::SubstNonTypeTemplateParmPackExprClass:
12692   case Expr::FunctionParmPackExprClass:
12693   case Expr::AsTypeExprClass:
12694   case Expr::ObjCIndirectCopyRestoreExprClass:
12695   case Expr::MaterializeTemporaryExprClass:
12696   case Expr::PseudoObjectExprClass:
12697   case Expr::AtomicExprClass:
12698   case Expr::LambdaExprClass:
12699   case Expr::CXXFoldExprClass:
12700   case Expr::CoawaitExprClass:
12701   case Expr::DependentCoawaitExprClass:
12702   case Expr::CoyieldExprClass:
12703     return ICEDiag(IK_NotICE, E->getBeginLoc());
12704 
12705   case Expr::InitListExprClass: {
12706     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
12707     // form "T x = { a };" is equivalent to "T x = a;".
12708     // Unless we're initializing a reference, T is a scalar as it is known to be
12709     // of integral or enumeration type.
12710     if (E->isRValue())
12711       if (cast<InitListExpr>(E)->getNumInits() == 1)
12712         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
12713     return ICEDiag(IK_NotICE, E->getBeginLoc());
12714   }
12715 
12716   case Expr::SizeOfPackExprClass:
12717   case Expr::GNUNullExprClass:
12718   case Expr::SourceLocExprClass:
12719     return NoDiag();
12720 
12721   case Expr::SubstNonTypeTemplateParmExprClass:
12722     return
12723       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
12724 
12725   case Expr::ConstantExprClass:
12726     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
12727 
12728   case Expr::ParenExprClass:
12729     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
12730   case Expr::GenericSelectionExprClass:
12731     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
12732   case Expr::IntegerLiteralClass:
12733   case Expr::FixedPointLiteralClass:
12734   case Expr::CharacterLiteralClass:
12735   case Expr::ObjCBoolLiteralExprClass:
12736   case Expr::CXXBoolLiteralExprClass:
12737   case Expr::CXXScalarValueInitExprClass:
12738   case Expr::TypeTraitExprClass:
12739   case Expr::ArrayTypeTraitExprClass:
12740   case Expr::ExpressionTraitExprClass:
12741   case Expr::CXXNoexceptExprClass:
12742     return NoDiag();
12743   case Expr::CallExprClass:
12744   case Expr::CXXOperatorCallExprClass: {
12745     // C99 6.6/3 allows function calls within unevaluated subexpressions of
12746     // constant expressions, but they can never be ICEs because an ICE cannot
12747     // contain an operand of (pointer to) function type.
12748     const CallExpr *CE = cast<CallExpr>(E);
12749     if (CE->getBuiltinCallee())
12750       return CheckEvalInICE(E, Ctx);
12751     return ICEDiag(IK_NotICE, E->getBeginLoc());
12752   }
12753   case Expr::DeclRefExprClass: {
12754     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
12755       return NoDiag();
12756     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
12757     if (Ctx.getLangOpts().CPlusPlus &&
12758         D && IsConstNonVolatile(D->getType())) {
12759       // Parameter variables are never constants.  Without this check,
12760       // getAnyInitializer() can find a default argument, which leads
12761       // to chaos.
12762       if (isa<ParmVarDecl>(D))
12763         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12764 
12765       // C++ 7.1.5.1p2
12766       //   A variable of non-volatile const-qualified integral or enumeration
12767       //   type initialized by an ICE can be used in ICEs.
12768       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
12769         if (!Dcl->getType()->isIntegralOrEnumerationType())
12770           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12771 
12772         const VarDecl *VD;
12773         // Look for a declaration of this variable that has an initializer, and
12774         // check whether it is an ICE.
12775         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
12776           return NoDiag();
12777         else
12778           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
12779       }
12780     }
12781     return ICEDiag(IK_NotICE, E->getBeginLoc());
12782   }
12783   case Expr::UnaryOperatorClass: {
12784     const UnaryOperator *Exp = cast<UnaryOperator>(E);
12785     switch (Exp->getOpcode()) {
12786     case UO_PostInc:
12787     case UO_PostDec:
12788     case UO_PreInc:
12789     case UO_PreDec:
12790     case UO_AddrOf:
12791     case UO_Deref:
12792     case UO_Coawait:
12793       // C99 6.6/3 allows increment and decrement within unevaluated
12794       // subexpressions of constant expressions, but they can never be ICEs
12795       // because an ICE cannot contain an lvalue operand.
12796       return ICEDiag(IK_NotICE, E->getBeginLoc());
12797     case UO_Extension:
12798     case UO_LNot:
12799     case UO_Plus:
12800     case UO_Minus:
12801     case UO_Not:
12802     case UO_Real:
12803     case UO_Imag:
12804       return CheckICE(Exp->getSubExpr(), Ctx);
12805     }
12806     llvm_unreachable("invalid unary operator class");
12807   }
12808   case Expr::OffsetOfExprClass: {
12809     // Note that per C99, offsetof must be an ICE. And AFAIK, using
12810     // EvaluateAsRValue matches the proposed gcc behavior for cases like
12811     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
12812     // compliance: we should warn earlier for offsetof expressions with
12813     // array subscripts that aren't ICEs, and if the array subscripts
12814     // are ICEs, the value of the offsetof must be an integer constant.
12815     return CheckEvalInICE(E, Ctx);
12816   }
12817   case Expr::UnaryExprOrTypeTraitExprClass: {
12818     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
12819     if ((Exp->getKind() ==  UETT_SizeOf) &&
12820         Exp->getTypeOfArgument()->isVariableArrayType())
12821       return ICEDiag(IK_NotICE, E->getBeginLoc());
12822     return NoDiag();
12823   }
12824   case Expr::BinaryOperatorClass: {
12825     const BinaryOperator *Exp = cast<BinaryOperator>(E);
12826     switch (Exp->getOpcode()) {
12827     case BO_PtrMemD:
12828     case BO_PtrMemI:
12829     case BO_Assign:
12830     case BO_MulAssign:
12831     case BO_DivAssign:
12832     case BO_RemAssign:
12833     case BO_AddAssign:
12834     case BO_SubAssign:
12835     case BO_ShlAssign:
12836     case BO_ShrAssign:
12837     case BO_AndAssign:
12838     case BO_XorAssign:
12839     case BO_OrAssign:
12840       // C99 6.6/3 allows assignments within unevaluated subexpressions of
12841       // constant expressions, but they can never be ICEs because an ICE cannot
12842       // contain an lvalue operand.
12843       return ICEDiag(IK_NotICE, E->getBeginLoc());
12844 
12845     case BO_Mul:
12846     case BO_Div:
12847     case BO_Rem:
12848     case BO_Add:
12849     case BO_Sub:
12850     case BO_Shl:
12851     case BO_Shr:
12852     case BO_LT:
12853     case BO_GT:
12854     case BO_LE:
12855     case BO_GE:
12856     case BO_EQ:
12857     case BO_NE:
12858     case BO_And:
12859     case BO_Xor:
12860     case BO_Or:
12861     case BO_Comma:
12862     case BO_Cmp: {
12863       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12864       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12865       if (Exp->getOpcode() == BO_Div ||
12866           Exp->getOpcode() == BO_Rem) {
12867         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
12868         // we don't evaluate one.
12869         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
12870           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
12871           if (REval == 0)
12872             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12873           if (REval.isSigned() && REval.isAllOnesValue()) {
12874             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
12875             if (LEval.isMinSignedValue())
12876               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12877           }
12878         }
12879       }
12880       if (Exp->getOpcode() == BO_Comma) {
12881         if (Ctx.getLangOpts().C99) {
12882           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
12883           // if it isn't evaluated.
12884           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
12885             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
12886         } else {
12887           // In both C89 and C++, commas in ICEs are illegal.
12888           return ICEDiag(IK_NotICE, E->getBeginLoc());
12889         }
12890       }
12891       return Worst(LHSResult, RHSResult);
12892     }
12893     case BO_LAnd:
12894     case BO_LOr: {
12895       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
12896       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
12897       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
12898         // Rare case where the RHS has a comma "side-effect"; we need
12899         // to actually check the condition to see whether the side
12900         // with the comma is evaluated.
12901         if ((Exp->getOpcode() == BO_LAnd) !=
12902             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
12903           return RHSResult;
12904         return NoDiag();
12905       }
12906 
12907       return Worst(LHSResult, RHSResult);
12908     }
12909     }
12910     llvm_unreachable("invalid binary operator kind");
12911   }
12912   case Expr::ImplicitCastExprClass:
12913   case Expr::CStyleCastExprClass:
12914   case Expr::CXXFunctionalCastExprClass:
12915   case Expr::CXXStaticCastExprClass:
12916   case Expr::CXXReinterpretCastExprClass:
12917   case Expr::CXXConstCastExprClass:
12918   case Expr::ObjCBridgedCastExprClass: {
12919     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
12920     if (isa<ExplicitCastExpr>(E)) {
12921       if (const FloatingLiteral *FL
12922             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
12923         unsigned DestWidth = Ctx.getIntWidth(E->getType());
12924         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
12925         APSInt IgnoredVal(DestWidth, !DestSigned);
12926         bool Ignored;
12927         // If the value does not fit in the destination type, the behavior is
12928         // undefined, so we are not required to treat it as a constant
12929         // expression.
12930         if (FL->getValue().convertToInteger(IgnoredVal,
12931                                             llvm::APFloat::rmTowardZero,
12932                                             &Ignored) & APFloat::opInvalidOp)
12933           return ICEDiag(IK_NotICE, E->getBeginLoc());
12934         return NoDiag();
12935       }
12936     }
12937     switch (cast<CastExpr>(E)->getCastKind()) {
12938     case CK_LValueToRValue:
12939     case CK_AtomicToNonAtomic:
12940     case CK_NonAtomicToAtomic:
12941     case CK_NoOp:
12942     case CK_IntegralToBoolean:
12943     case CK_IntegralCast:
12944       return CheckICE(SubExpr, Ctx);
12945     default:
12946       return ICEDiag(IK_NotICE, E->getBeginLoc());
12947     }
12948   }
12949   case Expr::BinaryConditionalOperatorClass: {
12950     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
12951     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
12952     if (CommonResult.Kind == IK_NotICE) return CommonResult;
12953     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12954     if (FalseResult.Kind == IK_NotICE) return FalseResult;
12955     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
12956     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
12957         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
12958     return FalseResult;
12959   }
12960   case Expr::ConditionalOperatorClass: {
12961     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
12962     // If the condition (ignoring parens) is a __builtin_constant_p call,
12963     // then only the true side is actually considered in an integer constant
12964     // expression, and it is fully evaluated.  This is an important GNU
12965     // extension.  See GCC PR38377 for discussion.
12966     if (const CallExpr *CallCE
12967         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
12968       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
12969         return CheckEvalInICE(E, Ctx);
12970     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
12971     if (CondResult.Kind == IK_NotICE)
12972       return CondResult;
12973 
12974     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
12975     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
12976 
12977     if (TrueResult.Kind == IK_NotICE)
12978       return TrueResult;
12979     if (FalseResult.Kind == IK_NotICE)
12980       return FalseResult;
12981     if (CondResult.Kind == IK_ICEIfUnevaluated)
12982       return CondResult;
12983     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
12984       return NoDiag();
12985     // Rare case where the diagnostics depend on which side is evaluated
12986     // Note that if we get here, CondResult is 0, and at least one of
12987     // TrueResult and FalseResult is non-zero.
12988     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
12989       return FalseResult;
12990     return TrueResult;
12991   }
12992   case Expr::CXXDefaultArgExprClass:
12993     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
12994   case Expr::CXXDefaultInitExprClass:
12995     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
12996   case Expr::ChooseExprClass: {
12997     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
12998   }
12999   case Expr::BuiltinBitCastExprClass: {
13000     if (!checkBitCastConstexprEligibility(nullptr, Ctx, cast<CastExpr>(E)))
13001       return ICEDiag(IK_NotICE, E->getBeginLoc());
13002     return CheckICE(cast<CastExpr>(E)->getSubExpr(), Ctx);
13003   }
13004   }
13005 
13006   llvm_unreachable("Invalid StmtClass!");
13007 }
13008 
13009 /// Evaluate an expression as a C++11 integral constant expression.
13010 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
13011                                                     const Expr *E,
13012                                                     llvm::APSInt *Value,
13013                                                     SourceLocation *Loc) {
13014   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
13015     if (Loc) *Loc = E->getExprLoc();
13016     return false;
13017   }
13018 
13019   APValue Result;
13020   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
13021     return false;
13022 
13023   if (!Result.isInt()) {
13024     if (Loc) *Loc = E->getExprLoc();
13025     return false;
13026   }
13027 
13028   if (Value) *Value = Result.getInt();
13029   return true;
13030 }
13031 
13032 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
13033                                  SourceLocation *Loc) const {
13034   assert(!isValueDependent() &&
13035          "Expression evaluator can't be called on a dependent expression.");
13036 
13037   if (Ctx.getLangOpts().CPlusPlus11)
13038     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
13039 
13040   ICEDiag D = CheckICE(this, Ctx);
13041   if (D.Kind != IK_ICE) {
13042     if (Loc) *Loc = D.Loc;
13043     return false;
13044   }
13045   return true;
13046 }
13047 
13048 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
13049                                  SourceLocation *Loc, bool isEvaluated) const {
13050   assert(!isValueDependent() &&
13051          "Expression evaluator can't be called on a dependent expression.");
13052 
13053   if (Ctx.getLangOpts().CPlusPlus11)
13054     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
13055 
13056   if (!isIntegerConstantExpr(Ctx, Loc))
13057     return false;
13058 
13059   // The only possible side-effects here are due to UB discovered in the
13060   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
13061   // required to treat the expression as an ICE, so we produce the folded
13062   // value.
13063   EvalResult ExprResult;
13064   Expr::EvalStatus Status;
13065   EvalInfo Info(Ctx, Status, EvalInfo::EM_IgnoreSideEffects);
13066   Info.InConstantContext = true;
13067 
13068   if (!::EvaluateAsInt(this, ExprResult, Ctx, SE_AllowSideEffects, Info))
13069     llvm_unreachable("ICE cannot be evaluated!");
13070 
13071   Value = ExprResult.Val.getInt();
13072   return true;
13073 }
13074 
13075 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
13076   assert(!isValueDependent() &&
13077          "Expression evaluator can't be called on a dependent expression.");
13078 
13079   return CheckICE(this, Ctx).Kind == IK_ICE;
13080 }
13081 
13082 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
13083                                SourceLocation *Loc) const {
13084   assert(!isValueDependent() &&
13085          "Expression evaluator can't be called on a dependent expression.");
13086 
13087   // We support this checking in C++98 mode in order to diagnose compatibility
13088   // issues.
13089   assert(Ctx.getLangOpts().CPlusPlus);
13090 
13091   // Build evaluation settings.
13092   Expr::EvalStatus Status;
13093   SmallVector<PartialDiagnosticAt, 8> Diags;
13094   Status.Diag = &Diags;
13095   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
13096 
13097   APValue Scratch;
13098   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
13099 
13100   if (!Diags.empty()) {
13101     IsConstExpr = false;
13102     if (Loc) *Loc = Diags[0].first;
13103   } else if (!IsConstExpr) {
13104     // FIXME: This shouldn't happen.
13105     if (Loc) *Loc = getExprLoc();
13106   }
13107 
13108   return IsConstExpr;
13109 }
13110 
13111 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
13112                                     const FunctionDecl *Callee,
13113                                     ArrayRef<const Expr*> Args,
13114                                     const Expr *This) const {
13115   assert(!isValueDependent() &&
13116          "Expression evaluator can't be called on a dependent expression.");
13117 
13118   Expr::EvalStatus Status;
13119   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
13120   Info.InConstantContext = true;
13121 
13122   LValue ThisVal;
13123   const LValue *ThisPtr = nullptr;
13124   if (This) {
13125 #ifndef NDEBUG
13126     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
13127     assert(MD && "Don't provide `this` for non-methods.");
13128     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
13129 #endif
13130     if (EvaluateObjectArgument(Info, This, ThisVal))
13131       ThisPtr = &ThisVal;
13132     if (Info.EvalStatus.HasSideEffects)
13133       return false;
13134   }
13135 
13136   ArgVector ArgValues(Args.size());
13137   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
13138        I != E; ++I) {
13139     if ((*I)->isValueDependent() ||
13140         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
13141       // If evaluation fails, throw away the argument entirely.
13142       ArgValues[I - Args.begin()] = APValue();
13143     if (Info.EvalStatus.HasSideEffects)
13144       return false;
13145   }
13146 
13147   // Build fake call to Callee.
13148   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
13149                        ArgValues.data());
13150   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
13151 }
13152 
13153 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
13154                                    SmallVectorImpl<
13155                                      PartialDiagnosticAt> &Diags) {
13156   // FIXME: It would be useful to check constexpr function templates, but at the
13157   // moment the constant expression evaluator cannot cope with the non-rigorous
13158   // ASTs which we build for dependent expressions.
13159   if (FD->isDependentContext())
13160     return true;
13161 
13162   Expr::EvalStatus Status;
13163   Status.Diag = &Diags;
13164 
13165   EvalInfo Info(FD->getASTContext(), Status, EvalInfo::EM_ConstantExpression);
13166   Info.InConstantContext = true;
13167   Info.CheckingPotentialConstantExpression = true;
13168 
13169   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
13170   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
13171 
13172   // Fabricate an arbitrary expression on the stack and pretend that it
13173   // is a temporary being used as the 'this' pointer.
13174   LValue This;
13175   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
13176   This.set({&VIE, Info.CurrentCall->Index});
13177 
13178   ArrayRef<const Expr*> Args;
13179 
13180   APValue Scratch;
13181   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
13182     // Evaluate the call as a constant initializer, to allow the construction
13183     // of objects of non-literal types.
13184     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
13185     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
13186   } else {
13187     SourceLocation Loc = FD->getLocation();
13188     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
13189                        Args, FD->getBody(), Info, Scratch, nullptr);
13190   }
13191 
13192   return Diags.empty();
13193 }
13194 
13195 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
13196                                               const FunctionDecl *FD,
13197                                               SmallVectorImpl<
13198                                                 PartialDiagnosticAt> &Diags) {
13199   assert(!E->isValueDependent() &&
13200          "Expression evaluator can't be called on a dependent expression.");
13201 
13202   Expr::EvalStatus Status;
13203   Status.Diag = &Diags;
13204 
13205   EvalInfo Info(FD->getASTContext(), Status,
13206                 EvalInfo::EM_ConstantExpressionUnevaluated);
13207   Info.InConstantContext = true;
13208   Info.CheckingPotentialConstantExpression = true;
13209 
13210   // Fabricate a call stack frame to give the arguments a plausible cover story.
13211   ArrayRef<const Expr*> Args;
13212   ArgVector ArgValues(0);
13213   bool Success = EvaluateArgs(Args, ArgValues, Info, FD);
13214   (void)Success;
13215   assert(Success &&
13216          "Failed to set up arguments for potential constant evaluation");
13217   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
13218 
13219   APValue ResultScratch;
13220   Evaluate(ResultScratch, Info, E);
13221   return Diags.empty();
13222 }
13223 
13224 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
13225                                  unsigned Type) const {
13226   if (!getType()->isPointerType())
13227     return false;
13228 
13229   Expr::EvalStatus Status;
13230   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
13231   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
13232 }
13233