1 //===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Expr constant evaluator.
11 //
12 // Constant expression evaluation produces four main results:
13 //
14 //  * A success/failure flag indicating whether constant folding was successful.
15 //    This is the 'bool' return value used by most of the code in this file. A
16 //    'false' return value indicates that constant folding has failed, and any
17 //    appropriate diagnostic has already been produced.
18 //
19 //  * An evaluated result, valid only if constant folding has not failed.
20 //
21 //  * A flag indicating if evaluation encountered (unevaluated) side-effects.
22 //    These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23 //    where it is possible to determine the evaluated result regardless.
24 //
25 //  * A set of notes indicating why the evaluation was not a constant expression
26 //    (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27 //    too, why the expression could not be folded.
28 //
29 // If we are checking for a potential constant expression, failure to constant
30 // fold a potential constant sub-expression will be indicated by a 'false'
31 // return value (the expression could not be folded) and no diagnostic (the
32 // expression is not necessarily non-constant).
33 //
34 //===----------------------------------------------------------------------===//
35 
36 #include "clang/AST/APValue.h"
37 #include "clang/AST/ASTContext.h"
38 #include "clang/AST/ASTDiagnostic.h"
39 #include "clang/AST/ASTLambda.h"
40 #include "clang/AST/CharUnits.h"
41 #include "clang/AST/Expr.h"
42 #include "clang/AST/OSLog.h"
43 #include "clang/AST/RecordLayout.h"
44 #include "clang/AST/StmtVisitor.h"
45 #include "clang/AST/TypeLoc.h"
46 #include "clang/Basic/Builtins.h"
47 #include "clang/Basic/TargetInfo.h"
48 #include "llvm/Support/raw_ostream.h"
49 #include <cstring>
50 #include <functional>
51 
52 #define DEBUG_TYPE "exprconstant"
53 
54 using namespace clang;
55 using llvm::APSInt;
56 using llvm::APFloat;
57 
58 static bool IsGlobalLValue(APValue::LValueBase B);
59 
60 namespace {
61   struct LValue;
62   struct CallStackFrame;
63   struct EvalInfo;
64 
65   static QualType getType(APValue::LValueBase B) {
66     if (!B) return QualType();
67     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
68       // FIXME: It's unclear where we're supposed to take the type from, and
69       // this actually matters for arrays of unknown bound. Eg:
70       //
71       // extern int arr[]; void f() { extern int arr[3]; };
72       // constexpr int *p = &arr[1]; // valid?
73       //
74       // For now, we take the array bound from the most recent declaration.
75       for (auto *Redecl = cast<ValueDecl>(D->getMostRecentDecl()); Redecl;
76            Redecl = cast_or_null<ValueDecl>(Redecl->getPreviousDecl())) {
77         QualType T = Redecl->getType();
78         if (!T->isIncompleteArrayType())
79           return T;
80       }
81       return D->getType();
82     }
83 
84     const Expr *Base = B.get<const Expr*>();
85 
86     // For a materialized temporary, the type of the temporary we materialized
87     // may not be the type of the expression.
88     if (const MaterializeTemporaryExpr *MTE =
89             dyn_cast<MaterializeTemporaryExpr>(Base)) {
90       SmallVector<const Expr *, 2> CommaLHSs;
91       SmallVector<SubobjectAdjustment, 2> Adjustments;
92       const Expr *Temp = MTE->GetTemporaryExpr();
93       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
94                                                                Adjustments);
95       // Keep any cv-qualifiers from the reference if we generated a temporary
96       // for it directly. Otherwise use the type after adjustment.
97       if (!Adjustments.empty())
98         return Inner->getType();
99     }
100 
101     return Base->getType();
102   }
103 
104   /// Get an LValue path entry, which is known to not be an array index, as a
105   /// field or base class.
106   static
107   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
108     APValue::BaseOrMemberType Value;
109     Value.setFromOpaqueValue(E.BaseOrMember);
110     return Value;
111   }
112 
113   /// Get an LValue path entry, which is known to not be an array index, as a
114   /// field declaration.
115   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
116     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
117   }
118   /// Get an LValue path entry, which is known to not be an array index, as a
119   /// base class declaration.
120   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
121     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
122   }
123   /// Determine whether this LValue path entry for a base class names a virtual
124   /// base class.
125   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
126     return getAsBaseOrMember(E).getInt();
127   }
128 
129   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
130   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
131     const FunctionDecl *Callee = CE->getDirectCallee();
132     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
133   }
134 
135   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
136   /// This will look through a single cast.
137   ///
138   /// Returns null if we couldn't unwrap a function with alloc_size.
139   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
140     if (!E->getType()->isPointerType())
141       return nullptr;
142 
143     E = E->IgnoreParens();
144     // If we're doing a variable assignment from e.g. malloc(N), there will
145     // probably be a cast of some kind. In exotic cases, we might also see a
146     // top-level ExprWithCleanups. Ignore them either way.
147     if (const auto *FE = dyn_cast<FullExpr>(E))
148       E = FE->getSubExpr()->IgnoreParens();
149 
150     if (const auto *Cast = dyn_cast<CastExpr>(E))
151       E = Cast->getSubExpr()->IgnoreParens();
152 
153     if (const auto *CE = dyn_cast<CallExpr>(E))
154       return getAllocSizeAttr(CE) ? CE : nullptr;
155     return nullptr;
156   }
157 
158   /// Determines whether or not the given Base contains a call to a function
159   /// with the alloc_size attribute.
160   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
161     const auto *E = Base.dyn_cast<const Expr *>();
162     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
163   }
164 
165   /// The bound to claim that an array of unknown bound has.
166   /// The value in MostDerivedArraySize is undefined in this case. So, set it
167   /// to an arbitrary value that's likely to loudly break things if it's used.
168   static const uint64_t AssumedSizeForUnsizedArray =
169       std::numeric_limits<uint64_t>::max() / 2;
170 
171   /// Determines if an LValue with the given LValueBase will have an unsized
172   /// array in its designator.
173   /// Find the path length and type of the most-derived subobject in the given
174   /// path, and find the size of the containing array, if any.
175   static unsigned
176   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
177                            ArrayRef<APValue::LValuePathEntry> Path,
178                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
179                            bool &FirstEntryIsUnsizedArray) {
180     // This only accepts LValueBases from APValues, and APValues don't support
181     // arrays that lack size info.
182     assert(!isBaseAnAllocSizeCall(Base) &&
183            "Unsized arrays shouldn't appear here");
184     unsigned MostDerivedLength = 0;
185     Type = getType(Base);
186 
187     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
188       if (Type->isArrayType()) {
189         const ArrayType *AT = Ctx.getAsArrayType(Type);
190         Type = AT->getElementType();
191         MostDerivedLength = I + 1;
192         IsArray = true;
193 
194         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
195           ArraySize = CAT->getSize().getZExtValue();
196         } else {
197           assert(I == 0 && "unexpected unsized array designator");
198           FirstEntryIsUnsizedArray = true;
199           ArraySize = AssumedSizeForUnsizedArray;
200         }
201       } else if (Type->isAnyComplexType()) {
202         const ComplexType *CT = Type->castAs<ComplexType>();
203         Type = CT->getElementType();
204         ArraySize = 2;
205         MostDerivedLength = I + 1;
206         IsArray = true;
207       } else if (const FieldDecl *FD = getAsField(Path[I])) {
208         Type = FD->getType();
209         ArraySize = 0;
210         MostDerivedLength = I + 1;
211         IsArray = false;
212       } else {
213         // Path[I] describes a base class.
214         ArraySize = 0;
215         IsArray = false;
216       }
217     }
218     return MostDerivedLength;
219   }
220 
221   // The order of this enum is important for diagnostics.
222   enum CheckSubobjectKind {
223     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
224     CSK_This, CSK_Real, CSK_Imag
225   };
226 
227   /// A path from a glvalue to a subobject of that glvalue.
228   struct SubobjectDesignator {
229     /// True if the subobject was named in a manner not supported by C++11. Such
230     /// lvalues can still be folded, but they are not core constant expressions
231     /// and we cannot perform lvalue-to-rvalue conversions on them.
232     unsigned Invalid : 1;
233 
234     /// Is this a pointer one past the end of an object?
235     unsigned IsOnePastTheEnd : 1;
236 
237     /// Indicator of whether the first entry is an unsized array.
238     unsigned FirstEntryIsAnUnsizedArray : 1;
239 
240     /// Indicator of whether the most-derived object is an array element.
241     unsigned MostDerivedIsArrayElement : 1;
242 
243     /// The length of the path to the most-derived object of which this is a
244     /// subobject.
245     unsigned MostDerivedPathLength : 28;
246 
247     /// The size of the array of which the most-derived object is an element.
248     /// This will always be 0 if the most-derived object is not an array
249     /// element. 0 is not an indicator of whether or not the most-derived object
250     /// is an array, however, because 0-length arrays are allowed.
251     ///
252     /// If the current array is an unsized array, the value of this is
253     /// undefined.
254     uint64_t MostDerivedArraySize;
255 
256     /// The type of the most derived object referred to by this address.
257     QualType MostDerivedType;
258 
259     typedef APValue::LValuePathEntry PathEntry;
260 
261     /// The entries on the path from the glvalue to the designated subobject.
262     SmallVector<PathEntry, 8> Entries;
263 
264     SubobjectDesignator() : Invalid(true) {}
265 
266     explicit SubobjectDesignator(QualType T)
267         : Invalid(false), IsOnePastTheEnd(false),
268           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
269           MostDerivedPathLength(0), MostDerivedArraySize(0),
270           MostDerivedType(T) {}
271 
272     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
273         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
274           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
275           MostDerivedPathLength(0), MostDerivedArraySize(0) {
276       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
277       if (!Invalid) {
278         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
279         ArrayRef<PathEntry> VEntries = V.getLValuePath();
280         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
281         if (V.getLValueBase()) {
282           bool IsArray = false;
283           bool FirstIsUnsizedArray = false;
284           MostDerivedPathLength = findMostDerivedSubobject(
285               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
286               MostDerivedType, IsArray, FirstIsUnsizedArray);
287           MostDerivedIsArrayElement = IsArray;
288           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
289         }
290       }
291     }
292 
293     void setInvalid() {
294       Invalid = true;
295       Entries.clear();
296     }
297 
298     /// Determine whether the most derived subobject is an array without a
299     /// known bound.
300     bool isMostDerivedAnUnsizedArray() const {
301       assert(!Invalid && "Calling this makes no sense on invalid designators");
302       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
303     }
304 
305     /// Determine what the most derived array's size is. Results in an assertion
306     /// failure if the most derived array lacks a size.
307     uint64_t getMostDerivedArraySize() const {
308       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
309       return MostDerivedArraySize;
310     }
311 
312     /// Determine whether this is a one-past-the-end pointer.
313     bool isOnePastTheEnd() const {
314       assert(!Invalid);
315       if (IsOnePastTheEnd)
316         return true;
317       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
318           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
319         return true;
320       return false;
321     }
322 
323     /// Get the range of valid index adjustments in the form
324     ///   {maximum value that can be subtracted from this pointer,
325     ///    maximum value that can be added to this pointer}
326     std::pair<uint64_t, uint64_t> validIndexAdjustments() {
327       if (Invalid || isMostDerivedAnUnsizedArray())
328         return {0, 0};
329 
330       // [expr.add]p4: For the purposes of these operators, a pointer to a
331       // nonarray object behaves the same as a pointer to the first element of
332       // an array of length one with the type of the object as its element type.
333       bool IsArray = MostDerivedPathLength == Entries.size() &&
334                      MostDerivedIsArrayElement;
335       uint64_t ArrayIndex =
336           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
337       uint64_t ArraySize =
338           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
339       return {ArrayIndex, ArraySize - ArrayIndex};
340     }
341 
342     /// Check that this refers to a valid subobject.
343     bool isValidSubobject() const {
344       if (Invalid)
345         return false;
346       return !isOnePastTheEnd();
347     }
348     /// Check that this refers to a valid subobject, and if not, produce a
349     /// relevant diagnostic and set the designator as invalid.
350     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
351 
352     /// Get the type of the designated object.
353     QualType getType(ASTContext &Ctx) const {
354       assert(!Invalid && "invalid designator has no subobject type");
355       return MostDerivedPathLength == Entries.size()
356                  ? MostDerivedType
357                  : Ctx.getRecordType(getAsBaseClass(Entries.back()));
358     }
359 
360     /// Update this designator to refer to the first element within this array.
361     void addArrayUnchecked(const ConstantArrayType *CAT) {
362       PathEntry Entry;
363       Entry.ArrayIndex = 0;
364       Entries.push_back(Entry);
365 
366       // This is a most-derived object.
367       MostDerivedType = CAT->getElementType();
368       MostDerivedIsArrayElement = true;
369       MostDerivedArraySize = CAT->getSize().getZExtValue();
370       MostDerivedPathLength = Entries.size();
371     }
372     /// Update this designator to refer to the first element within the array of
373     /// elements of type T. This is an array of unknown size.
374     void addUnsizedArrayUnchecked(QualType ElemTy) {
375       PathEntry Entry;
376       Entry.ArrayIndex = 0;
377       Entries.push_back(Entry);
378 
379       MostDerivedType = ElemTy;
380       MostDerivedIsArrayElement = true;
381       // The value in MostDerivedArraySize is undefined in this case. So, set it
382       // to an arbitrary value that's likely to loudly break things if it's
383       // used.
384       MostDerivedArraySize = AssumedSizeForUnsizedArray;
385       MostDerivedPathLength = Entries.size();
386     }
387     /// Update this designator to refer to the given base or member of this
388     /// object.
389     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
390       PathEntry Entry;
391       APValue::BaseOrMemberType Value(D, Virtual);
392       Entry.BaseOrMember = Value.getOpaqueValue();
393       Entries.push_back(Entry);
394 
395       // If this isn't a base class, it's a new most-derived object.
396       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
397         MostDerivedType = FD->getType();
398         MostDerivedIsArrayElement = false;
399         MostDerivedArraySize = 0;
400         MostDerivedPathLength = Entries.size();
401       }
402     }
403     /// Update this designator to refer to the given complex component.
404     void addComplexUnchecked(QualType EltTy, bool Imag) {
405       PathEntry Entry;
406       Entry.ArrayIndex = Imag;
407       Entries.push_back(Entry);
408 
409       // This is technically a most-derived object, though in practice this
410       // is unlikely to matter.
411       MostDerivedType = EltTy;
412       MostDerivedIsArrayElement = true;
413       MostDerivedArraySize = 2;
414       MostDerivedPathLength = Entries.size();
415     }
416     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
417     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
418                                    const APSInt &N);
419     /// Add N to the address of this subobject.
420     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
421       if (Invalid || !N) return;
422       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
423       if (isMostDerivedAnUnsizedArray()) {
424         diagnoseUnsizedArrayPointerArithmetic(Info, E);
425         // Can't verify -- trust that the user is doing the right thing (or if
426         // not, trust that the caller will catch the bad behavior).
427         // FIXME: Should we reject if this overflows, at least?
428         Entries.back().ArrayIndex += TruncatedN;
429         return;
430       }
431 
432       // [expr.add]p4: For the purposes of these operators, a pointer to a
433       // nonarray object behaves the same as a pointer to the first element of
434       // an array of length one with the type of the object as its element type.
435       bool IsArray = MostDerivedPathLength == Entries.size() &&
436                      MostDerivedIsArrayElement;
437       uint64_t ArrayIndex =
438           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
439       uint64_t ArraySize =
440           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
441 
442       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
443         // Calculate the actual index in a wide enough type, so we can include
444         // it in the note.
445         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
446         (llvm::APInt&)N += ArrayIndex;
447         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
448         diagnosePointerArithmetic(Info, E, N);
449         setInvalid();
450         return;
451       }
452 
453       ArrayIndex += TruncatedN;
454       assert(ArrayIndex <= ArraySize &&
455              "bounds check succeeded for out-of-bounds index");
456 
457       if (IsArray)
458         Entries.back().ArrayIndex = ArrayIndex;
459       else
460         IsOnePastTheEnd = (ArrayIndex != 0);
461     }
462   };
463 
464   /// A stack frame in the constexpr call stack.
465   struct CallStackFrame {
466     EvalInfo &Info;
467 
468     /// Parent - The caller of this stack frame.
469     CallStackFrame *Caller;
470 
471     /// Callee - The function which was called.
472     const FunctionDecl *Callee;
473 
474     /// This - The binding for the this pointer in this call, if any.
475     const LValue *This;
476 
477     /// Arguments - Parameter bindings for this function call, indexed by
478     /// parameters' function scope indices.
479     APValue *Arguments;
480 
481     // Note that we intentionally use std::map here so that references to
482     // values are stable.
483     typedef std::pair<const void *, unsigned> MapKeyTy;
484     typedef std::map<MapKeyTy, APValue> MapTy;
485     /// Temporaries - Temporary lvalues materialized within this stack frame.
486     MapTy Temporaries;
487 
488     /// CallLoc - The location of the call expression for this call.
489     SourceLocation CallLoc;
490 
491     /// Index - The call index of this call.
492     unsigned Index;
493 
494     /// The stack of integers for tracking version numbers for temporaries.
495     SmallVector<unsigned, 2> TempVersionStack = {1};
496     unsigned CurTempVersion = TempVersionStack.back();
497 
498     unsigned getTempVersion() const { return TempVersionStack.back(); }
499 
500     void pushTempVersion() {
501       TempVersionStack.push_back(++CurTempVersion);
502     }
503 
504     void popTempVersion() {
505       TempVersionStack.pop_back();
506     }
507 
508     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
509     // on the overall stack usage of deeply-recursing constexpr evaluataions.
510     // (We should cache this map rather than recomputing it repeatedly.)
511     // But let's try this and see how it goes; we can look into caching the map
512     // as a later change.
513 
514     /// LambdaCaptureFields - Mapping from captured variables/this to
515     /// corresponding data members in the closure class.
516     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
517     FieldDecl *LambdaThisCaptureField;
518 
519     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
520                    const FunctionDecl *Callee, const LValue *This,
521                    APValue *Arguments);
522     ~CallStackFrame();
523 
524     // Return the temporary for Key whose version number is Version.
525     APValue *getTemporary(const void *Key, unsigned Version) {
526       MapKeyTy KV(Key, Version);
527       auto LB = Temporaries.lower_bound(KV);
528       if (LB != Temporaries.end() && LB->first == KV)
529         return &LB->second;
530       // Pair (Key,Version) wasn't found in the map. Check that no elements
531       // in the map have 'Key' as their key.
532       assert((LB == Temporaries.end() || LB->first.first != Key) &&
533              (LB == Temporaries.begin() || std::prev(LB)->first.first != Key) &&
534              "Element with key 'Key' found in map");
535       return nullptr;
536     }
537 
538     // Return the current temporary for Key in the map.
539     APValue *getCurrentTemporary(const void *Key) {
540       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
541       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
542         return &std::prev(UB)->second;
543       return nullptr;
544     }
545 
546     // Return the version number of the current temporary for Key.
547     unsigned getCurrentTemporaryVersion(const void *Key) const {
548       auto UB = Temporaries.upper_bound(MapKeyTy(Key, UINT_MAX));
549       if (UB != Temporaries.begin() && std::prev(UB)->first.first == Key)
550         return std::prev(UB)->first.second;
551       return 0;
552     }
553 
554     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
555   };
556 
557   /// Temporarily override 'this'.
558   class ThisOverrideRAII {
559   public:
560     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
561         : Frame(Frame), OldThis(Frame.This) {
562       if (Enable)
563         Frame.This = NewThis;
564     }
565     ~ThisOverrideRAII() {
566       Frame.This = OldThis;
567     }
568   private:
569     CallStackFrame &Frame;
570     const LValue *OldThis;
571   };
572 
573   /// A partial diagnostic which we might know in advance that we are not going
574   /// to emit.
575   class OptionalDiagnostic {
576     PartialDiagnostic *Diag;
577 
578   public:
579     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
580       : Diag(Diag) {}
581 
582     template<typename T>
583     OptionalDiagnostic &operator<<(const T &v) {
584       if (Diag)
585         *Diag << v;
586       return *this;
587     }
588 
589     OptionalDiagnostic &operator<<(const APSInt &I) {
590       if (Diag) {
591         SmallVector<char, 32> Buffer;
592         I.toString(Buffer);
593         *Diag << StringRef(Buffer.data(), Buffer.size());
594       }
595       return *this;
596     }
597 
598     OptionalDiagnostic &operator<<(const APFloat &F) {
599       if (Diag) {
600         // FIXME: Force the precision of the source value down so we don't
601         // print digits which are usually useless (we don't really care here if
602         // we truncate a digit by accident in edge cases).  Ideally,
603         // APFloat::toString would automatically print the shortest
604         // representation which rounds to the correct value, but it's a bit
605         // tricky to implement.
606         unsigned precision =
607             llvm::APFloat::semanticsPrecision(F.getSemantics());
608         precision = (precision * 59 + 195) / 196;
609         SmallVector<char, 32> Buffer;
610         F.toString(Buffer, precision);
611         *Diag << StringRef(Buffer.data(), Buffer.size());
612       }
613       return *this;
614     }
615   };
616 
617   /// A cleanup, and a flag indicating whether it is lifetime-extended.
618   class Cleanup {
619     llvm::PointerIntPair<APValue*, 1, bool> Value;
620 
621   public:
622     Cleanup(APValue *Val, bool IsLifetimeExtended)
623         : Value(Val, IsLifetimeExtended) {}
624 
625     bool isLifetimeExtended() const { return Value.getInt(); }
626     void endLifetime() {
627       *Value.getPointer() = APValue();
628     }
629   };
630 
631   /// EvalInfo - This is a private struct used by the evaluator to capture
632   /// information about a subexpression as it is folded.  It retains information
633   /// about the AST context, but also maintains information about the folded
634   /// expression.
635   ///
636   /// If an expression could be evaluated, it is still possible it is not a C
637   /// "integer constant expression" or constant expression.  If not, this struct
638   /// captures information about how and why not.
639   ///
640   /// One bit of information passed *into* the request for constant folding
641   /// indicates whether the subexpression is "evaluated" or not according to C
642   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
643   /// evaluate the expression regardless of what the RHS is, but C only allows
644   /// certain things in certain situations.
645   struct EvalInfo {
646     ASTContext &Ctx;
647 
648     /// EvalStatus - Contains information about the evaluation.
649     Expr::EvalStatus &EvalStatus;
650 
651     /// CurrentCall - The top of the constexpr call stack.
652     CallStackFrame *CurrentCall;
653 
654     /// CallStackDepth - The number of calls in the call stack right now.
655     unsigned CallStackDepth;
656 
657     /// NextCallIndex - The next call index to assign.
658     unsigned NextCallIndex;
659 
660     /// StepsLeft - The remaining number of evaluation steps we're permitted
661     /// to perform. This is essentially a limit for the number of statements
662     /// we will evaluate.
663     unsigned StepsLeft;
664 
665     /// BottomFrame - The frame in which evaluation started. This must be
666     /// initialized after CurrentCall and CallStackDepth.
667     CallStackFrame BottomFrame;
668 
669     /// A stack of values whose lifetimes end at the end of some surrounding
670     /// evaluation frame.
671     llvm::SmallVector<Cleanup, 16> CleanupStack;
672 
673     /// EvaluatingDecl - This is the declaration whose initializer is being
674     /// evaluated, if any.
675     APValue::LValueBase EvaluatingDecl;
676 
677     /// EvaluatingDeclValue - This is the value being constructed for the
678     /// declaration whose initializer is being evaluated, if any.
679     APValue *EvaluatingDeclValue;
680 
681     /// EvaluatingObject - Pair of the AST node that an lvalue represents and
682     /// the call index that that lvalue was allocated in.
683     typedef std::pair<APValue::LValueBase, std::pair<unsigned, unsigned>>
684         EvaluatingObject;
685 
686     /// EvaluatingConstructors - Set of objects that are currently being
687     /// constructed.
688     llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
689 
690     struct EvaluatingConstructorRAII {
691       EvalInfo &EI;
692       EvaluatingObject Object;
693       bool DidInsert;
694       EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
695           : EI(EI), Object(Object) {
696         DidInsert = EI.EvaluatingConstructors.insert(Object).second;
697       }
698       ~EvaluatingConstructorRAII() {
699         if (DidInsert) EI.EvaluatingConstructors.erase(Object);
700       }
701     };
702 
703     bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex,
704                                  unsigned Version) {
705       return EvaluatingConstructors.count(
706           EvaluatingObject(Decl, {CallIndex, Version}));
707     }
708 
709     /// The current array initialization index, if we're performing array
710     /// initialization.
711     uint64_t ArrayInitIndex = -1;
712 
713     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
714     /// notes attached to it will also be stored, otherwise they will not be.
715     bool HasActiveDiagnostic;
716 
717     /// Have we emitted a diagnostic explaining why we couldn't constant
718     /// fold (not just why it's not strictly a constant expression)?
719     bool HasFoldFailureDiagnostic;
720 
721     /// Whether or not we're currently speculatively evaluating.
722     bool IsSpeculativelyEvaluating;
723 
724     enum EvaluationMode {
725       /// Evaluate as a constant expression. Stop if we find that the expression
726       /// is not a constant expression.
727       EM_ConstantExpression,
728 
729       /// Evaluate as a potential constant expression. Keep going if we hit a
730       /// construct that we can't evaluate yet (because we don't yet know the
731       /// value of something) but stop if we hit something that could never be
732       /// a constant expression.
733       EM_PotentialConstantExpression,
734 
735       /// Fold the expression to a constant. Stop if we hit a side-effect that
736       /// we can't model.
737       EM_ConstantFold,
738 
739       /// Evaluate the expression looking for integer overflow and similar
740       /// issues. Don't worry about side-effects, and try to visit all
741       /// subexpressions.
742       EM_EvaluateForOverflow,
743 
744       /// Evaluate in any way we know how. Don't worry about side-effects that
745       /// can't be modeled.
746       EM_IgnoreSideEffects,
747 
748       /// Evaluate as a constant expression. Stop if we find that the expression
749       /// is not a constant expression. Some expressions can be retried in the
750       /// optimizer if we don't constant fold them here, but in an unevaluated
751       /// context we try to fold them immediately since the optimizer never
752       /// gets a chance to look at it.
753       EM_ConstantExpressionUnevaluated,
754 
755       /// Evaluate as a potential constant expression. Keep going if we hit a
756       /// construct that we can't evaluate yet (because we don't yet know the
757       /// value of something) but stop if we hit something that could never be
758       /// a constant expression. Some expressions can be retried in the
759       /// optimizer if we don't constant fold them here, but in an unevaluated
760       /// context we try to fold them immediately since the optimizer never
761       /// gets a chance to look at it.
762       EM_PotentialConstantExpressionUnevaluated,
763     } EvalMode;
764 
765     /// Are we checking whether the expression is a potential constant
766     /// expression?
767     bool checkingPotentialConstantExpression() const {
768       return EvalMode == EM_PotentialConstantExpression ||
769              EvalMode == EM_PotentialConstantExpressionUnevaluated;
770     }
771 
772     /// Are we checking an expression for overflow?
773     // FIXME: We should check for any kind of undefined or suspicious behavior
774     // in such constructs, not just overflow.
775     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
776 
777     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
778       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
779         CallStackDepth(0), NextCallIndex(1),
780         StepsLeft(getLangOpts().ConstexprStepLimit),
781         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
782         EvaluatingDecl((const ValueDecl *)nullptr),
783         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
784         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
785         EvalMode(Mode) {}
786 
787     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
788       EvaluatingDecl = Base;
789       EvaluatingDeclValue = &Value;
790       EvaluatingConstructors.insert({Base, {0, 0}});
791     }
792 
793     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
794 
795     bool CheckCallLimit(SourceLocation Loc) {
796       // Don't perform any constexpr calls (other than the call we're checking)
797       // when checking a potential constant expression.
798       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
799         return false;
800       if (NextCallIndex == 0) {
801         // NextCallIndex has wrapped around.
802         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
803         return false;
804       }
805       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
806         return true;
807       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
808         << getLangOpts().ConstexprCallDepth;
809       return false;
810     }
811 
812     CallStackFrame *getCallFrame(unsigned CallIndex) {
813       assert(CallIndex && "no call index in getCallFrame");
814       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
815       // be null in this loop.
816       CallStackFrame *Frame = CurrentCall;
817       while (Frame->Index > CallIndex)
818         Frame = Frame->Caller;
819       return (Frame->Index == CallIndex) ? Frame : nullptr;
820     }
821 
822     bool nextStep(const Stmt *S) {
823       if (!StepsLeft) {
824         FFDiag(S->getBeginLoc(), diag::note_constexpr_step_limit_exceeded);
825         return false;
826       }
827       --StepsLeft;
828       return true;
829     }
830 
831   private:
832     /// Add a diagnostic to the diagnostics list.
833     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
834       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
835       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
836       return EvalStatus.Diag->back().second;
837     }
838 
839     /// Add notes containing a call stack to the current point of evaluation.
840     void addCallStack(unsigned Limit);
841 
842   private:
843     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
844                             unsigned ExtraNotes, bool IsCCEDiag) {
845 
846       if (EvalStatus.Diag) {
847         // If we have a prior diagnostic, it will be noting that the expression
848         // isn't a constant expression. This diagnostic is more important,
849         // unless we require this evaluation to produce a constant expression.
850         //
851         // FIXME: We might want to show both diagnostics to the user in
852         // EM_ConstantFold mode.
853         if (!EvalStatus.Diag->empty()) {
854           switch (EvalMode) {
855           case EM_ConstantFold:
856           case EM_IgnoreSideEffects:
857           case EM_EvaluateForOverflow:
858             if (!HasFoldFailureDiagnostic)
859               break;
860             // We've already failed to fold something. Keep that diagnostic.
861             LLVM_FALLTHROUGH;
862           case EM_ConstantExpression:
863           case EM_PotentialConstantExpression:
864           case EM_ConstantExpressionUnevaluated:
865           case EM_PotentialConstantExpressionUnevaluated:
866             HasActiveDiagnostic = false;
867             return OptionalDiagnostic();
868           }
869         }
870 
871         unsigned CallStackNotes = CallStackDepth - 1;
872         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
873         if (Limit)
874           CallStackNotes = std::min(CallStackNotes, Limit + 1);
875         if (checkingPotentialConstantExpression())
876           CallStackNotes = 0;
877 
878         HasActiveDiagnostic = true;
879         HasFoldFailureDiagnostic = !IsCCEDiag;
880         EvalStatus.Diag->clear();
881         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
882         addDiag(Loc, DiagId);
883         if (!checkingPotentialConstantExpression())
884           addCallStack(Limit);
885         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
886       }
887       HasActiveDiagnostic = false;
888       return OptionalDiagnostic();
889     }
890   public:
891     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
892     OptionalDiagnostic
893     FFDiag(SourceLocation Loc,
894           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
895           unsigned ExtraNotes = 0) {
896       return Diag(Loc, DiagId, ExtraNotes, false);
897     }
898 
899     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
900                               = diag::note_invalid_subexpr_in_const_expr,
901                             unsigned ExtraNotes = 0) {
902       if (EvalStatus.Diag)
903         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
904       HasActiveDiagnostic = false;
905       return OptionalDiagnostic();
906     }
907 
908     /// Diagnose that the evaluation does not produce a C++11 core constant
909     /// expression.
910     ///
911     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
912     /// EM_PotentialConstantExpression mode and we produce one of these.
913     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
914                                  = diag::note_invalid_subexpr_in_const_expr,
915                                unsigned ExtraNotes = 0) {
916       // Don't override a previous diagnostic. Don't bother collecting
917       // diagnostics if we're evaluating for overflow.
918       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
919         HasActiveDiagnostic = false;
920         return OptionalDiagnostic();
921       }
922       return Diag(Loc, DiagId, ExtraNotes, true);
923     }
924     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
925                                  = diag::note_invalid_subexpr_in_const_expr,
926                                unsigned ExtraNotes = 0) {
927       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
928     }
929     /// Add a note to a prior diagnostic.
930     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
931       if (!HasActiveDiagnostic)
932         return OptionalDiagnostic();
933       return OptionalDiagnostic(&addDiag(Loc, DiagId));
934     }
935 
936     /// Add a stack of notes to a prior diagnostic.
937     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
938       if (HasActiveDiagnostic) {
939         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
940                                 Diags.begin(), Diags.end());
941       }
942     }
943 
944     /// Should we continue evaluation after encountering a side-effect that we
945     /// couldn't model?
946     bool keepEvaluatingAfterSideEffect() {
947       switch (EvalMode) {
948       case EM_PotentialConstantExpression:
949       case EM_PotentialConstantExpressionUnevaluated:
950       case EM_EvaluateForOverflow:
951       case EM_IgnoreSideEffects:
952         return true;
953 
954       case EM_ConstantExpression:
955       case EM_ConstantExpressionUnevaluated:
956       case EM_ConstantFold:
957         return false;
958       }
959       llvm_unreachable("Missed EvalMode case");
960     }
961 
962     /// Note that we have had a side-effect, and determine whether we should
963     /// keep evaluating.
964     bool noteSideEffect() {
965       EvalStatus.HasSideEffects = true;
966       return keepEvaluatingAfterSideEffect();
967     }
968 
969     /// Should we continue evaluation after encountering undefined behavior?
970     bool keepEvaluatingAfterUndefinedBehavior() {
971       switch (EvalMode) {
972       case EM_EvaluateForOverflow:
973       case EM_IgnoreSideEffects:
974       case EM_ConstantFold:
975         return true;
976 
977       case EM_PotentialConstantExpression:
978       case EM_PotentialConstantExpressionUnevaluated:
979       case EM_ConstantExpression:
980       case EM_ConstantExpressionUnevaluated:
981         return false;
982       }
983       llvm_unreachable("Missed EvalMode case");
984     }
985 
986     /// Note that we hit something that was technically undefined behavior, but
987     /// that we can evaluate past it (such as signed overflow or floating-point
988     /// division by zero.)
989     bool noteUndefinedBehavior() {
990       EvalStatus.HasUndefinedBehavior = true;
991       return keepEvaluatingAfterUndefinedBehavior();
992     }
993 
994     /// Should we continue evaluation as much as possible after encountering a
995     /// construct which can't be reduced to a value?
996     bool keepEvaluatingAfterFailure() {
997       if (!StepsLeft)
998         return false;
999 
1000       switch (EvalMode) {
1001       case EM_PotentialConstantExpression:
1002       case EM_PotentialConstantExpressionUnevaluated:
1003       case EM_EvaluateForOverflow:
1004         return true;
1005 
1006       case EM_ConstantExpression:
1007       case EM_ConstantExpressionUnevaluated:
1008       case EM_ConstantFold:
1009       case EM_IgnoreSideEffects:
1010         return false;
1011       }
1012       llvm_unreachable("Missed EvalMode case");
1013     }
1014 
1015     /// Notes that we failed to evaluate an expression that other expressions
1016     /// directly depend on, and determine if we should keep evaluating. This
1017     /// should only be called if we actually intend to keep evaluating.
1018     ///
1019     /// Call noteSideEffect() instead if we may be able to ignore the value that
1020     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
1021     ///
1022     /// (Foo(), 1)      // use noteSideEffect
1023     /// (Foo() || true) // use noteSideEffect
1024     /// Foo() + 1       // use noteFailure
1025     LLVM_NODISCARD bool noteFailure() {
1026       // Failure when evaluating some expression often means there is some
1027       // subexpression whose evaluation was skipped. Therefore, (because we
1028       // don't track whether we skipped an expression when unwinding after an
1029       // evaluation failure) every evaluation failure that bubbles up from a
1030       // subexpression implies that a side-effect has potentially happened. We
1031       // skip setting the HasSideEffects flag to true until we decide to
1032       // continue evaluating after that point, which happens here.
1033       bool KeepGoing = keepEvaluatingAfterFailure();
1034       EvalStatus.HasSideEffects |= KeepGoing;
1035       return KeepGoing;
1036     }
1037 
1038     class ArrayInitLoopIndex {
1039       EvalInfo &Info;
1040       uint64_t OuterIndex;
1041 
1042     public:
1043       ArrayInitLoopIndex(EvalInfo &Info)
1044           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
1045         Info.ArrayInitIndex = 0;
1046       }
1047       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
1048 
1049       operator uint64_t&() { return Info.ArrayInitIndex; }
1050     };
1051   };
1052 
1053   /// Object used to treat all foldable expressions as constant expressions.
1054   struct FoldConstant {
1055     EvalInfo &Info;
1056     bool Enabled;
1057     bool HadNoPriorDiags;
1058     EvalInfo::EvaluationMode OldMode;
1059 
1060     explicit FoldConstant(EvalInfo &Info, bool Enabled)
1061       : Info(Info),
1062         Enabled(Enabled),
1063         HadNoPriorDiags(Info.EvalStatus.Diag &&
1064                         Info.EvalStatus.Diag->empty() &&
1065                         !Info.EvalStatus.HasSideEffects),
1066         OldMode(Info.EvalMode) {
1067       if (Enabled &&
1068           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1069            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1070         Info.EvalMode = EvalInfo::EM_ConstantFold;
1071     }
1072     void keepDiagnostics() { Enabled = false; }
1073     ~FoldConstant() {
1074       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1075           !Info.EvalStatus.HasSideEffects)
1076         Info.EvalStatus.Diag->clear();
1077       Info.EvalMode = OldMode;
1078     }
1079   };
1080 
1081   /// RAII object used to set the current evaluation mode to ignore
1082   /// side-effects.
1083   struct IgnoreSideEffectsRAII {
1084     EvalInfo &Info;
1085     EvalInfo::EvaluationMode OldMode;
1086     explicit IgnoreSideEffectsRAII(EvalInfo &Info)
1087         : Info(Info), OldMode(Info.EvalMode) {
1088       if (!Info.checkingPotentialConstantExpression())
1089         Info.EvalMode = EvalInfo::EM_IgnoreSideEffects;
1090     }
1091 
1092     ~IgnoreSideEffectsRAII() { Info.EvalMode = OldMode; }
1093   };
1094 
1095   /// RAII object used to optionally suppress diagnostics and side-effects from
1096   /// a speculative evaluation.
1097   class SpeculativeEvaluationRAII {
1098     EvalInfo *Info = nullptr;
1099     Expr::EvalStatus OldStatus;
1100     bool OldIsSpeculativelyEvaluating;
1101 
1102     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1103       Info = Other.Info;
1104       OldStatus = Other.OldStatus;
1105       OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1106       Other.Info = nullptr;
1107     }
1108 
1109     void maybeRestoreState() {
1110       if (!Info)
1111         return;
1112 
1113       Info->EvalStatus = OldStatus;
1114       Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1115     }
1116 
1117   public:
1118     SpeculativeEvaluationRAII() = default;
1119 
1120     SpeculativeEvaluationRAII(
1121         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1122         : Info(&Info), OldStatus(Info.EvalStatus),
1123           OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1124       Info.EvalStatus.Diag = NewDiag;
1125       Info.IsSpeculativelyEvaluating = true;
1126     }
1127 
1128     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1129     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1130       moveFromAndCancel(std::move(Other));
1131     }
1132 
1133     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1134       maybeRestoreState();
1135       moveFromAndCancel(std::move(Other));
1136       return *this;
1137     }
1138 
1139     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1140   };
1141 
1142   /// RAII object wrapping a full-expression or block scope, and handling
1143   /// the ending of the lifetime of temporaries created within it.
1144   template<bool IsFullExpression>
1145   class ScopeRAII {
1146     EvalInfo &Info;
1147     unsigned OldStackSize;
1148   public:
1149     ScopeRAII(EvalInfo &Info)
1150         : Info(Info), OldStackSize(Info.CleanupStack.size()) {
1151       // Push a new temporary version. This is needed to distinguish between
1152       // temporaries created in different iterations of a loop.
1153       Info.CurrentCall->pushTempVersion();
1154     }
1155     ~ScopeRAII() {
1156       // Body moved to a static method to encourage the compiler to inline away
1157       // instances of this class.
1158       cleanup(Info, OldStackSize);
1159       Info.CurrentCall->popTempVersion();
1160     }
1161   private:
1162     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1163       unsigned NewEnd = OldStackSize;
1164       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1165            I != N; ++I) {
1166         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1167           // Full-expression cleanup of a lifetime-extended temporary: nothing
1168           // to do, just move this cleanup to the right place in the stack.
1169           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1170           ++NewEnd;
1171         } else {
1172           // End the lifetime of the object.
1173           Info.CleanupStack[I].endLifetime();
1174         }
1175       }
1176       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1177                               Info.CleanupStack.end());
1178     }
1179   };
1180   typedef ScopeRAII<false> BlockScopeRAII;
1181   typedef ScopeRAII<true> FullExpressionRAII;
1182 }
1183 
1184 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1185                                          CheckSubobjectKind CSK) {
1186   if (Invalid)
1187     return false;
1188   if (isOnePastTheEnd()) {
1189     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1190       << CSK;
1191     setInvalid();
1192     return false;
1193   }
1194   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1195   // must actually be at least one array element; even a VLA cannot have a
1196   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1197   return true;
1198 }
1199 
1200 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1201                                                                 const Expr *E) {
1202   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1203   // Do not set the designator as invalid: we can represent this situation,
1204   // and correct handling of __builtin_object_size requires us to do so.
1205 }
1206 
1207 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1208                                                     const Expr *E,
1209                                                     const APSInt &N) {
1210   // If we're complaining, we must be able to statically determine the size of
1211   // the most derived array.
1212   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1213     Info.CCEDiag(E, diag::note_constexpr_array_index)
1214       << N << /*array*/ 0
1215       << static_cast<unsigned>(getMostDerivedArraySize());
1216   else
1217     Info.CCEDiag(E, diag::note_constexpr_array_index)
1218       << N << /*non-array*/ 1;
1219   setInvalid();
1220 }
1221 
1222 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1223                                const FunctionDecl *Callee, const LValue *This,
1224                                APValue *Arguments)
1225     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1226       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1227   Info.CurrentCall = this;
1228   ++Info.CallStackDepth;
1229 }
1230 
1231 CallStackFrame::~CallStackFrame() {
1232   assert(Info.CurrentCall == this && "calls retired out of order");
1233   --Info.CallStackDepth;
1234   Info.CurrentCall = Caller;
1235 }
1236 
1237 APValue &CallStackFrame::createTemporary(const void *Key,
1238                                          bool IsLifetimeExtended) {
1239   unsigned Version = Info.CurrentCall->getTempVersion();
1240   APValue &Result = Temporaries[MapKeyTy(Key, Version)];
1241   assert(Result.isUninit() && "temporary created multiple times");
1242   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1243   return Result;
1244 }
1245 
1246 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1247 
1248 void EvalInfo::addCallStack(unsigned Limit) {
1249   // Determine which calls to skip, if any.
1250   unsigned ActiveCalls = CallStackDepth - 1;
1251   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1252   if (Limit && Limit < ActiveCalls) {
1253     SkipStart = Limit / 2 + Limit % 2;
1254     SkipEnd = ActiveCalls - Limit / 2;
1255   }
1256 
1257   // Walk the call stack and add the diagnostics.
1258   unsigned CallIdx = 0;
1259   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1260        Frame = Frame->Caller, ++CallIdx) {
1261     // Skip this call?
1262     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1263       if (CallIdx == SkipStart) {
1264         // Note that we're skipping calls.
1265         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1266           << unsigned(ActiveCalls - Limit);
1267       }
1268       continue;
1269     }
1270 
1271     // Use a different note for an inheriting constructor, because from the
1272     // user's perspective it's not really a function at all.
1273     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1274       if (CD->isInheritingConstructor()) {
1275         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1276           << CD->getParent();
1277         continue;
1278       }
1279     }
1280 
1281     SmallVector<char, 128> Buffer;
1282     llvm::raw_svector_ostream Out(Buffer);
1283     describeCall(Frame, Out);
1284     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1285   }
1286 }
1287 
1288 namespace {
1289   struct ComplexValue {
1290   private:
1291     bool IsInt;
1292 
1293   public:
1294     APSInt IntReal, IntImag;
1295     APFloat FloatReal, FloatImag;
1296 
1297     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1298 
1299     void makeComplexFloat() { IsInt = false; }
1300     bool isComplexFloat() const { return !IsInt; }
1301     APFloat &getComplexFloatReal() { return FloatReal; }
1302     APFloat &getComplexFloatImag() { return FloatImag; }
1303 
1304     void makeComplexInt() { IsInt = true; }
1305     bool isComplexInt() const { return IsInt; }
1306     APSInt &getComplexIntReal() { return IntReal; }
1307     APSInt &getComplexIntImag() { return IntImag; }
1308 
1309     void moveInto(APValue &v) const {
1310       if (isComplexFloat())
1311         v = APValue(FloatReal, FloatImag);
1312       else
1313         v = APValue(IntReal, IntImag);
1314     }
1315     void setFrom(const APValue &v) {
1316       assert(v.isComplexFloat() || v.isComplexInt());
1317       if (v.isComplexFloat()) {
1318         makeComplexFloat();
1319         FloatReal = v.getComplexFloatReal();
1320         FloatImag = v.getComplexFloatImag();
1321       } else {
1322         makeComplexInt();
1323         IntReal = v.getComplexIntReal();
1324         IntImag = v.getComplexIntImag();
1325       }
1326     }
1327   };
1328 
1329   struct LValue {
1330     APValue::LValueBase Base;
1331     CharUnits Offset;
1332     SubobjectDesignator Designator;
1333     bool IsNullPtr : 1;
1334     bool InvalidBase : 1;
1335 
1336     const APValue::LValueBase getLValueBase() const { return Base; }
1337     CharUnits &getLValueOffset() { return Offset; }
1338     const CharUnits &getLValueOffset() const { return Offset; }
1339     SubobjectDesignator &getLValueDesignator() { return Designator; }
1340     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1341     bool isNullPointer() const { return IsNullPtr;}
1342 
1343     unsigned getLValueCallIndex() const { return Base.getCallIndex(); }
1344     unsigned getLValueVersion() const { return Base.getVersion(); }
1345 
1346     void moveInto(APValue &V) const {
1347       if (Designator.Invalid)
1348         V = APValue(Base, Offset, APValue::NoLValuePath(), IsNullPtr);
1349       else {
1350         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1351         V = APValue(Base, Offset, Designator.Entries,
1352                     Designator.IsOnePastTheEnd, IsNullPtr);
1353       }
1354     }
1355     void setFrom(ASTContext &Ctx, const APValue &V) {
1356       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1357       Base = V.getLValueBase();
1358       Offset = V.getLValueOffset();
1359       InvalidBase = false;
1360       Designator = SubobjectDesignator(Ctx, V);
1361       IsNullPtr = V.isNullPointer();
1362     }
1363 
1364     void set(APValue::LValueBase B, bool BInvalid = false) {
1365 #ifndef NDEBUG
1366       // We only allow a few types of invalid bases. Enforce that here.
1367       if (BInvalid) {
1368         const auto *E = B.get<const Expr *>();
1369         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1370                "Unexpected type of invalid base");
1371       }
1372 #endif
1373 
1374       Base = B;
1375       Offset = CharUnits::fromQuantity(0);
1376       InvalidBase = BInvalid;
1377       Designator = SubobjectDesignator(getType(B));
1378       IsNullPtr = false;
1379     }
1380 
1381     void setNull(QualType PointerTy, uint64_t TargetVal) {
1382       Base = (Expr *)nullptr;
1383       Offset = CharUnits::fromQuantity(TargetVal);
1384       InvalidBase = false;
1385       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1386       IsNullPtr = true;
1387     }
1388 
1389     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1390       set(B, true);
1391     }
1392 
1393     // Check that this LValue is not based on a null pointer. If it is, produce
1394     // a diagnostic and mark the designator as invalid.
1395     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1396                           CheckSubobjectKind CSK) {
1397       if (Designator.Invalid)
1398         return false;
1399       if (IsNullPtr) {
1400         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1401           << CSK;
1402         Designator.setInvalid();
1403         return false;
1404       }
1405       return true;
1406     }
1407 
1408     // Check this LValue refers to an object. If not, set the designator to be
1409     // invalid and emit a diagnostic.
1410     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1411       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1412              Designator.checkSubobject(Info, E, CSK);
1413     }
1414 
1415     void addDecl(EvalInfo &Info, const Expr *E,
1416                  const Decl *D, bool Virtual = false) {
1417       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1418         Designator.addDeclUnchecked(D, Virtual);
1419     }
1420     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1421       if (!Designator.Entries.empty()) {
1422         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1423         Designator.setInvalid();
1424         return;
1425       }
1426       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1427         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1428         Designator.FirstEntryIsAnUnsizedArray = true;
1429         Designator.addUnsizedArrayUnchecked(ElemTy);
1430       }
1431     }
1432     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1433       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1434         Designator.addArrayUnchecked(CAT);
1435     }
1436     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1437       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1438         Designator.addComplexUnchecked(EltTy, Imag);
1439     }
1440     void clearIsNullPointer() {
1441       IsNullPtr = false;
1442     }
1443     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1444                               const APSInt &Index, CharUnits ElementSize) {
1445       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1446       // but we're not required to diagnose it and it's valid in C++.)
1447       if (!Index)
1448         return;
1449 
1450       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1451       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1452       // offsets.
1453       uint64_t Offset64 = Offset.getQuantity();
1454       uint64_t ElemSize64 = ElementSize.getQuantity();
1455       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1456       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1457 
1458       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1459         Designator.adjustIndex(Info, E, Index);
1460       clearIsNullPointer();
1461     }
1462     void adjustOffset(CharUnits N) {
1463       Offset += N;
1464       if (N.getQuantity())
1465         clearIsNullPointer();
1466     }
1467   };
1468 
1469   struct MemberPtr {
1470     MemberPtr() {}
1471     explicit MemberPtr(const ValueDecl *Decl) :
1472       DeclAndIsDerivedMember(Decl, false), Path() {}
1473 
1474     /// The member or (direct or indirect) field referred to by this member
1475     /// pointer, or 0 if this is a null member pointer.
1476     const ValueDecl *getDecl() const {
1477       return DeclAndIsDerivedMember.getPointer();
1478     }
1479     /// Is this actually a member of some type derived from the relevant class?
1480     bool isDerivedMember() const {
1481       return DeclAndIsDerivedMember.getInt();
1482     }
1483     /// Get the class which the declaration actually lives in.
1484     const CXXRecordDecl *getContainingRecord() const {
1485       return cast<CXXRecordDecl>(
1486           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1487     }
1488 
1489     void moveInto(APValue &V) const {
1490       V = APValue(getDecl(), isDerivedMember(), Path);
1491     }
1492     void setFrom(const APValue &V) {
1493       assert(V.isMemberPointer());
1494       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1495       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1496       Path.clear();
1497       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1498       Path.insert(Path.end(), P.begin(), P.end());
1499     }
1500 
1501     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1502     /// whether the member is a member of some class derived from the class type
1503     /// of the member pointer.
1504     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1505     /// Path - The path of base/derived classes from the member declaration's
1506     /// class (exclusive) to the class type of the member pointer (inclusive).
1507     SmallVector<const CXXRecordDecl*, 4> Path;
1508 
1509     /// Perform a cast towards the class of the Decl (either up or down the
1510     /// hierarchy).
1511     bool castBack(const CXXRecordDecl *Class) {
1512       assert(!Path.empty());
1513       const CXXRecordDecl *Expected;
1514       if (Path.size() >= 2)
1515         Expected = Path[Path.size() - 2];
1516       else
1517         Expected = getContainingRecord();
1518       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1519         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1520         // if B does not contain the original member and is not a base or
1521         // derived class of the class containing the original member, the result
1522         // of the cast is undefined.
1523         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1524         // (D::*). We consider that to be a language defect.
1525         return false;
1526       }
1527       Path.pop_back();
1528       return true;
1529     }
1530     /// Perform a base-to-derived member pointer cast.
1531     bool castToDerived(const CXXRecordDecl *Derived) {
1532       if (!getDecl())
1533         return true;
1534       if (!isDerivedMember()) {
1535         Path.push_back(Derived);
1536         return true;
1537       }
1538       if (!castBack(Derived))
1539         return false;
1540       if (Path.empty())
1541         DeclAndIsDerivedMember.setInt(false);
1542       return true;
1543     }
1544     /// Perform a derived-to-base member pointer cast.
1545     bool castToBase(const CXXRecordDecl *Base) {
1546       if (!getDecl())
1547         return true;
1548       if (Path.empty())
1549         DeclAndIsDerivedMember.setInt(true);
1550       if (isDerivedMember()) {
1551         Path.push_back(Base);
1552         return true;
1553       }
1554       return castBack(Base);
1555     }
1556   };
1557 
1558   /// Compare two member pointers, which are assumed to be of the same type.
1559   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1560     if (!LHS.getDecl() || !RHS.getDecl())
1561       return !LHS.getDecl() && !RHS.getDecl();
1562     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1563       return false;
1564     return LHS.Path == RHS.Path;
1565   }
1566 }
1567 
1568 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1569 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1570                             const LValue &This, const Expr *E,
1571                             bool AllowNonLiteralTypes = false);
1572 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1573                            bool InvalidBaseOK = false);
1574 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1575                             bool InvalidBaseOK = false);
1576 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1577                                   EvalInfo &Info);
1578 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1579 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1580 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1581                                     EvalInfo &Info);
1582 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1583 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1584 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1585                            EvalInfo &Info);
1586 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1587 
1588 //===----------------------------------------------------------------------===//
1589 // Misc utilities
1590 //===----------------------------------------------------------------------===//
1591 
1592 /// A helper function to create a temporary and set an LValue.
1593 template <class KeyTy>
1594 static APValue &createTemporary(const KeyTy *Key, bool IsLifetimeExtended,
1595                                 LValue &LV, CallStackFrame &Frame) {
1596   LV.set({Key, Frame.Info.CurrentCall->Index,
1597           Frame.Info.CurrentCall->getTempVersion()});
1598   return Frame.createTemporary(Key, IsLifetimeExtended);
1599 }
1600 
1601 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1602 /// preserving its value (by extending by up to one bit as needed).
1603 static void negateAsSigned(APSInt &Int) {
1604   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1605     Int = Int.extend(Int.getBitWidth() + 1);
1606     Int.setIsSigned(true);
1607   }
1608   Int = -Int;
1609 }
1610 
1611 /// Produce a string describing the given constexpr call.
1612 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1613   unsigned ArgIndex = 0;
1614   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1615                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1616                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1617 
1618   if (!IsMemberCall)
1619     Out << *Frame->Callee << '(';
1620 
1621   if (Frame->This && IsMemberCall) {
1622     APValue Val;
1623     Frame->This->moveInto(Val);
1624     Val.printPretty(Out, Frame->Info.Ctx,
1625                     Frame->This->Designator.MostDerivedType);
1626     // FIXME: Add parens around Val if needed.
1627     Out << "->" << *Frame->Callee << '(';
1628     IsMemberCall = false;
1629   }
1630 
1631   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1632        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1633     if (ArgIndex > (unsigned)IsMemberCall)
1634       Out << ", ";
1635 
1636     const ParmVarDecl *Param = *I;
1637     const APValue &Arg = Frame->Arguments[ArgIndex];
1638     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1639 
1640     if (ArgIndex == 0 && IsMemberCall)
1641       Out << "->" << *Frame->Callee << '(';
1642   }
1643 
1644   Out << ')';
1645 }
1646 
1647 /// Evaluate an expression to see if it had side-effects, and discard its
1648 /// result.
1649 /// \return \c true if the caller should keep evaluating.
1650 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1651   APValue Scratch;
1652   if (!Evaluate(Scratch, Info, E))
1653     // We don't need the value, but we might have skipped a side effect here.
1654     return Info.noteSideEffect();
1655   return true;
1656 }
1657 
1658 /// Should this call expression be treated as a string literal?
1659 static bool IsStringLiteralCall(const CallExpr *E) {
1660   unsigned Builtin = E->getBuiltinCallee();
1661   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1662           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1663 }
1664 
1665 static bool IsGlobalLValue(APValue::LValueBase B) {
1666   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1667   // constant expression of pointer type that evaluates to...
1668 
1669   // ... a null pointer value, or a prvalue core constant expression of type
1670   // std::nullptr_t.
1671   if (!B) return true;
1672 
1673   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1674     // ... the address of an object with static storage duration,
1675     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1676       return VD->hasGlobalStorage();
1677     // ... the address of a function,
1678     return isa<FunctionDecl>(D);
1679   }
1680 
1681   const Expr *E = B.get<const Expr*>();
1682   switch (E->getStmtClass()) {
1683   default:
1684     return false;
1685   case Expr::CompoundLiteralExprClass: {
1686     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1687     return CLE->isFileScope() && CLE->isLValue();
1688   }
1689   case Expr::MaterializeTemporaryExprClass:
1690     // A materialized temporary might have been lifetime-extended to static
1691     // storage duration.
1692     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1693   // A string literal has static storage duration.
1694   case Expr::StringLiteralClass:
1695   case Expr::PredefinedExprClass:
1696   case Expr::ObjCStringLiteralClass:
1697   case Expr::ObjCEncodeExprClass:
1698   case Expr::CXXTypeidExprClass:
1699   case Expr::CXXUuidofExprClass:
1700     return true;
1701   case Expr::CallExprClass:
1702     return IsStringLiteralCall(cast<CallExpr>(E));
1703   // For GCC compatibility, &&label has static storage duration.
1704   case Expr::AddrLabelExprClass:
1705     return true;
1706   // A Block literal expression may be used as the initialization value for
1707   // Block variables at global or local static scope.
1708   case Expr::BlockExprClass:
1709     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1710   case Expr::ImplicitValueInitExprClass:
1711     // FIXME:
1712     // We can never form an lvalue with an implicit value initialization as its
1713     // base through expression evaluation, so these only appear in one case: the
1714     // implicit variable declaration we invent when checking whether a constexpr
1715     // constructor can produce a constant expression. We must assume that such
1716     // an expression might be a global lvalue.
1717     return true;
1718   }
1719 }
1720 
1721 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1722   return LVal.Base.dyn_cast<const ValueDecl*>();
1723 }
1724 
1725 static bool IsLiteralLValue(const LValue &Value) {
1726   if (Value.getLValueCallIndex())
1727     return false;
1728   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1729   return E && !isa<MaterializeTemporaryExpr>(E);
1730 }
1731 
1732 static bool IsWeakLValue(const LValue &Value) {
1733   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1734   return Decl && Decl->isWeak();
1735 }
1736 
1737 static bool isZeroSized(const LValue &Value) {
1738   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1739   if (Decl && isa<VarDecl>(Decl)) {
1740     QualType Ty = Decl->getType();
1741     if (Ty->isArrayType())
1742       return Ty->isIncompleteType() ||
1743              Decl->getASTContext().getTypeSize(Ty) == 0;
1744   }
1745   return false;
1746 }
1747 
1748 static bool HasSameBase(const LValue &A, const LValue &B) {
1749   if (!A.getLValueBase())
1750     return !B.getLValueBase();
1751   if (!B.getLValueBase())
1752     return false;
1753 
1754   if (A.getLValueBase().getOpaqueValue() !=
1755       B.getLValueBase().getOpaqueValue()) {
1756     const Decl *ADecl = GetLValueBaseDecl(A);
1757     if (!ADecl)
1758       return false;
1759     const Decl *BDecl = GetLValueBaseDecl(B);
1760     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
1761       return false;
1762   }
1763 
1764   return IsGlobalLValue(A.getLValueBase()) ||
1765          (A.getLValueCallIndex() == B.getLValueCallIndex() &&
1766           A.getLValueVersion() == B.getLValueVersion());
1767 }
1768 
1769 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1770   assert(Base && "no location for a null lvalue");
1771   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1772   if (VD)
1773     Info.Note(VD->getLocation(), diag::note_declared_at);
1774   else
1775     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1776               diag::note_constexpr_temporary_here);
1777 }
1778 
1779 /// Check that this reference or pointer core constant expression is a valid
1780 /// value for an address or reference constant expression. Return true if we
1781 /// can fold this expression, whether or not it's a constant expression.
1782 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1783                                           QualType Type, const LValue &LVal,
1784                                           Expr::ConstExprUsage Usage) {
1785   bool IsReferenceType = Type->isReferenceType();
1786 
1787   APValue::LValueBase Base = LVal.getLValueBase();
1788   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1789 
1790   // Check that the object is a global. Note that the fake 'this' object we
1791   // manufacture when checking potential constant expressions is conservatively
1792   // assumed to be global here.
1793   if (!IsGlobalLValue(Base)) {
1794     if (Info.getLangOpts().CPlusPlus11) {
1795       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1796       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1797         << IsReferenceType << !Designator.Entries.empty()
1798         << !!VD << VD;
1799       NoteLValueLocation(Info, Base);
1800     } else {
1801       Info.FFDiag(Loc);
1802     }
1803     // Don't allow references to temporaries to escape.
1804     return false;
1805   }
1806   assert((Info.checkingPotentialConstantExpression() ||
1807           LVal.getLValueCallIndex() == 0) &&
1808          "have call index for global lvalue");
1809 
1810   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1811     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1812       // Check if this is a thread-local variable.
1813       if (Var->getTLSKind())
1814         return false;
1815 
1816       // A dllimport variable never acts like a constant.
1817       if (Usage == Expr::EvaluateForCodeGen && Var->hasAttr<DLLImportAttr>())
1818         return false;
1819     }
1820     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1821       // __declspec(dllimport) must be handled very carefully:
1822       // We must never initialize an expression with the thunk in C++.
1823       // Doing otherwise would allow the same id-expression to yield
1824       // different addresses for the same function in different translation
1825       // units.  However, this means that we must dynamically initialize the
1826       // expression with the contents of the import address table at runtime.
1827       //
1828       // The C language has no notion of ODR; furthermore, it has no notion of
1829       // dynamic initialization.  This means that we are permitted to
1830       // perform initialization with the address of the thunk.
1831       if (Info.getLangOpts().CPlusPlus && Usage == Expr::EvaluateForCodeGen &&
1832           FD->hasAttr<DLLImportAttr>())
1833         return false;
1834     }
1835   }
1836 
1837   // Allow address constant expressions to be past-the-end pointers. This is
1838   // an extension: the standard requires them to point to an object.
1839   if (!IsReferenceType)
1840     return true;
1841 
1842   // A reference constant expression must refer to an object.
1843   if (!Base) {
1844     // FIXME: diagnostic
1845     Info.CCEDiag(Loc);
1846     return true;
1847   }
1848 
1849   // Does this refer one past the end of some object?
1850   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1851     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1852     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1853       << !Designator.Entries.empty() << !!VD << VD;
1854     NoteLValueLocation(Info, Base);
1855   }
1856 
1857   return true;
1858 }
1859 
1860 /// Member pointers are constant expressions unless they point to a
1861 /// non-virtual dllimport member function.
1862 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1863                                                  SourceLocation Loc,
1864                                                  QualType Type,
1865                                                  const APValue &Value,
1866                                                  Expr::ConstExprUsage Usage) {
1867   const ValueDecl *Member = Value.getMemberPointerDecl();
1868   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1869   if (!FD)
1870     return true;
1871   return Usage == Expr::EvaluateForMangling || FD->isVirtual() ||
1872          !FD->hasAttr<DLLImportAttr>();
1873 }
1874 
1875 /// Check that this core constant expression is of literal type, and if not,
1876 /// produce an appropriate diagnostic.
1877 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1878                              const LValue *This = nullptr) {
1879   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1880     return true;
1881 
1882   // C++1y: A constant initializer for an object o [...] may also invoke
1883   // constexpr constructors for o and its subobjects even if those objects
1884   // are of non-literal class types.
1885   //
1886   // C++11 missed this detail for aggregates, so classes like this:
1887   //   struct foo_t { union { int i; volatile int j; } u; };
1888   // are not (obviously) initializable like so:
1889   //   __attribute__((__require_constant_initialization__))
1890   //   static const foo_t x = {{0}};
1891   // because "i" is a subobject with non-literal initialization (due to the
1892   // volatile member of the union). See:
1893   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1894   // Therefore, we use the C++1y behavior.
1895   if (This && Info.EvaluatingDecl == This->getLValueBase())
1896     return true;
1897 
1898   // Prvalue constant expressions must be of literal types.
1899   if (Info.getLangOpts().CPlusPlus11)
1900     Info.FFDiag(E, diag::note_constexpr_nonliteral)
1901       << E->getType();
1902   else
1903     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1904   return false;
1905 }
1906 
1907 /// Check that this core constant expression value is a valid value for a
1908 /// constant expression. If not, report an appropriate diagnostic. Does not
1909 /// check that the expression is of literal type.
1910 static bool
1911 CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc, QualType Type,
1912                         const APValue &Value,
1913                         Expr::ConstExprUsage Usage = Expr::EvaluateForCodeGen) {
1914   if (Value.isUninit()) {
1915     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1916       << true << Type;
1917     return false;
1918   }
1919 
1920   // We allow _Atomic(T) to be initialized from anything that T can be
1921   // initialized from.
1922   if (const AtomicType *AT = Type->getAs<AtomicType>())
1923     Type = AT->getValueType();
1924 
1925   // Core issue 1454: For a literal constant expression of array or class type,
1926   // each subobject of its value shall have been initialized by a constant
1927   // expression.
1928   if (Value.isArray()) {
1929     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1930     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1931       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1932                                    Value.getArrayInitializedElt(I), Usage))
1933         return false;
1934     }
1935     if (!Value.hasArrayFiller())
1936       return true;
1937     return CheckConstantExpression(Info, DiagLoc, EltTy, Value.getArrayFiller(),
1938                                    Usage);
1939   }
1940   if (Value.isUnion() && Value.getUnionField()) {
1941     return CheckConstantExpression(Info, DiagLoc,
1942                                    Value.getUnionField()->getType(),
1943                                    Value.getUnionValue(), Usage);
1944   }
1945   if (Value.isStruct()) {
1946     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1947     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1948       unsigned BaseIndex = 0;
1949       for (const CXXBaseSpecifier &BS : CD->bases()) {
1950         if (!CheckConstantExpression(Info, DiagLoc, BS.getType(),
1951                                      Value.getStructBase(BaseIndex), Usage))
1952           return false;
1953         ++BaseIndex;
1954       }
1955     }
1956     for (const auto *I : RD->fields()) {
1957       if (I->isUnnamedBitfield())
1958         continue;
1959 
1960       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1961                                    Value.getStructField(I->getFieldIndex()),
1962                                    Usage))
1963         return false;
1964     }
1965   }
1966 
1967   if (Value.isLValue()) {
1968     LValue LVal;
1969     LVal.setFrom(Info.Ctx, Value);
1970     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal, Usage);
1971   }
1972 
1973   if (Value.isMemberPointer())
1974     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value, Usage);
1975 
1976   // Everything else is fine.
1977   return true;
1978 }
1979 
1980 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1981   // A null base expression indicates a null pointer.  These are always
1982   // evaluatable, and they are false unless the offset is zero.
1983   if (!Value.getLValueBase()) {
1984     Result = !Value.getLValueOffset().isZero();
1985     return true;
1986   }
1987 
1988   // We have a non-null base.  These are generally known to be true, but if it's
1989   // a weak declaration it can be null at runtime.
1990   Result = true;
1991   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1992   return !Decl || !Decl->isWeak();
1993 }
1994 
1995 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1996   switch (Val.getKind()) {
1997   case APValue::Uninitialized:
1998     return false;
1999   case APValue::Int:
2000     Result = Val.getInt().getBoolValue();
2001     return true;
2002   case APValue::Float:
2003     Result = !Val.getFloat().isZero();
2004     return true;
2005   case APValue::ComplexInt:
2006     Result = Val.getComplexIntReal().getBoolValue() ||
2007              Val.getComplexIntImag().getBoolValue();
2008     return true;
2009   case APValue::ComplexFloat:
2010     Result = !Val.getComplexFloatReal().isZero() ||
2011              !Val.getComplexFloatImag().isZero();
2012     return true;
2013   case APValue::LValue:
2014     return EvalPointerValueAsBool(Val, Result);
2015   case APValue::MemberPointer:
2016     Result = Val.getMemberPointerDecl();
2017     return true;
2018   case APValue::Vector:
2019   case APValue::Array:
2020   case APValue::Struct:
2021   case APValue::Union:
2022   case APValue::AddrLabelDiff:
2023     return false;
2024   }
2025 
2026   llvm_unreachable("unknown APValue kind");
2027 }
2028 
2029 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
2030                                        EvalInfo &Info) {
2031   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
2032   APValue Val;
2033   if (!Evaluate(Val, Info, E))
2034     return false;
2035   return HandleConversionToBool(Val, Result);
2036 }
2037 
2038 template<typename T>
2039 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
2040                            const T &SrcValue, QualType DestType) {
2041   Info.CCEDiag(E, diag::note_constexpr_overflow)
2042     << SrcValue << DestType;
2043   return Info.noteUndefinedBehavior();
2044 }
2045 
2046 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
2047                                  QualType SrcType, const APFloat &Value,
2048                                  QualType DestType, APSInt &Result) {
2049   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2050   // Determine whether we are converting to unsigned or signed.
2051   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
2052 
2053   Result = APSInt(DestWidth, !DestSigned);
2054   bool ignored;
2055   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
2056       & APFloat::opInvalidOp)
2057     return HandleOverflow(Info, E, Value, DestType);
2058   return true;
2059 }
2060 
2061 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
2062                                    QualType SrcType, QualType DestType,
2063                                    APFloat &Result) {
2064   APFloat Value = Result;
2065   bool ignored;
2066   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
2067                      APFloat::rmNearestTiesToEven, &ignored)
2068       & APFloat::opOverflow)
2069     return HandleOverflow(Info, E, Value, DestType);
2070   return true;
2071 }
2072 
2073 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
2074                                  QualType DestType, QualType SrcType,
2075                                  const APSInt &Value) {
2076   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
2077   APSInt Result = Value;
2078   // Figure out if this is a truncate, extend or noop cast.
2079   // If the input is signed, do a sign extend, noop, or truncate.
2080   Result = Result.extOrTrunc(DestWidth);
2081   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
2082   return Result;
2083 }
2084 
2085 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
2086                                  QualType SrcType, const APSInt &Value,
2087                                  QualType DestType, APFloat &Result) {
2088   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
2089   if (Result.convertFromAPInt(Value, Value.isSigned(),
2090                               APFloat::rmNearestTiesToEven)
2091       & APFloat::opOverflow)
2092     return HandleOverflow(Info, E, Value, DestType);
2093   return true;
2094 }
2095 
2096 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
2097                                   APValue &Value, const FieldDecl *FD) {
2098   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
2099 
2100   if (!Value.isInt()) {
2101     // Trying to store a pointer-cast-to-integer into a bitfield.
2102     // FIXME: In this case, we should provide the diagnostic for casting
2103     // a pointer to an integer.
2104     assert(Value.isLValue() && "integral value neither int nor lvalue?");
2105     Info.FFDiag(E);
2106     return false;
2107   }
2108 
2109   APSInt &Int = Value.getInt();
2110   unsigned OldBitWidth = Int.getBitWidth();
2111   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2112   if (NewBitWidth < OldBitWidth)
2113     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2114   return true;
2115 }
2116 
2117 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2118                                   llvm::APInt &Res) {
2119   APValue SVal;
2120   if (!Evaluate(SVal, Info, E))
2121     return false;
2122   if (SVal.isInt()) {
2123     Res = SVal.getInt();
2124     return true;
2125   }
2126   if (SVal.isFloat()) {
2127     Res = SVal.getFloat().bitcastToAPInt();
2128     return true;
2129   }
2130   if (SVal.isVector()) {
2131     QualType VecTy = E->getType();
2132     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2133     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2134     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2135     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2136     Res = llvm::APInt::getNullValue(VecSize);
2137     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2138       APValue &Elt = SVal.getVectorElt(i);
2139       llvm::APInt EltAsInt;
2140       if (Elt.isInt()) {
2141         EltAsInt = Elt.getInt();
2142       } else if (Elt.isFloat()) {
2143         EltAsInt = Elt.getFloat().bitcastToAPInt();
2144       } else {
2145         // Don't try to handle vectors of anything other than int or float
2146         // (not sure if it's possible to hit this case).
2147         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2148         return false;
2149       }
2150       unsigned BaseEltSize = EltAsInt.getBitWidth();
2151       if (BigEndian)
2152         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2153       else
2154         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2155     }
2156     return true;
2157   }
2158   // Give up if the input isn't an int, float, or vector.  For example, we
2159   // reject "(v4i16)(intptr_t)&a".
2160   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2161   return false;
2162 }
2163 
2164 /// Perform the given integer operation, which is known to need at most BitWidth
2165 /// bits, and check for overflow in the original type (if that type was not an
2166 /// unsigned type).
2167 template<typename Operation>
2168 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2169                                  const APSInt &LHS, const APSInt &RHS,
2170                                  unsigned BitWidth, Operation Op,
2171                                  APSInt &Result) {
2172   if (LHS.isUnsigned()) {
2173     Result = Op(LHS, RHS);
2174     return true;
2175   }
2176 
2177   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2178   Result = Value.trunc(LHS.getBitWidth());
2179   if (Result.extend(BitWidth) != Value) {
2180     if (Info.checkingForOverflow())
2181       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2182                                        diag::warn_integer_constant_overflow)
2183           << Result.toString(10) << E->getType();
2184     else
2185       return HandleOverflow(Info, E, Value, E->getType());
2186   }
2187   return true;
2188 }
2189 
2190 /// Perform the given binary integer operation.
2191 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2192                               BinaryOperatorKind Opcode, APSInt RHS,
2193                               APSInt &Result) {
2194   switch (Opcode) {
2195   default:
2196     Info.FFDiag(E);
2197     return false;
2198   case BO_Mul:
2199     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2200                                 std::multiplies<APSInt>(), Result);
2201   case BO_Add:
2202     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2203                                 std::plus<APSInt>(), Result);
2204   case BO_Sub:
2205     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2206                                 std::minus<APSInt>(), Result);
2207   case BO_And: Result = LHS & RHS; return true;
2208   case BO_Xor: Result = LHS ^ RHS; return true;
2209   case BO_Or:  Result = LHS | RHS; return true;
2210   case BO_Div:
2211   case BO_Rem:
2212     if (RHS == 0) {
2213       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2214       return false;
2215     }
2216     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2217     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2218     // this operation and gives the two's complement result.
2219     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2220         LHS.isSigned() && LHS.isMinSignedValue())
2221       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2222                             E->getType());
2223     return true;
2224   case BO_Shl: {
2225     if (Info.getLangOpts().OpenCL)
2226       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2227       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2228                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2229                     RHS.isUnsigned());
2230     else if (RHS.isSigned() && RHS.isNegative()) {
2231       // During constant-folding, a negative shift is an opposite shift. Such
2232       // a shift is not a constant expression.
2233       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2234       RHS = -RHS;
2235       goto shift_right;
2236     }
2237   shift_left:
2238     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2239     // the shifted type.
2240     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2241     if (SA != RHS) {
2242       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2243         << RHS << E->getType() << LHS.getBitWidth();
2244     } else if (LHS.isSigned()) {
2245       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2246       // operand, and must not overflow the corresponding unsigned type.
2247       if (LHS.isNegative())
2248         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2249       else if (LHS.countLeadingZeros() < SA)
2250         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2251     }
2252     Result = LHS << SA;
2253     return true;
2254   }
2255   case BO_Shr: {
2256     if (Info.getLangOpts().OpenCL)
2257       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2258       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2259                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2260                     RHS.isUnsigned());
2261     else if (RHS.isSigned() && RHS.isNegative()) {
2262       // During constant-folding, a negative shift is an opposite shift. Such a
2263       // shift is not a constant expression.
2264       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2265       RHS = -RHS;
2266       goto shift_left;
2267     }
2268   shift_right:
2269     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2270     // shifted type.
2271     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2272     if (SA != RHS)
2273       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2274         << RHS << E->getType() << LHS.getBitWidth();
2275     Result = LHS >> SA;
2276     return true;
2277   }
2278 
2279   case BO_LT: Result = LHS < RHS; return true;
2280   case BO_GT: Result = LHS > RHS; return true;
2281   case BO_LE: Result = LHS <= RHS; return true;
2282   case BO_GE: Result = LHS >= RHS; return true;
2283   case BO_EQ: Result = LHS == RHS; return true;
2284   case BO_NE: Result = LHS != RHS; return true;
2285   case BO_Cmp:
2286     llvm_unreachable("BO_Cmp should be handled elsewhere");
2287   }
2288 }
2289 
2290 /// Perform the given binary floating-point operation, in-place, on LHS.
2291 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2292                                   APFloat &LHS, BinaryOperatorKind Opcode,
2293                                   const APFloat &RHS) {
2294   switch (Opcode) {
2295   default:
2296     Info.FFDiag(E);
2297     return false;
2298   case BO_Mul:
2299     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2300     break;
2301   case BO_Add:
2302     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2303     break;
2304   case BO_Sub:
2305     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2306     break;
2307   case BO_Div:
2308     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2309     break;
2310   }
2311 
2312   if (LHS.isInfinity() || LHS.isNaN()) {
2313     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2314     return Info.noteUndefinedBehavior();
2315   }
2316   return true;
2317 }
2318 
2319 /// Cast an lvalue referring to a base subobject to a derived class, by
2320 /// truncating the lvalue's path to the given length.
2321 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2322                                const RecordDecl *TruncatedType,
2323                                unsigned TruncatedElements) {
2324   SubobjectDesignator &D = Result.Designator;
2325 
2326   // Check we actually point to a derived class object.
2327   if (TruncatedElements == D.Entries.size())
2328     return true;
2329   assert(TruncatedElements >= D.MostDerivedPathLength &&
2330          "not casting to a derived class");
2331   if (!Result.checkSubobject(Info, E, CSK_Derived))
2332     return false;
2333 
2334   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2335   const RecordDecl *RD = TruncatedType;
2336   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2337     if (RD->isInvalidDecl()) return false;
2338     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2339     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2340     if (isVirtualBaseClass(D.Entries[I]))
2341       Result.Offset -= Layout.getVBaseClassOffset(Base);
2342     else
2343       Result.Offset -= Layout.getBaseClassOffset(Base);
2344     RD = Base;
2345   }
2346   D.Entries.resize(TruncatedElements);
2347   return true;
2348 }
2349 
2350 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2351                                    const CXXRecordDecl *Derived,
2352                                    const CXXRecordDecl *Base,
2353                                    const ASTRecordLayout *RL = nullptr) {
2354   if (!RL) {
2355     if (Derived->isInvalidDecl()) return false;
2356     RL = &Info.Ctx.getASTRecordLayout(Derived);
2357   }
2358 
2359   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2360   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2361   return true;
2362 }
2363 
2364 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2365                              const CXXRecordDecl *DerivedDecl,
2366                              const CXXBaseSpecifier *Base) {
2367   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2368 
2369   if (!Base->isVirtual())
2370     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2371 
2372   SubobjectDesignator &D = Obj.Designator;
2373   if (D.Invalid)
2374     return false;
2375 
2376   // Extract most-derived object and corresponding type.
2377   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2378   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2379     return false;
2380 
2381   // Find the virtual base class.
2382   if (DerivedDecl->isInvalidDecl()) return false;
2383   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2384   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2385   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2386   return true;
2387 }
2388 
2389 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2390                                  QualType Type, LValue &Result) {
2391   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2392                                      PathE = E->path_end();
2393        PathI != PathE; ++PathI) {
2394     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2395                           *PathI))
2396       return false;
2397     Type = (*PathI)->getType();
2398   }
2399   return true;
2400 }
2401 
2402 /// Update LVal to refer to the given field, which must be a member of the type
2403 /// currently described by LVal.
2404 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2405                                const FieldDecl *FD,
2406                                const ASTRecordLayout *RL = nullptr) {
2407   if (!RL) {
2408     if (FD->getParent()->isInvalidDecl()) return false;
2409     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2410   }
2411 
2412   unsigned I = FD->getFieldIndex();
2413   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2414   LVal.addDecl(Info, E, FD);
2415   return true;
2416 }
2417 
2418 /// Update LVal to refer to the given indirect field.
2419 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2420                                        LValue &LVal,
2421                                        const IndirectFieldDecl *IFD) {
2422   for (const auto *C : IFD->chain())
2423     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2424       return false;
2425   return true;
2426 }
2427 
2428 /// Get the size of the given type in char units.
2429 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2430                          QualType Type, CharUnits &Size) {
2431   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2432   // extension.
2433   if (Type->isVoidType() || Type->isFunctionType()) {
2434     Size = CharUnits::One();
2435     return true;
2436   }
2437 
2438   if (Type->isDependentType()) {
2439     Info.FFDiag(Loc);
2440     return false;
2441   }
2442 
2443   if (!Type->isConstantSizeType()) {
2444     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2445     // FIXME: Better diagnostic.
2446     Info.FFDiag(Loc);
2447     return false;
2448   }
2449 
2450   Size = Info.Ctx.getTypeSizeInChars(Type);
2451   return true;
2452 }
2453 
2454 /// Update a pointer value to model pointer arithmetic.
2455 /// \param Info - Information about the ongoing evaluation.
2456 /// \param E - The expression being evaluated, for diagnostic purposes.
2457 /// \param LVal - The pointer value to be updated.
2458 /// \param EltTy - The pointee type represented by LVal.
2459 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2460 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2461                                         LValue &LVal, QualType EltTy,
2462                                         APSInt Adjustment) {
2463   CharUnits SizeOfPointee;
2464   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2465     return false;
2466 
2467   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2468   return true;
2469 }
2470 
2471 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2472                                         LValue &LVal, QualType EltTy,
2473                                         int64_t Adjustment) {
2474   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2475                                      APSInt::get(Adjustment));
2476 }
2477 
2478 /// Update an lvalue to refer to a component of a complex number.
2479 /// \param Info - Information about the ongoing evaluation.
2480 /// \param LVal - The lvalue to be updated.
2481 /// \param EltTy - The complex number's component type.
2482 /// \param Imag - False for the real component, true for the imaginary.
2483 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2484                                        LValue &LVal, QualType EltTy,
2485                                        bool Imag) {
2486   if (Imag) {
2487     CharUnits SizeOfComponent;
2488     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2489       return false;
2490     LVal.Offset += SizeOfComponent;
2491   }
2492   LVal.addComplex(Info, E, EltTy, Imag);
2493   return true;
2494 }
2495 
2496 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2497                                            QualType Type, const LValue &LVal,
2498                                            APValue &RVal);
2499 
2500 /// Try to evaluate the initializer for a variable declaration.
2501 ///
2502 /// \param Info   Information about the ongoing evaluation.
2503 /// \param E      An expression to be used when printing diagnostics.
2504 /// \param VD     The variable whose initializer should be obtained.
2505 /// \param Frame  The frame in which the variable was created. Must be null
2506 ///               if this variable is not local to the evaluation.
2507 /// \param Result Filled in with a pointer to the value of the variable.
2508 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2509                                 const VarDecl *VD, CallStackFrame *Frame,
2510                                 APValue *&Result, const LValue *LVal) {
2511 
2512   // If this is a parameter to an active constexpr function call, perform
2513   // argument substitution.
2514   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2515     // Assume arguments of a potential constant expression are unknown
2516     // constant expressions.
2517     if (Info.checkingPotentialConstantExpression())
2518       return false;
2519     if (!Frame || !Frame->Arguments) {
2520       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2521       return false;
2522     }
2523     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2524     return true;
2525   }
2526 
2527   // If this is a local variable, dig out its value.
2528   if (Frame) {
2529     Result = LVal ? Frame->getTemporary(VD, LVal->getLValueVersion())
2530                   : Frame->getCurrentTemporary(VD);
2531     if (!Result) {
2532       // Assume variables referenced within a lambda's call operator that were
2533       // not declared within the call operator are captures and during checking
2534       // of a potential constant expression, assume they are unknown constant
2535       // expressions.
2536       assert(isLambdaCallOperator(Frame->Callee) &&
2537              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2538              "missing value for local variable");
2539       if (Info.checkingPotentialConstantExpression())
2540         return false;
2541       // FIXME: implement capture evaluation during constant expr evaluation.
2542       Info.FFDiag(E->getBeginLoc(),
2543                   diag::note_unimplemented_constexpr_lambda_feature_ast)
2544           << "captures not currently allowed";
2545       return false;
2546     }
2547     return true;
2548   }
2549 
2550   // Dig out the initializer, and use the declaration which it's attached to.
2551   const Expr *Init = VD->getAnyInitializer(VD);
2552   if (!Init || Init->isValueDependent()) {
2553     // If we're checking a potential constant expression, the variable could be
2554     // initialized later.
2555     if (!Info.checkingPotentialConstantExpression())
2556       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2557     return false;
2558   }
2559 
2560   // If we're currently evaluating the initializer of this declaration, use that
2561   // in-flight value.
2562   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2563     Result = Info.EvaluatingDeclValue;
2564     return true;
2565   }
2566 
2567   // Never evaluate the initializer of a weak variable. We can't be sure that
2568   // this is the definition which will be used.
2569   if (VD->isWeak()) {
2570     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2571     return false;
2572   }
2573 
2574   // Check that we can fold the initializer. In C++, we will have already done
2575   // this in the cases where it matters for conformance.
2576   SmallVector<PartialDiagnosticAt, 8> Notes;
2577   if (!VD->evaluateValue(Notes)) {
2578     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2579               Notes.size() + 1) << VD;
2580     Info.Note(VD->getLocation(), diag::note_declared_at);
2581     Info.addNotes(Notes);
2582     return false;
2583   } else if (!VD->checkInitIsICE()) {
2584     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2585                  Notes.size() + 1) << VD;
2586     Info.Note(VD->getLocation(), diag::note_declared_at);
2587     Info.addNotes(Notes);
2588   }
2589 
2590   Result = VD->getEvaluatedValue();
2591   return true;
2592 }
2593 
2594 static bool IsConstNonVolatile(QualType T) {
2595   Qualifiers Quals = T.getQualifiers();
2596   return Quals.hasConst() && !Quals.hasVolatile();
2597 }
2598 
2599 /// Get the base index of the given base class within an APValue representing
2600 /// the given derived class.
2601 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2602                              const CXXRecordDecl *Base) {
2603   Base = Base->getCanonicalDecl();
2604   unsigned Index = 0;
2605   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2606          E = Derived->bases_end(); I != E; ++I, ++Index) {
2607     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2608       return Index;
2609   }
2610 
2611   llvm_unreachable("base class missing from derived class's bases list");
2612 }
2613 
2614 /// Extract the value of a character from a string literal.
2615 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2616                                             uint64_t Index) {
2617   // FIXME: Support MakeStringConstant
2618   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2619     std::string Str;
2620     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2621     assert(Index <= Str.size() && "Index too large");
2622     return APSInt::getUnsigned(Str.c_str()[Index]);
2623   }
2624 
2625   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2626     Lit = PE->getFunctionName();
2627   const StringLiteral *S = cast<StringLiteral>(Lit);
2628   const ConstantArrayType *CAT =
2629       Info.Ctx.getAsConstantArrayType(S->getType());
2630   assert(CAT && "string literal isn't an array");
2631   QualType CharType = CAT->getElementType();
2632   assert(CharType->isIntegerType() && "unexpected character type");
2633 
2634   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2635                CharType->isUnsignedIntegerType());
2636   if (Index < S->getLength())
2637     Value = S->getCodeUnit(Index);
2638   return Value;
2639 }
2640 
2641 // Expand a string literal into an array of characters.
2642 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2643                                 APValue &Result) {
2644   const StringLiteral *S = cast<StringLiteral>(Lit);
2645   const ConstantArrayType *CAT =
2646       Info.Ctx.getAsConstantArrayType(S->getType());
2647   assert(CAT && "string literal isn't an array");
2648   QualType CharType = CAT->getElementType();
2649   assert(CharType->isIntegerType() && "unexpected character type");
2650 
2651   unsigned Elts = CAT->getSize().getZExtValue();
2652   Result = APValue(APValue::UninitArray(),
2653                    std::min(S->getLength(), Elts), Elts);
2654   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2655                CharType->isUnsignedIntegerType());
2656   if (Result.hasArrayFiller())
2657     Result.getArrayFiller() = APValue(Value);
2658   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2659     Value = S->getCodeUnit(I);
2660     Result.getArrayInitializedElt(I) = APValue(Value);
2661   }
2662 }
2663 
2664 // Expand an array so that it has more than Index filled elements.
2665 static void expandArray(APValue &Array, unsigned Index) {
2666   unsigned Size = Array.getArraySize();
2667   assert(Index < Size);
2668 
2669   // Always at least double the number of elements for which we store a value.
2670   unsigned OldElts = Array.getArrayInitializedElts();
2671   unsigned NewElts = std::max(Index+1, OldElts * 2);
2672   NewElts = std::min(Size, std::max(NewElts, 8u));
2673 
2674   // Copy the data across.
2675   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2676   for (unsigned I = 0; I != OldElts; ++I)
2677     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2678   for (unsigned I = OldElts; I != NewElts; ++I)
2679     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2680   if (NewValue.hasArrayFiller())
2681     NewValue.getArrayFiller() = Array.getArrayFiller();
2682   Array.swap(NewValue);
2683 }
2684 
2685 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2686 /// conversion. If it's of class type, we may assume that the copy operation
2687 /// is trivial. Note that this is never true for a union type with fields
2688 /// (because the copy always "reads" the active member) and always true for
2689 /// a non-class type.
2690 static bool isReadByLvalueToRvalueConversion(QualType T) {
2691   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2692   if (!RD || (RD->isUnion() && !RD->field_empty()))
2693     return true;
2694   if (RD->isEmpty())
2695     return false;
2696 
2697   for (auto *Field : RD->fields())
2698     if (isReadByLvalueToRvalueConversion(Field->getType()))
2699       return true;
2700 
2701   for (auto &BaseSpec : RD->bases())
2702     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2703       return true;
2704 
2705   return false;
2706 }
2707 
2708 /// Diagnose an attempt to read from any unreadable field within the specified
2709 /// type, which might be a class type.
2710 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2711                                      QualType T) {
2712   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2713   if (!RD)
2714     return false;
2715 
2716   if (!RD->hasMutableFields())
2717     return false;
2718 
2719   for (auto *Field : RD->fields()) {
2720     // If we're actually going to read this field in some way, then it can't
2721     // be mutable. If we're in a union, then assigning to a mutable field
2722     // (even an empty one) can change the active member, so that's not OK.
2723     // FIXME: Add core issue number for the union case.
2724     if (Field->isMutable() &&
2725         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2726       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2727       Info.Note(Field->getLocation(), diag::note_declared_at);
2728       return true;
2729     }
2730 
2731     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2732       return true;
2733   }
2734 
2735   for (auto &BaseSpec : RD->bases())
2736     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2737       return true;
2738 
2739   // All mutable fields were empty, and thus not actually read.
2740   return false;
2741 }
2742 
2743 /// Kinds of access we can perform on an object, for diagnostics.
2744 enum AccessKinds {
2745   AK_Read,
2746   AK_Assign,
2747   AK_Increment,
2748   AK_Decrement
2749 };
2750 
2751 namespace {
2752 /// A handle to a complete object (an object that is not a subobject of
2753 /// another object).
2754 struct CompleteObject {
2755   /// The value of the complete object.
2756   APValue *Value;
2757   /// The type of the complete object.
2758   QualType Type;
2759   bool LifetimeStartedInEvaluation;
2760 
2761   CompleteObject() : Value(nullptr) {}
2762   CompleteObject(APValue *Value, QualType Type,
2763                  bool LifetimeStartedInEvaluation)
2764       : Value(Value), Type(Type),
2765         LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2766     assert(Value && "missing value for complete object");
2767   }
2768 
2769   explicit operator bool() const { return Value; }
2770 };
2771 } // end anonymous namespace
2772 
2773 /// Find the designated sub-object of an rvalue.
2774 template<typename SubobjectHandler>
2775 typename SubobjectHandler::result_type
2776 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2777               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2778   if (Sub.Invalid)
2779     // A diagnostic will have already been produced.
2780     return handler.failed();
2781   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2782     if (Info.getLangOpts().CPlusPlus11)
2783       Info.FFDiag(E, Sub.isOnePastTheEnd()
2784                          ? diag::note_constexpr_access_past_end
2785                          : diag::note_constexpr_access_unsized_array)
2786           << handler.AccessKind;
2787     else
2788       Info.FFDiag(E);
2789     return handler.failed();
2790   }
2791 
2792   APValue *O = Obj.Value;
2793   QualType ObjType = Obj.Type;
2794   const FieldDecl *LastField = nullptr;
2795   const bool MayReadMutableMembers =
2796       Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2797 
2798   // Walk the designator's path to find the subobject.
2799   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2800     if (O->isUninit()) {
2801       if (!Info.checkingPotentialConstantExpression())
2802         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2803       return handler.failed();
2804     }
2805 
2806     if (I == N) {
2807       // If we are reading an object of class type, there may still be more
2808       // things we need to check: if there are any mutable subobjects, we
2809       // cannot perform this read. (This only happens when performing a trivial
2810       // copy or assignment.)
2811       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2812           !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2813         return handler.failed();
2814 
2815       if (!handler.found(*O, ObjType))
2816         return false;
2817 
2818       // If we modified a bit-field, truncate it to the right width.
2819       if (handler.AccessKind != AK_Read &&
2820           LastField && LastField->isBitField() &&
2821           !truncateBitfieldValue(Info, E, *O, LastField))
2822         return false;
2823 
2824       return true;
2825     }
2826 
2827     LastField = nullptr;
2828     if (ObjType->isArrayType()) {
2829       // Next subobject is an array element.
2830       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2831       assert(CAT && "vla in literal type?");
2832       uint64_t Index = Sub.Entries[I].ArrayIndex;
2833       if (CAT->getSize().ule(Index)) {
2834         // Note, it should not be possible to form a pointer with a valid
2835         // designator which points more than one past the end of the array.
2836         if (Info.getLangOpts().CPlusPlus11)
2837           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2838             << handler.AccessKind;
2839         else
2840           Info.FFDiag(E);
2841         return handler.failed();
2842       }
2843 
2844       ObjType = CAT->getElementType();
2845 
2846       // An array object is represented as either an Array APValue or as an
2847       // LValue which refers to a string literal.
2848       if (O->isLValue()) {
2849         assert(I == N - 1 && "extracting subobject of character?");
2850         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2851         if (handler.AccessKind != AK_Read)
2852           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2853                               *O);
2854         else
2855           return handler.foundString(*O, ObjType, Index);
2856       }
2857 
2858       if (O->getArrayInitializedElts() > Index)
2859         O = &O->getArrayInitializedElt(Index);
2860       else if (handler.AccessKind != AK_Read) {
2861         expandArray(*O, Index);
2862         O = &O->getArrayInitializedElt(Index);
2863       } else
2864         O = &O->getArrayFiller();
2865     } else if (ObjType->isAnyComplexType()) {
2866       // Next subobject is a complex number.
2867       uint64_t Index = Sub.Entries[I].ArrayIndex;
2868       if (Index > 1) {
2869         if (Info.getLangOpts().CPlusPlus11)
2870           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2871             << handler.AccessKind;
2872         else
2873           Info.FFDiag(E);
2874         return handler.failed();
2875       }
2876 
2877       bool WasConstQualified = ObjType.isConstQualified();
2878       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2879       if (WasConstQualified)
2880         ObjType.addConst();
2881 
2882       assert(I == N - 1 && "extracting subobject of scalar?");
2883       if (O->isComplexInt()) {
2884         return handler.found(Index ? O->getComplexIntImag()
2885                                    : O->getComplexIntReal(), ObjType);
2886       } else {
2887         assert(O->isComplexFloat());
2888         return handler.found(Index ? O->getComplexFloatImag()
2889                                    : O->getComplexFloatReal(), ObjType);
2890       }
2891     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2892       // In C++14 onwards, it is permitted to read a mutable member whose
2893       // lifetime began within the evaluation.
2894       // FIXME: Should we also allow this in C++11?
2895       if (Field->isMutable() && handler.AccessKind == AK_Read &&
2896           !MayReadMutableMembers) {
2897         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2898           << Field;
2899         Info.Note(Field->getLocation(), diag::note_declared_at);
2900         return handler.failed();
2901       }
2902 
2903       // Next subobject is a class, struct or union field.
2904       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2905       if (RD->isUnion()) {
2906         const FieldDecl *UnionField = O->getUnionField();
2907         if (!UnionField ||
2908             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2909           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2910             << handler.AccessKind << Field << !UnionField << UnionField;
2911           return handler.failed();
2912         }
2913         O = &O->getUnionValue();
2914       } else
2915         O = &O->getStructField(Field->getFieldIndex());
2916 
2917       bool WasConstQualified = ObjType.isConstQualified();
2918       ObjType = Field->getType();
2919       if (WasConstQualified && !Field->isMutable())
2920         ObjType.addConst();
2921 
2922       if (ObjType.isVolatileQualified()) {
2923         if (Info.getLangOpts().CPlusPlus) {
2924           // FIXME: Include a description of the path to the volatile subobject.
2925           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2926             << handler.AccessKind << 2 << Field;
2927           Info.Note(Field->getLocation(), diag::note_declared_at);
2928         } else {
2929           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2930         }
2931         return handler.failed();
2932       }
2933 
2934       LastField = Field;
2935     } else {
2936       // Next subobject is a base class.
2937       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2938       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2939       O = &O->getStructBase(getBaseIndex(Derived, Base));
2940 
2941       bool WasConstQualified = ObjType.isConstQualified();
2942       ObjType = Info.Ctx.getRecordType(Base);
2943       if (WasConstQualified)
2944         ObjType.addConst();
2945     }
2946   }
2947 }
2948 
2949 namespace {
2950 struct ExtractSubobjectHandler {
2951   EvalInfo &Info;
2952   APValue &Result;
2953 
2954   static const AccessKinds AccessKind = AK_Read;
2955 
2956   typedef bool result_type;
2957   bool failed() { return false; }
2958   bool found(APValue &Subobj, QualType SubobjType) {
2959     Result = Subobj;
2960     return true;
2961   }
2962   bool found(APSInt &Value, QualType SubobjType) {
2963     Result = APValue(Value);
2964     return true;
2965   }
2966   bool found(APFloat &Value, QualType SubobjType) {
2967     Result = APValue(Value);
2968     return true;
2969   }
2970   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2971     Result = APValue(extractStringLiteralCharacter(
2972         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2973     return true;
2974   }
2975 };
2976 } // end anonymous namespace
2977 
2978 const AccessKinds ExtractSubobjectHandler::AccessKind;
2979 
2980 /// Extract the designated sub-object of an rvalue.
2981 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2982                              const CompleteObject &Obj,
2983                              const SubobjectDesignator &Sub,
2984                              APValue &Result) {
2985   ExtractSubobjectHandler Handler = { Info, Result };
2986   return findSubobject(Info, E, Obj, Sub, Handler);
2987 }
2988 
2989 namespace {
2990 struct ModifySubobjectHandler {
2991   EvalInfo &Info;
2992   APValue &NewVal;
2993   const Expr *E;
2994 
2995   typedef bool result_type;
2996   static const AccessKinds AccessKind = AK_Assign;
2997 
2998   bool checkConst(QualType QT) {
2999     // Assigning to a const object has undefined behavior.
3000     if (QT.isConstQualified()) {
3001       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3002       return false;
3003     }
3004     return true;
3005   }
3006 
3007   bool failed() { return false; }
3008   bool found(APValue &Subobj, QualType SubobjType) {
3009     if (!checkConst(SubobjType))
3010       return false;
3011     // We've been given ownership of NewVal, so just swap it in.
3012     Subobj.swap(NewVal);
3013     return true;
3014   }
3015   bool found(APSInt &Value, QualType SubobjType) {
3016     if (!checkConst(SubobjType))
3017       return false;
3018     if (!NewVal.isInt()) {
3019       // Maybe trying to write a cast pointer value into a complex?
3020       Info.FFDiag(E);
3021       return false;
3022     }
3023     Value = NewVal.getInt();
3024     return true;
3025   }
3026   bool found(APFloat &Value, QualType SubobjType) {
3027     if (!checkConst(SubobjType))
3028       return false;
3029     Value = NewVal.getFloat();
3030     return true;
3031   }
3032   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3033     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
3034   }
3035 };
3036 } // end anonymous namespace
3037 
3038 const AccessKinds ModifySubobjectHandler::AccessKind;
3039 
3040 /// Update the designated sub-object of an rvalue to the given value.
3041 static bool modifySubobject(EvalInfo &Info, const Expr *E,
3042                             const CompleteObject &Obj,
3043                             const SubobjectDesignator &Sub,
3044                             APValue &NewVal) {
3045   ModifySubobjectHandler Handler = { Info, NewVal, E };
3046   return findSubobject(Info, E, Obj, Sub, Handler);
3047 }
3048 
3049 /// Find the position where two subobject designators diverge, or equivalently
3050 /// the length of the common initial subsequence.
3051 static unsigned FindDesignatorMismatch(QualType ObjType,
3052                                        const SubobjectDesignator &A,
3053                                        const SubobjectDesignator &B,
3054                                        bool &WasArrayIndex) {
3055   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
3056   for (/**/; I != N; ++I) {
3057     if (!ObjType.isNull() &&
3058         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
3059       // Next subobject is an array element.
3060       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
3061         WasArrayIndex = true;
3062         return I;
3063       }
3064       if (ObjType->isAnyComplexType())
3065         ObjType = ObjType->castAs<ComplexType>()->getElementType();
3066       else
3067         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
3068     } else {
3069       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
3070         WasArrayIndex = false;
3071         return I;
3072       }
3073       if (const FieldDecl *FD = getAsField(A.Entries[I]))
3074         // Next subobject is a field.
3075         ObjType = FD->getType();
3076       else
3077         // Next subobject is a base class.
3078         ObjType = QualType();
3079     }
3080   }
3081   WasArrayIndex = false;
3082   return I;
3083 }
3084 
3085 /// Determine whether the given subobject designators refer to elements of the
3086 /// same array object.
3087 static bool AreElementsOfSameArray(QualType ObjType,
3088                                    const SubobjectDesignator &A,
3089                                    const SubobjectDesignator &B) {
3090   if (A.Entries.size() != B.Entries.size())
3091     return false;
3092 
3093   bool IsArray = A.MostDerivedIsArrayElement;
3094   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
3095     // A is a subobject of the array element.
3096     return false;
3097 
3098   // If A (and B) designates an array element, the last entry will be the array
3099   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
3100   // of length 1' case, and the entire path must match.
3101   bool WasArrayIndex;
3102   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
3103   return CommonLength >= A.Entries.size() - IsArray;
3104 }
3105 
3106 /// Find the complete object to which an LValue refers.
3107 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
3108                                          AccessKinds AK, const LValue &LVal,
3109                                          QualType LValType) {
3110   if (!LVal.Base) {
3111     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3112     return CompleteObject();
3113   }
3114 
3115   CallStackFrame *Frame = nullptr;
3116   if (LVal.getLValueCallIndex()) {
3117     Frame = Info.getCallFrame(LVal.getLValueCallIndex());
3118     if (!Frame) {
3119       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3120         << AK << LVal.Base.is<const ValueDecl*>();
3121       NoteLValueLocation(Info, LVal.Base);
3122       return CompleteObject();
3123     }
3124   }
3125 
3126   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3127   // is not a constant expression (even if the object is non-volatile). We also
3128   // apply this rule to C++98, in order to conform to the expected 'volatile'
3129   // semantics.
3130   if (LValType.isVolatileQualified()) {
3131     if (Info.getLangOpts().CPlusPlus)
3132       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3133         << AK << LValType;
3134     else
3135       Info.FFDiag(E);
3136     return CompleteObject();
3137   }
3138 
3139   // Compute value storage location and type of base object.
3140   APValue *BaseVal = nullptr;
3141   QualType BaseType = getType(LVal.Base);
3142   bool LifetimeStartedInEvaluation = Frame;
3143 
3144   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3145     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3146     // In C++11, constexpr, non-volatile variables initialized with constant
3147     // expressions are constant expressions too. Inside constexpr functions,
3148     // parameters are constant expressions even if they're non-const.
3149     // In C++1y, objects local to a constant expression (those with a Frame) are
3150     // both readable and writable inside constant expressions.
3151     // In C, such things can also be folded, although they are not ICEs.
3152     const VarDecl *VD = dyn_cast<VarDecl>(D);
3153     if (VD) {
3154       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3155         VD = VDef;
3156     }
3157     if (!VD || VD->isInvalidDecl()) {
3158       Info.FFDiag(E);
3159       return CompleteObject();
3160     }
3161 
3162     // Accesses of volatile-qualified objects are not allowed.
3163     if (BaseType.isVolatileQualified()) {
3164       if (Info.getLangOpts().CPlusPlus) {
3165         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3166           << AK << 1 << VD;
3167         Info.Note(VD->getLocation(), diag::note_declared_at);
3168       } else {
3169         Info.FFDiag(E);
3170       }
3171       return CompleteObject();
3172     }
3173 
3174     // Unless we're looking at a local variable or argument in a constexpr call,
3175     // the variable we're reading must be const.
3176     if (!Frame) {
3177       if (Info.getLangOpts().CPlusPlus14 &&
3178           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3179         // OK, we can read and modify an object if we're in the process of
3180         // evaluating its initializer, because its lifetime began in this
3181         // evaluation.
3182       } else if (AK != AK_Read) {
3183         // All the remaining cases only permit reading.
3184         Info.FFDiag(E, diag::note_constexpr_modify_global);
3185         return CompleteObject();
3186       } else if (VD->isConstexpr()) {
3187         // OK, we can read this variable.
3188       } else if (BaseType->isIntegralOrEnumerationType()) {
3189         // In OpenCL if a variable is in constant address space it is a const value.
3190         if (!(BaseType.isConstQualified() ||
3191               (Info.getLangOpts().OpenCL &&
3192                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3193           if (Info.getLangOpts().CPlusPlus) {
3194             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3195             Info.Note(VD->getLocation(), diag::note_declared_at);
3196           } else {
3197             Info.FFDiag(E);
3198           }
3199           return CompleteObject();
3200         }
3201       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3202         // We support folding of const floating-point types, in order to make
3203         // static const data members of such types (supported as an extension)
3204         // more useful.
3205         if (Info.getLangOpts().CPlusPlus11) {
3206           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3207           Info.Note(VD->getLocation(), diag::note_declared_at);
3208         } else {
3209           Info.CCEDiag(E);
3210         }
3211       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3212         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3213         // Keep evaluating to see what we can do.
3214       } else {
3215         // FIXME: Allow folding of values of any literal type in all languages.
3216         if (Info.checkingPotentialConstantExpression() &&
3217             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3218           // The definition of this variable could be constexpr. We can't
3219           // access it right now, but may be able to in future.
3220         } else if (Info.getLangOpts().CPlusPlus11) {
3221           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3222           Info.Note(VD->getLocation(), diag::note_declared_at);
3223         } else {
3224           Info.FFDiag(E);
3225         }
3226         return CompleteObject();
3227       }
3228     }
3229 
3230     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal, &LVal))
3231       return CompleteObject();
3232   } else {
3233     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3234 
3235     if (!Frame) {
3236       if (const MaterializeTemporaryExpr *MTE =
3237               dyn_cast<MaterializeTemporaryExpr>(Base)) {
3238         assert(MTE->getStorageDuration() == SD_Static &&
3239                "should have a frame for a non-global materialized temporary");
3240 
3241         // Per C++1y [expr.const]p2:
3242         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3243         //   - a [...] glvalue of integral or enumeration type that refers to
3244         //     a non-volatile const object [...]
3245         //   [...]
3246         //   - a [...] glvalue of literal type that refers to a non-volatile
3247         //     object whose lifetime began within the evaluation of e.
3248         //
3249         // C++11 misses the 'began within the evaluation of e' check and
3250         // instead allows all temporaries, including things like:
3251         //   int &&r = 1;
3252         //   int x = ++r;
3253         //   constexpr int k = r;
3254         // Therefore we use the C++14 rules in C++11 too.
3255         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3256         const ValueDecl *ED = MTE->getExtendingDecl();
3257         if (!(BaseType.isConstQualified() &&
3258               BaseType->isIntegralOrEnumerationType()) &&
3259             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3260           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3261           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3262           return CompleteObject();
3263         }
3264 
3265         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3266         assert(BaseVal && "got reference to unevaluated temporary");
3267         LifetimeStartedInEvaluation = true;
3268       } else {
3269         Info.FFDiag(E);
3270         return CompleteObject();
3271       }
3272     } else {
3273       BaseVal = Frame->getTemporary(Base, LVal.Base.getVersion());
3274       assert(BaseVal && "missing value for temporary");
3275     }
3276 
3277     // Volatile temporary objects cannot be accessed in constant expressions.
3278     if (BaseType.isVolatileQualified()) {
3279       if (Info.getLangOpts().CPlusPlus) {
3280         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3281           << AK << 0;
3282         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3283       } else {
3284         Info.FFDiag(E);
3285       }
3286       return CompleteObject();
3287     }
3288   }
3289 
3290   // During the construction of an object, it is not yet 'const'.
3291   // FIXME: This doesn't do quite the right thing for const subobjects of the
3292   // object under construction.
3293   if (Info.isEvaluatingConstructor(LVal.getLValueBase(),
3294                                    LVal.getLValueCallIndex(),
3295                                    LVal.getLValueVersion())) {
3296     BaseType = Info.Ctx.getCanonicalType(BaseType);
3297     BaseType.removeLocalConst();
3298     LifetimeStartedInEvaluation = true;
3299   }
3300 
3301   // In C++14, we can't safely access any mutable state when we might be
3302   // evaluating after an unmodeled side effect.
3303   //
3304   // FIXME: Not all local state is mutable. Allow local constant subobjects
3305   // to be read here (but take care with 'mutable' fields).
3306   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3307        Info.EvalStatus.HasSideEffects) ||
3308       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3309     return CompleteObject();
3310 
3311   return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3312 }
3313 
3314 /// Perform an lvalue-to-rvalue conversion on the given glvalue. This
3315 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3316 /// glvalue referred to by an entity of reference type.
3317 ///
3318 /// \param Info - Information about the ongoing evaluation.
3319 /// \param Conv - The expression for which we are performing the conversion.
3320 ///               Used for diagnostics.
3321 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3322 ///               case of a non-class type).
3323 /// \param LVal - The glvalue on which we are attempting to perform this action.
3324 /// \param RVal - The produced value will be placed here.
3325 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3326                                            QualType Type,
3327                                            const LValue &LVal, APValue &RVal) {
3328   if (LVal.Designator.Invalid)
3329     return false;
3330 
3331   // Check for special cases where there is no existing APValue to look at.
3332   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3333   if (Base && !LVal.getLValueCallIndex() && !Type.isVolatileQualified()) {
3334     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3335       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3336       // initializer until now for such expressions. Such an expression can't be
3337       // an ICE in C, so this only matters for fold.
3338       if (Type.isVolatileQualified()) {
3339         Info.FFDiag(Conv);
3340         return false;
3341       }
3342       APValue Lit;
3343       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3344         return false;
3345       CompleteObject LitObj(&Lit, Base->getType(), false);
3346       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3347     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3348       // We represent a string literal array as an lvalue pointing at the
3349       // corresponding expression, rather than building an array of chars.
3350       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3351       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3352       CompleteObject StrObj(&Str, Base->getType(), false);
3353       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3354     }
3355   }
3356 
3357   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3358   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3359 }
3360 
3361 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3362 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3363                              QualType LValType, APValue &Val) {
3364   if (LVal.Designator.Invalid)
3365     return false;
3366 
3367   if (!Info.getLangOpts().CPlusPlus14) {
3368     Info.FFDiag(E);
3369     return false;
3370   }
3371 
3372   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3373   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3374 }
3375 
3376 namespace {
3377 struct CompoundAssignSubobjectHandler {
3378   EvalInfo &Info;
3379   const Expr *E;
3380   QualType PromotedLHSType;
3381   BinaryOperatorKind Opcode;
3382   const APValue &RHS;
3383 
3384   static const AccessKinds AccessKind = AK_Assign;
3385 
3386   typedef bool result_type;
3387 
3388   bool checkConst(QualType QT) {
3389     // Assigning to a const object has undefined behavior.
3390     if (QT.isConstQualified()) {
3391       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3392       return false;
3393     }
3394     return true;
3395   }
3396 
3397   bool failed() { return false; }
3398   bool found(APValue &Subobj, QualType SubobjType) {
3399     switch (Subobj.getKind()) {
3400     case APValue::Int:
3401       return found(Subobj.getInt(), SubobjType);
3402     case APValue::Float:
3403       return found(Subobj.getFloat(), SubobjType);
3404     case APValue::ComplexInt:
3405     case APValue::ComplexFloat:
3406       // FIXME: Implement complex compound assignment.
3407       Info.FFDiag(E);
3408       return false;
3409     case APValue::LValue:
3410       return foundPointer(Subobj, SubobjType);
3411     default:
3412       // FIXME: can this happen?
3413       Info.FFDiag(E);
3414       return false;
3415     }
3416   }
3417   bool found(APSInt &Value, QualType SubobjType) {
3418     if (!checkConst(SubobjType))
3419       return false;
3420 
3421     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3422       // We don't support compound assignment on integer-cast-to-pointer
3423       // values.
3424       Info.FFDiag(E);
3425       return false;
3426     }
3427 
3428     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3429                                     SubobjType, Value);
3430     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3431       return false;
3432     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3433     return true;
3434   }
3435   bool found(APFloat &Value, QualType SubobjType) {
3436     return checkConst(SubobjType) &&
3437            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3438                                   Value) &&
3439            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3440            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3441   }
3442   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3443     if (!checkConst(SubobjType))
3444       return false;
3445 
3446     QualType PointeeType;
3447     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3448       PointeeType = PT->getPointeeType();
3449 
3450     if (PointeeType.isNull() || !RHS.isInt() ||
3451         (Opcode != BO_Add && Opcode != BO_Sub)) {
3452       Info.FFDiag(E);
3453       return false;
3454     }
3455 
3456     APSInt Offset = RHS.getInt();
3457     if (Opcode == BO_Sub)
3458       negateAsSigned(Offset);
3459 
3460     LValue LVal;
3461     LVal.setFrom(Info.Ctx, Subobj);
3462     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3463       return false;
3464     LVal.moveInto(Subobj);
3465     return true;
3466   }
3467   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3468     llvm_unreachable("shouldn't encounter string elements here");
3469   }
3470 };
3471 } // end anonymous namespace
3472 
3473 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3474 
3475 /// Perform a compound assignment of LVal <op>= RVal.
3476 static bool handleCompoundAssignment(
3477     EvalInfo &Info, const Expr *E,
3478     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3479     BinaryOperatorKind Opcode, const APValue &RVal) {
3480   if (LVal.Designator.Invalid)
3481     return false;
3482 
3483   if (!Info.getLangOpts().CPlusPlus14) {
3484     Info.FFDiag(E);
3485     return false;
3486   }
3487 
3488   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3489   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3490                                              RVal };
3491   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3492 }
3493 
3494 namespace {
3495 struct IncDecSubobjectHandler {
3496   EvalInfo &Info;
3497   const UnaryOperator *E;
3498   AccessKinds AccessKind;
3499   APValue *Old;
3500 
3501   typedef bool result_type;
3502 
3503   bool checkConst(QualType QT) {
3504     // Assigning to a const object has undefined behavior.
3505     if (QT.isConstQualified()) {
3506       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3507       return false;
3508     }
3509     return true;
3510   }
3511 
3512   bool failed() { return false; }
3513   bool found(APValue &Subobj, QualType SubobjType) {
3514     // Stash the old value. Also clear Old, so we don't clobber it later
3515     // if we're post-incrementing a complex.
3516     if (Old) {
3517       *Old = Subobj;
3518       Old = nullptr;
3519     }
3520 
3521     switch (Subobj.getKind()) {
3522     case APValue::Int:
3523       return found(Subobj.getInt(), SubobjType);
3524     case APValue::Float:
3525       return found(Subobj.getFloat(), SubobjType);
3526     case APValue::ComplexInt:
3527       return found(Subobj.getComplexIntReal(),
3528                    SubobjType->castAs<ComplexType>()->getElementType()
3529                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3530     case APValue::ComplexFloat:
3531       return found(Subobj.getComplexFloatReal(),
3532                    SubobjType->castAs<ComplexType>()->getElementType()
3533                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3534     case APValue::LValue:
3535       return foundPointer(Subobj, SubobjType);
3536     default:
3537       // FIXME: can this happen?
3538       Info.FFDiag(E);
3539       return false;
3540     }
3541   }
3542   bool found(APSInt &Value, QualType SubobjType) {
3543     if (!checkConst(SubobjType))
3544       return false;
3545 
3546     if (!SubobjType->isIntegerType()) {
3547       // We don't support increment / decrement on integer-cast-to-pointer
3548       // values.
3549       Info.FFDiag(E);
3550       return false;
3551     }
3552 
3553     if (Old) *Old = APValue(Value);
3554 
3555     // bool arithmetic promotes to int, and the conversion back to bool
3556     // doesn't reduce mod 2^n, so special-case it.
3557     if (SubobjType->isBooleanType()) {
3558       if (AccessKind == AK_Increment)
3559         Value = 1;
3560       else
3561         Value = !Value;
3562       return true;
3563     }
3564 
3565     bool WasNegative = Value.isNegative();
3566     if (AccessKind == AK_Increment) {
3567       ++Value;
3568 
3569       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3570         APSInt ActualValue(Value, /*IsUnsigned*/true);
3571         return HandleOverflow(Info, E, ActualValue, SubobjType);
3572       }
3573     } else {
3574       --Value;
3575 
3576       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3577         unsigned BitWidth = Value.getBitWidth();
3578         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3579         ActualValue.setBit(BitWidth);
3580         return HandleOverflow(Info, E, ActualValue, SubobjType);
3581       }
3582     }
3583     return true;
3584   }
3585   bool found(APFloat &Value, QualType SubobjType) {
3586     if (!checkConst(SubobjType))
3587       return false;
3588 
3589     if (Old) *Old = APValue(Value);
3590 
3591     APFloat One(Value.getSemantics(), 1);
3592     if (AccessKind == AK_Increment)
3593       Value.add(One, APFloat::rmNearestTiesToEven);
3594     else
3595       Value.subtract(One, APFloat::rmNearestTiesToEven);
3596     return true;
3597   }
3598   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3599     if (!checkConst(SubobjType))
3600       return false;
3601 
3602     QualType PointeeType;
3603     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3604       PointeeType = PT->getPointeeType();
3605     else {
3606       Info.FFDiag(E);
3607       return false;
3608     }
3609 
3610     LValue LVal;
3611     LVal.setFrom(Info.Ctx, Subobj);
3612     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3613                                      AccessKind == AK_Increment ? 1 : -1))
3614       return false;
3615     LVal.moveInto(Subobj);
3616     return true;
3617   }
3618   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3619     llvm_unreachable("shouldn't encounter string elements here");
3620   }
3621 };
3622 } // end anonymous namespace
3623 
3624 /// Perform an increment or decrement on LVal.
3625 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3626                          QualType LValType, bool IsIncrement, APValue *Old) {
3627   if (LVal.Designator.Invalid)
3628     return false;
3629 
3630   if (!Info.getLangOpts().CPlusPlus14) {
3631     Info.FFDiag(E);
3632     return false;
3633   }
3634 
3635   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3636   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3637   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3638   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3639 }
3640 
3641 /// Build an lvalue for the object argument of a member function call.
3642 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3643                                    LValue &This) {
3644   if (Object->getType()->isPointerType())
3645     return EvaluatePointer(Object, This, Info);
3646 
3647   if (Object->isGLValue())
3648     return EvaluateLValue(Object, This, Info);
3649 
3650   if (Object->getType()->isLiteralType(Info.Ctx))
3651     return EvaluateTemporary(Object, This, Info);
3652 
3653   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3654   return false;
3655 }
3656 
3657 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3658 /// lvalue referring to the result.
3659 ///
3660 /// \param Info - Information about the ongoing evaluation.
3661 /// \param LV - An lvalue referring to the base of the member pointer.
3662 /// \param RHS - The member pointer expression.
3663 /// \param IncludeMember - Specifies whether the member itself is included in
3664 ///        the resulting LValue subobject designator. This is not possible when
3665 ///        creating a bound member function.
3666 /// \return The field or method declaration to which the member pointer refers,
3667 ///         or 0 if evaluation fails.
3668 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3669                                                   QualType LVType,
3670                                                   LValue &LV,
3671                                                   const Expr *RHS,
3672                                                   bool IncludeMember = true) {
3673   MemberPtr MemPtr;
3674   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3675     return nullptr;
3676 
3677   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3678   // member value, the behavior is undefined.
3679   if (!MemPtr.getDecl()) {
3680     // FIXME: Specific diagnostic.
3681     Info.FFDiag(RHS);
3682     return nullptr;
3683   }
3684 
3685   if (MemPtr.isDerivedMember()) {
3686     // This is a member of some derived class. Truncate LV appropriately.
3687     // The end of the derived-to-base path for the base object must match the
3688     // derived-to-base path for the member pointer.
3689     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3690         LV.Designator.Entries.size()) {
3691       Info.FFDiag(RHS);
3692       return nullptr;
3693     }
3694     unsigned PathLengthToMember =
3695         LV.Designator.Entries.size() - MemPtr.Path.size();
3696     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3697       const CXXRecordDecl *LVDecl = getAsBaseClass(
3698           LV.Designator.Entries[PathLengthToMember + I]);
3699       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3700       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3701         Info.FFDiag(RHS);
3702         return nullptr;
3703       }
3704     }
3705 
3706     // Truncate the lvalue to the appropriate derived class.
3707     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3708                             PathLengthToMember))
3709       return nullptr;
3710   } else if (!MemPtr.Path.empty()) {
3711     // Extend the LValue path with the member pointer's path.
3712     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3713                                   MemPtr.Path.size() + IncludeMember);
3714 
3715     // Walk down to the appropriate base class.
3716     if (const PointerType *PT = LVType->getAs<PointerType>())
3717       LVType = PT->getPointeeType();
3718     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3719     assert(RD && "member pointer access on non-class-type expression");
3720     // The first class in the path is that of the lvalue.
3721     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3722       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3723       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3724         return nullptr;
3725       RD = Base;
3726     }
3727     // Finally cast to the class containing the member.
3728     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3729                                 MemPtr.getContainingRecord()))
3730       return nullptr;
3731   }
3732 
3733   // Add the member. Note that we cannot build bound member functions here.
3734   if (IncludeMember) {
3735     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3736       if (!HandleLValueMember(Info, RHS, LV, FD))
3737         return nullptr;
3738     } else if (const IndirectFieldDecl *IFD =
3739                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3740       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3741         return nullptr;
3742     } else {
3743       llvm_unreachable("can't construct reference to bound member function");
3744     }
3745   }
3746 
3747   return MemPtr.getDecl();
3748 }
3749 
3750 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3751                                                   const BinaryOperator *BO,
3752                                                   LValue &LV,
3753                                                   bool IncludeMember = true) {
3754   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3755 
3756   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3757     if (Info.noteFailure()) {
3758       MemberPtr MemPtr;
3759       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3760     }
3761     return nullptr;
3762   }
3763 
3764   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3765                                    BO->getRHS(), IncludeMember);
3766 }
3767 
3768 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3769 /// the provided lvalue, which currently refers to the base object.
3770 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3771                                     LValue &Result) {
3772   SubobjectDesignator &D = Result.Designator;
3773   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3774     return false;
3775 
3776   QualType TargetQT = E->getType();
3777   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3778     TargetQT = PT->getPointeeType();
3779 
3780   // Check this cast lands within the final derived-to-base subobject path.
3781   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3782     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3783       << D.MostDerivedType << TargetQT;
3784     return false;
3785   }
3786 
3787   // Check the type of the final cast. We don't need to check the path,
3788   // since a cast can only be formed if the path is unique.
3789   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3790   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3791   const CXXRecordDecl *FinalType;
3792   if (NewEntriesSize == D.MostDerivedPathLength)
3793     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3794   else
3795     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3796   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3797     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3798       << D.MostDerivedType << TargetQT;
3799     return false;
3800   }
3801 
3802   // Truncate the lvalue to the appropriate derived class.
3803   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3804 }
3805 
3806 namespace {
3807 enum EvalStmtResult {
3808   /// Evaluation failed.
3809   ESR_Failed,
3810   /// Hit a 'return' statement.
3811   ESR_Returned,
3812   /// Evaluation succeeded.
3813   ESR_Succeeded,
3814   /// Hit a 'continue' statement.
3815   ESR_Continue,
3816   /// Hit a 'break' statement.
3817   ESR_Break,
3818   /// Still scanning for 'case' or 'default' statement.
3819   ESR_CaseNotFound
3820 };
3821 }
3822 
3823 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3824   // We don't need to evaluate the initializer for a static local.
3825   if (!VD->hasLocalStorage())
3826     return true;
3827 
3828   LValue Result;
3829   APValue &Val = createTemporary(VD, true, Result, *Info.CurrentCall);
3830 
3831   const Expr *InitE = VD->getInit();
3832   if (!InitE) {
3833     Info.FFDiag(VD->getBeginLoc(), diag::note_constexpr_uninitialized)
3834         << false << VD->getType();
3835     Val = APValue();
3836     return false;
3837   }
3838 
3839   if (InitE->isValueDependent())
3840     return false;
3841 
3842   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3843     // Wipe out any partially-computed value, to allow tracking that this
3844     // evaluation failed.
3845     Val = APValue();
3846     return false;
3847   }
3848 
3849   return true;
3850 }
3851 
3852 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3853   bool OK = true;
3854 
3855   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3856     OK &= EvaluateVarDecl(Info, VD);
3857 
3858   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3859     for (auto *BD : DD->bindings())
3860       if (auto *VD = BD->getHoldingVar())
3861         OK &= EvaluateDecl(Info, VD);
3862 
3863   return OK;
3864 }
3865 
3866 
3867 /// Evaluate a condition (either a variable declaration or an expression).
3868 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3869                          const Expr *Cond, bool &Result) {
3870   FullExpressionRAII Scope(Info);
3871   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3872     return false;
3873   return EvaluateAsBooleanCondition(Cond, Result, Info);
3874 }
3875 
3876 namespace {
3877 /// A location where the result (returned value) of evaluating a
3878 /// statement should be stored.
3879 struct StmtResult {
3880   /// The APValue that should be filled in with the returned value.
3881   APValue &Value;
3882   /// The location containing the result, if any (used to support RVO).
3883   const LValue *Slot;
3884 };
3885 
3886 struct TempVersionRAII {
3887   CallStackFrame &Frame;
3888 
3889   TempVersionRAII(CallStackFrame &Frame) : Frame(Frame) {
3890     Frame.pushTempVersion();
3891   }
3892 
3893   ~TempVersionRAII() {
3894     Frame.popTempVersion();
3895   }
3896 };
3897 
3898 }
3899 
3900 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3901                                    const Stmt *S,
3902                                    const SwitchCase *SC = nullptr);
3903 
3904 /// Evaluate the body of a loop, and translate the result as appropriate.
3905 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3906                                        const Stmt *Body,
3907                                        const SwitchCase *Case = nullptr) {
3908   BlockScopeRAII Scope(Info);
3909   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3910   case ESR_Break:
3911     return ESR_Succeeded;
3912   case ESR_Succeeded:
3913   case ESR_Continue:
3914     return ESR_Continue;
3915   case ESR_Failed:
3916   case ESR_Returned:
3917   case ESR_CaseNotFound:
3918     return ESR;
3919   }
3920   llvm_unreachable("Invalid EvalStmtResult!");
3921 }
3922 
3923 /// Evaluate a switch statement.
3924 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3925                                      const SwitchStmt *SS) {
3926   BlockScopeRAII Scope(Info);
3927 
3928   // Evaluate the switch condition.
3929   APSInt Value;
3930   {
3931     FullExpressionRAII Scope(Info);
3932     if (const Stmt *Init = SS->getInit()) {
3933       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3934       if (ESR != ESR_Succeeded)
3935         return ESR;
3936     }
3937     if (SS->getConditionVariable() &&
3938         !EvaluateDecl(Info, SS->getConditionVariable()))
3939       return ESR_Failed;
3940     if (!EvaluateInteger(SS->getCond(), Value, Info))
3941       return ESR_Failed;
3942   }
3943 
3944   // Find the switch case corresponding to the value of the condition.
3945   // FIXME: Cache this lookup.
3946   const SwitchCase *Found = nullptr;
3947   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3948        SC = SC->getNextSwitchCase()) {
3949     if (isa<DefaultStmt>(SC)) {
3950       Found = SC;
3951       continue;
3952     }
3953 
3954     const CaseStmt *CS = cast<CaseStmt>(SC);
3955     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3956     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3957                               : LHS;
3958     if (LHS <= Value && Value <= RHS) {
3959       Found = SC;
3960       break;
3961     }
3962   }
3963 
3964   if (!Found)
3965     return ESR_Succeeded;
3966 
3967   // Search the switch body for the switch case and evaluate it from there.
3968   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3969   case ESR_Break:
3970     return ESR_Succeeded;
3971   case ESR_Succeeded:
3972   case ESR_Continue:
3973   case ESR_Failed:
3974   case ESR_Returned:
3975     return ESR;
3976   case ESR_CaseNotFound:
3977     // This can only happen if the switch case is nested within a statement
3978     // expression. We have no intention of supporting that.
3979     Info.FFDiag(Found->getBeginLoc(),
3980                 diag::note_constexpr_stmt_expr_unsupported);
3981     return ESR_Failed;
3982   }
3983   llvm_unreachable("Invalid EvalStmtResult!");
3984 }
3985 
3986 // Evaluate a statement.
3987 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3988                                    const Stmt *S, const SwitchCase *Case) {
3989   if (!Info.nextStep(S))
3990     return ESR_Failed;
3991 
3992   // If we're hunting down a 'case' or 'default' label, recurse through
3993   // substatements until we hit the label.
3994   if (Case) {
3995     // FIXME: We don't start the lifetime of objects whose initialization we
3996     // jump over. However, such objects must be of class type with a trivial
3997     // default constructor that initialize all subobjects, so must be empty,
3998     // so this almost never matters.
3999     switch (S->getStmtClass()) {
4000     case Stmt::CompoundStmtClass:
4001       // FIXME: Precompute which substatement of a compound statement we
4002       // would jump to, and go straight there rather than performing a
4003       // linear scan each time.
4004     case Stmt::LabelStmtClass:
4005     case Stmt::AttributedStmtClass:
4006     case Stmt::DoStmtClass:
4007       break;
4008 
4009     case Stmt::CaseStmtClass:
4010     case Stmt::DefaultStmtClass:
4011       if (Case == S)
4012         Case = nullptr;
4013       break;
4014 
4015     case Stmt::IfStmtClass: {
4016       // FIXME: Precompute which side of an 'if' we would jump to, and go
4017       // straight there rather than scanning both sides.
4018       const IfStmt *IS = cast<IfStmt>(S);
4019 
4020       // Wrap the evaluation in a block scope, in case it's a DeclStmt
4021       // preceded by our switch label.
4022       BlockScopeRAII Scope(Info);
4023 
4024       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
4025       if (ESR != ESR_CaseNotFound || !IS->getElse())
4026         return ESR;
4027       return EvaluateStmt(Result, Info, IS->getElse(), Case);
4028     }
4029 
4030     case Stmt::WhileStmtClass: {
4031       EvalStmtResult ESR =
4032           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
4033       if (ESR != ESR_Continue)
4034         return ESR;
4035       break;
4036     }
4037 
4038     case Stmt::ForStmtClass: {
4039       const ForStmt *FS = cast<ForStmt>(S);
4040       EvalStmtResult ESR =
4041           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
4042       if (ESR != ESR_Continue)
4043         return ESR;
4044       if (FS->getInc()) {
4045         FullExpressionRAII IncScope(Info);
4046         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4047           return ESR_Failed;
4048       }
4049       break;
4050     }
4051 
4052     case Stmt::DeclStmtClass:
4053       // FIXME: If the variable has initialization that can't be jumped over,
4054       // bail out of any immediately-surrounding compound-statement too.
4055     default:
4056       return ESR_CaseNotFound;
4057     }
4058   }
4059 
4060   switch (S->getStmtClass()) {
4061   default:
4062     if (const Expr *E = dyn_cast<Expr>(S)) {
4063       // Don't bother evaluating beyond an expression-statement which couldn't
4064       // be evaluated.
4065       FullExpressionRAII Scope(Info);
4066       if (!EvaluateIgnoredValue(Info, E))
4067         return ESR_Failed;
4068       return ESR_Succeeded;
4069     }
4070 
4071     Info.FFDiag(S->getBeginLoc());
4072     return ESR_Failed;
4073 
4074   case Stmt::NullStmtClass:
4075     return ESR_Succeeded;
4076 
4077   case Stmt::DeclStmtClass: {
4078     const DeclStmt *DS = cast<DeclStmt>(S);
4079     for (const auto *DclIt : DS->decls()) {
4080       // Each declaration initialization is its own full-expression.
4081       // FIXME: This isn't quite right; if we're performing aggregate
4082       // initialization, each braced subexpression is its own full-expression.
4083       FullExpressionRAII Scope(Info);
4084       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
4085         return ESR_Failed;
4086     }
4087     return ESR_Succeeded;
4088   }
4089 
4090   case Stmt::ReturnStmtClass: {
4091     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
4092     FullExpressionRAII Scope(Info);
4093     if (RetExpr &&
4094         !(Result.Slot
4095               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
4096               : Evaluate(Result.Value, Info, RetExpr)))
4097       return ESR_Failed;
4098     return ESR_Returned;
4099   }
4100 
4101   case Stmt::CompoundStmtClass: {
4102     BlockScopeRAII Scope(Info);
4103 
4104     const CompoundStmt *CS = cast<CompoundStmt>(S);
4105     for (const auto *BI : CS->body()) {
4106       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
4107       if (ESR == ESR_Succeeded)
4108         Case = nullptr;
4109       else if (ESR != ESR_CaseNotFound)
4110         return ESR;
4111     }
4112     return Case ? ESR_CaseNotFound : ESR_Succeeded;
4113   }
4114 
4115   case Stmt::IfStmtClass: {
4116     const IfStmt *IS = cast<IfStmt>(S);
4117 
4118     // Evaluate the condition, as either a var decl or as an expression.
4119     BlockScopeRAII Scope(Info);
4120     if (const Stmt *Init = IS->getInit()) {
4121       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
4122       if (ESR != ESR_Succeeded)
4123         return ESR;
4124     }
4125     bool Cond;
4126     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4127       return ESR_Failed;
4128 
4129     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4130       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4131       if (ESR != ESR_Succeeded)
4132         return ESR;
4133     }
4134     return ESR_Succeeded;
4135   }
4136 
4137   case Stmt::WhileStmtClass: {
4138     const WhileStmt *WS = cast<WhileStmt>(S);
4139     while (true) {
4140       BlockScopeRAII Scope(Info);
4141       bool Continue;
4142       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4143                         Continue))
4144         return ESR_Failed;
4145       if (!Continue)
4146         break;
4147 
4148       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4149       if (ESR != ESR_Continue)
4150         return ESR;
4151     }
4152     return ESR_Succeeded;
4153   }
4154 
4155   case Stmt::DoStmtClass: {
4156     const DoStmt *DS = cast<DoStmt>(S);
4157     bool Continue;
4158     do {
4159       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4160       if (ESR != ESR_Continue)
4161         return ESR;
4162       Case = nullptr;
4163 
4164       FullExpressionRAII CondScope(Info);
4165       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4166         return ESR_Failed;
4167     } while (Continue);
4168     return ESR_Succeeded;
4169   }
4170 
4171   case Stmt::ForStmtClass: {
4172     const ForStmt *FS = cast<ForStmt>(S);
4173     BlockScopeRAII Scope(Info);
4174     if (FS->getInit()) {
4175       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4176       if (ESR != ESR_Succeeded)
4177         return ESR;
4178     }
4179     while (true) {
4180       BlockScopeRAII Scope(Info);
4181       bool Continue = true;
4182       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4183                                          FS->getCond(), Continue))
4184         return ESR_Failed;
4185       if (!Continue)
4186         break;
4187 
4188       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4189       if (ESR != ESR_Continue)
4190         return ESR;
4191 
4192       if (FS->getInc()) {
4193         FullExpressionRAII IncScope(Info);
4194         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4195           return ESR_Failed;
4196       }
4197     }
4198     return ESR_Succeeded;
4199   }
4200 
4201   case Stmt::CXXForRangeStmtClass: {
4202     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4203     BlockScopeRAII Scope(Info);
4204 
4205     // Evaluate the init-statement if present.
4206     if (FS->getInit()) {
4207       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4208       if (ESR != ESR_Succeeded)
4209         return ESR;
4210     }
4211 
4212     // Initialize the __range variable.
4213     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4214     if (ESR != ESR_Succeeded)
4215       return ESR;
4216 
4217     // Create the __begin and __end iterators.
4218     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4219     if (ESR != ESR_Succeeded)
4220       return ESR;
4221     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4222     if (ESR != ESR_Succeeded)
4223       return ESR;
4224 
4225     while (true) {
4226       // Condition: __begin != __end.
4227       {
4228         bool Continue = true;
4229         FullExpressionRAII CondExpr(Info);
4230         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4231           return ESR_Failed;
4232         if (!Continue)
4233           break;
4234       }
4235 
4236       // User's variable declaration, initialized by *__begin.
4237       BlockScopeRAII InnerScope(Info);
4238       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4239       if (ESR != ESR_Succeeded)
4240         return ESR;
4241 
4242       // Loop body.
4243       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4244       if (ESR != ESR_Continue)
4245         return ESR;
4246 
4247       // Increment: ++__begin
4248       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4249         return ESR_Failed;
4250     }
4251 
4252     return ESR_Succeeded;
4253   }
4254 
4255   case Stmt::SwitchStmtClass:
4256     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4257 
4258   case Stmt::ContinueStmtClass:
4259     return ESR_Continue;
4260 
4261   case Stmt::BreakStmtClass:
4262     return ESR_Break;
4263 
4264   case Stmt::LabelStmtClass:
4265     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4266 
4267   case Stmt::AttributedStmtClass:
4268     // As a general principle, C++11 attributes can be ignored without
4269     // any semantic impact.
4270     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4271                         Case);
4272 
4273   case Stmt::CaseStmtClass:
4274   case Stmt::DefaultStmtClass:
4275     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4276   }
4277 }
4278 
4279 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4280 /// default constructor. If so, we'll fold it whether or not it's marked as
4281 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4282 /// so we need special handling.
4283 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4284                                            const CXXConstructorDecl *CD,
4285                                            bool IsValueInitialization) {
4286   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4287     return false;
4288 
4289   // Value-initialization does not call a trivial default constructor, so such a
4290   // call is a core constant expression whether or not the constructor is
4291   // constexpr.
4292   if (!CD->isConstexpr() && !IsValueInitialization) {
4293     if (Info.getLangOpts().CPlusPlus11) {
4294       // FIXME: If DiagDecl is an implicitly-declared special member function,
4295       // we should be much more explicit about why it's not constexpr.
4296       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4297         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4298       Info.Note(CD->getLocation(), diag::note_declared_at);
4299     } else {
4300       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4301     }
4302   }
4303   return true;
4304 }
4305 
4306 /// CheckConstexprFunction - Check that a function can be called in a constant
4307 /// expression.
4308 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4309                                    const FunctionDecl *Declaration,
4310                                    const FunctionDecl *Definition,
4311                                    const Stmt *Body) {
4312   // Potential constant expressions can contain calls to declared, but not yet
4313   // defined, constexpr functions.
4314   if (Info.checkingPotentialConstantExpression() && !Definition &&
4315       Declaration->isConstexpr())
4316     return false;
4317 
4318   // Bail out if the function declaration itself is invalid.  We will
4319   // have produced a relevant diagnostic while parsing it, so just
4320   // note the problematic sub-expression.
4321   if (Declaration->isInvalidDecl()) {
4322     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4323     return false;
4324   }
4325 
4326   // Can we evaluate this function call?
4327   if (Definition && Definition->isConstexpr() &&
4328       !Definition->isInvalidDecl() && Body)
4329     return true;
4330 
4331   if (Info.getLangOpts().CPlusPlus11) {
4332     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4333 
4334     // If this function is not constexpr because it is an inherited
4335     // non-constexpr constructor, diagnose that directly.
4336     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4337     if (CD && CD->isInheritingConstructor()) {
4338       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4339       if (!Inherited->isConstexpr())
4340         DiagDecl = CD = Inherited;
4341     }
4342 
4343     // FIXME: If DiagDecl is an implicitly-declared special member function
4344     // or an inheriting constructor, we should be much more explicit about why
4345     // it's not constexpr.
4346     if (CD && CD->isInheritingConstructor())
4347       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4348         << CD->getInheritedConstructor().getConstructor()->getParent();
4349     else
4350       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4351         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4352     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4353   } else {
4354     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4355   }
4356   return false;
4357 }
4358 
4359 /// Determine if a class has any fields that might need to be copied by a
4360 /// trivial copy or move operation.
4361 static bool hasFields(const CXXRecordDecl *RD) {
4362   if (!RD || RD->isEmpty())
4363     return false;
4364   for (auto *FD : RD->fields()) {
4365     if (FD->isUnnamedBitfield())
4366       continue;
4367     return true;
4368   }
4369   for (auto &Base : RD->bases())
4370     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4371       return true;
4372   return false;
4373 }
4374 
4375 namespace {
4376 typedef SmallVector<APValue, 8> ArgVector;
4377 }
4378 
4379 /// EvaluateArgs - Evaluate the arguments to a function call.
4380 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4381                          EvalInfo &Info) {
4382   bool Success = true;
4383   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4384        I != E; ++I) {
4385     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4386       // If we're checking for a potential constant expression, evaluate all
4387       // initializers even if some of them fail.
4388       if (!Info.noteFailure())
4389         return false;
4390       Success = false;
4391     }
4392   }
4393   return Success;
4394 }
4395 
4396 /// Evaluate a function call.
4397 static bool HandleFunctionCall(SourceLocation CallLoc,
4398                                const FunctionDecl *Callee, const LValue *This,
4399                                ArrayRef<const Expr*> Args, const Stmt *Body,
4400                                EvalInfo &Info, APValue &Result,
4401                                const LValue *ResultSlot) {
4402   ArgVector ArgValues(Args.size());
4403   if (!EvaluateArgs(Args, ArgValues, Info))
4404     return false;
4405 
4406   if (!Info.CheckCallLimit(CallLoc))
4407     return false;
4408 
4409   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4410 
4411   // For a trivial copy or move assignment, perform an APValue copy. This is
4412   // essential for unions, where the operations performed by the assignment
4413   // operator cannot be represented as statements.
4414   //
4415   // Skip this for non-union classes with no fields; in that case, the defaulted
4416   // copy/move does not actually read the object.
4417   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4418   if (MD && MD->isDefaulted() &&
4419       (MD->getParent()->isUnion() ||
4420        (MD->isTrivial() && hasFields(MD->getParent())))) {
4421     assert(This &&
4422            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4423     LValue RHS;
4424     RHS.setFrom(Info.Ctx, ArgValues[0]);
4425     APValue RHSValue;
4426     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4427                                         RHS, RHSValue))
4428       return false;
4429     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4430                           RHSValue))
4431       return false;
4432     This->moveInto(Result);
4433     return true;
4434   } else if (MD && isLambdaCallOperator(MD)) {
4435     // We're in a lambda; determine the lambda capture field maps unless we're
4436     // just constexpr checking a lambda's call operator. constexpr checking is
4437     // done before the captures have been added to the closure object (unless
4438     // we're inferring constexpr-ness), so we don't have access to them in this
4439     // case. But since we don't need the captures to constexpr check, we can
4440     // just ignore them.
4441     if (!Info.checkingPotentialConstantExpression())
4442       MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4443                                         Frame.LambdaThisCaptureField);
4444   }
4445 
4446   StmtResult Ret = {Result, ResultSlot};
4447   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4448   if (ESR == ESR_Succeeded) {
4449     if (Callee->getReturnType()->isVoidType())
4450       return true;
4451     Info.FFDiag(Callee->getEndLoc(), diag::note_constexpr_no_return);
4452   }
4453   return ESR == ESR_Returned;
4454 }
4455 
4456 /// Evaluate a constructor call.
4457 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4458                                   APValue *ArgValues,
4459                                   const CXXConstructorDecl *Definition,
4460                                   EvalInfo &Info, APValue &Result) {
4461   SourceLocation CallLoc = E->getExprLoc();
4462   if (!Info.CheckCallLimit(CallLoc))
4463     return false;
4464 
4465   const CXXRecordDecl *RD = Definition->getParent();
4466   if (RD->getNumVBases()) {
4467     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4468     return false;
4469   }
4470 
4471   EvalInfo::EvaluatingConstructorRAII EvalObj(
4472       Info, {This.getLValueBase(),
4473              {This.getLValueCallIndex(), This.getLValueVersion()}});
4474   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4475 
4476   // FIXME: Creating an APValue just to hold a nonexistent return value is
4477   // wasteful.
4478   APValue RetVal;
4479   StmtResult Ret = {RetVal, nullptr};
4480 
4481   // If it's a delegating constructor, delegate.
4482   if (Definition->isDelegatingConstructor()) {
4483     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4484     {
4485       FullExpressionRAII InitScope(Info);
4486       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4487         return false;
4488     }
4489     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4490   }
4491 
4492   // For a trivial copy or move constructor, perform an APValue copy. This is
4493   // essential for unions (or classes with anonymous union members), where the
4494   // operations performed by the constructor cannot be represented by
4495   // ctor-initializers.
4496   //
4497   // Skip this for empty non-union classes; we should not perform an
4498   // lvalue-to-rvalue conversion on them because their copy constructor does not
4499   // actually read them.
4500   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4501       (Definition->getParent()->isUnion() ||
4502        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4503     LValue RHS;
4504     RHS.setFrom(Info.Ctx, ArgValues[0]);
4505     return handleLValueToRValueConversion(
4506         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4507         RHS, Result);
4508   }
4509 
4510   // Reserve space for the struct members.
4511   if (!RD->isUnion() && Result.isUninit())
4512     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4513                      std::distance(RD->field_begin(), RD->field_end()));
4514 
4515   if (RD->isInvalidDecl()) return false;
4516   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4517 
4518   // A scope for temporaries lifetime-extended by reference members.
4519   BlockScopeRAII LifetimeExtendedScope(Info);
4520 
4521   bool Success = true;
4522   unsigned BasesSeen = 0;
4523 #ifndef NDEBUG
4524   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4525 #endif
4526   for (const auto *I : Definition->inits()) {
4527     LValue Subobject = This;
4528     LValue SubobjectParent = This;
4529     APValue *Value = &Result;
4530 
4531     // Determine the subobject to initialize.
4532     FieldDecl *FD = nullptr;
4533     if (I->isBaseInitializer()) {
4534       QualType BaseType(I->getBaseClass(), 0);
4535 #ifndef NDEBUG
4536       // Non-virtual base classes are initialized in the order in the class
4537       // definition. We have already checked for virtual base classes.
4538       assert(!BaseIt->isVirtual() && "virtual base for literal type");
4539       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4540              "base class initializers not in expected order");
4541       ++BaseIt;
4542 #endif
4543       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4544                                   BaseType->getAsCXXRecordDecl(), &Layout))
4545         return false;
4546       Value = &Result.getStructBase(BasesSeen++);
4547     } else if ((FD = I->getMember())) {
4548       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4549         return false;
4550       if (RD->isUnion()) {
4551         Result = APValue(FD);
4552         Value = &Result.getUnionValue();
4553       } else {
4554         Value = &Result.getStructField(FD->getFieldIndex());
4555       }
4556     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4557       // Walk the indirect field decl's chain to find the object to initialize,
4558       // and make sure we've initialized every step along it.
4559       auto IndirectFieldChain = IFD->chain();
4560       for (auto *C : IndirectFieldChain) {
4561         FD = cast<FieldDecl>(C);
4562         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4563         // Switch the union field if it differs. This happens if we had
4564         // preceding zero-initialization, and we're now initializing a union
4565         // subobject other than the first.
4566         // FIXME: In this case, the values of the other subobjects are
4567         // specified, since zero-initialization sets all padding bits to zero.
4568         if (Value->isUninit() ||
4569             (Value->isUnion() && Value->getUnionField() != FD)) {
4570           if (CD->isUnion())
4571             *Value = APValue(FD);
4572           else
4573             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4574                              std::distance(CD->field_begin(), CD->field_end()));
4575         }
4576         // Store Subobject as its parent before updating it for the last element
4577         // in the chain.
4578         if (C == IndirectFieldChain.back())
4579           SubobjectParent = Subobject;
4580         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4581           return false;
4582         if (CD->isUnion())
4583           Value = &Value->getUnionValue();
4584         else
4585           Value = &Value->getStructField(FD->getFieldIndex());
4586       }
4587     } else {
4588       llvm_unreachable("unknown base initializer kind");
4589     }
4590 
4591     // Need to override This for implicit field initializers as in this case
4592     // This refers to innermost anonymous struct/union containing initializer,
4593     // not to currently constructed class.
4594     const Expr *Init = I->getInit();
4595     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4596                                   isa<CXXDefaultInitExpr>(Init));
4597     FullExpressionRAII InitScope(Info);
4598     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4599         (FD && FD->isBitField() &&
4600          !truncateBitfieldValue(Info, Init, *Value, FD))) {
4601       // If we're checking for a potential constant expression, evaluate all
4602       // initializers even if some of them fail.
4603       if (!Info.noteFailure())
4604         return false;
4605       Success = false;
4606     }
4607   }
4608 
4609   return Success &&
4610          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4611 }
4612 
4613 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4614                                   ArrayRef<const Expr*> Args,
4615                                   const CXXConstructorDecl *Definition,
4616                                   EvalInfo &Info, APValue &Result) {
4617   ArgVector ArgValues(Args.size());
4618   if (!EvaluateArgs(Args, ArgValues, Info))
4619     return false;
4620 
4621   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4622                                Info, Result);
4623 }
4624 
4625 //===----------------------------------------------------------------------===//
4626 // Generic Evaluation
4627 //===----------------------------------------------------------------------===//
4628 namespace {
4629 
4630 template <class Derived>
4631 class ExprEvaluatorBase
4632   : public ConstStmtVisitor<Derived, bool> {
4633 private:
4634   Derived &getDerived() { return static_cast<Derived&>(*this); }
4635   bool DerivedSuccess(const APValue &V, const Expr *E) {
4636     return getDerived().Success(V, E);
4637   }
4638   bool DerivedZeroInitialization(const Expr *E) {
4639     return getDerived().ZeroInitialization(E);
4640   }
4641 
4642   // Check whether a conditional operator with a non-constant condition is a
4643   // potential constant expression. If neither arm is a potential constant
4644   // expression, then the conditional operator is not either.
4645   template<typename ConditionalOperator>
4646   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4647     assert(Info.checkingPotentialConstantExpression());
4648 
4649     // Speculatively evaluate both arms.
4650     SmallVector<PartialDiagnosticAt, 8> Diag;
4651     {
4652       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4653       StmtVisitorTy::Visit(E->getFalseExpr());
4654       if (Diag.empty())
4655         return;
4656     }
4657 
4658     {
4659       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4660       Diag.clear();
4661       StmtVisitorTy::Visit(E->getTrueExpr());
4662       if (Diag.empty())
4663         return;
4664     }
4665 
4666     Error(E, diag::note_constexpr_conditional_never_const);
4667   }
4668 
4669 
4670   template<typename ConditionalOperator>
4671   bool HandleConditionalOperator(const ConditionalOperator *E) {
4672     bool BoolResult;
4673     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4674       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4675         CheckPotentialConstantConditional(E);
4676         return false;
4677       }
4678       if (Info.noteFailure()) {
4679         StmtVisitorTy::Visit(E->getTrueExpr());
4680         StmtVisitorTy::Visit(E->getFalseExpr());
4681       }
4682       return false;
4683     }
4684 
4685     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4686     return StmtVisitorTy::Visit(EvalExpr);
4687   }
4688 
4689 protected:
4690   EvalInfo &Info;
4691   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4692   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4693 
4694   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4695     return Info.CCEDiag(E, D);
4696   }
4697 
4698   bool ZeroInitialization(const Expr *E) { return Error(E); }
4699 
4700 public:
4701   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4702 
4703   EvalInfo &getEvalInfo() { return Info; }
4704 
4705   /// Report an evaluation error. This should only be called when an error is
4706   /// first discovered. When propagating an error, just return false.
4707   bool Error(const Expr *E, diag::kind D) {
4708     Info.FFDiag(E, D);
4709     return false;
4710   }
4711   bool Error(const Expr *E) {
4712     return Error(E, diag::note_invalid_subexpr_in_const_expr);
4713   }
4714 
4715   bool VisitStmt(const Stmt *) {
4716     llvm_unreachable("Expression evaluator should not be called on stmts");
4717   }
4718   bool VisitExpr(const Expr *E) {
4719     return Error(E);
4720   }
4721 
4722   bool VisitConstantExpr(const ConstantExpr *E)
4723     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4724   bool VisitParenExpr(const ParenExpr *E)
4725     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4726   bool VisitUnaryExtension(const UnaryOperator *E)
4727     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4728   bool VisitUnaryPlus(const UnaryOperator *E)
4729     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4730   bool VisitChooseExpr(const ChooseExpr *E)
4731     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4732   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4733     { return StmtVisitorTy::Visit(E->getResultExpr()); }
4734   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4735     { return StmtVisitorTy::Visit(E->getReplacement()); }
4736   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4737     TempVersionRAII RAII(*Info.CurrentCall);
4738     return StmtVisitorTy::Visit(E->getExpr());
4739   }
4740   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4741     TempVersionRAII RAII(*Info.CurrentCall);
4742     // The initializer may not have been parsed yet, or might be erroneous.
4743     if (!E->getExpr())
4744       return Error(E);
4745     return StmtVisitorTy::Visit(E->getExpr());
4746   }
4747   // We cannot create any objects for which cleanups are required, so there is
4748   // nothing to do here; all cleanups must come from unevaluated subexpressions.
4749   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4750     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4751 
4752   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4753     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4754     return static_cast<Derived*>(this)->VisitCastExpr(E);
4755   }
4756   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4757     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4758     return static_cast<Derived*>(this)->VisitCastExpr(E);
4759   }
4760 
4761   bool VisitBinaryOperator(const BinaryOperator *E) {
4762     switch (E->getOpcode()) {
4763     default:
4764       return Error(E);
4765 
4766     case BO_Comma:
4767       VisitIgnoredValue(E->getLHS());
4768       return StmtVisitorTy::Visit(E->getRHS());
4769 
4770     case BO_PtrMemD:
4771     case BO_PtrMemI: {
4772       LValue Obj;
4773       if (!HandleMemberPointerAccess(Info, E, Obj))
4774         return false;
4775       APValue Result;
4776       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4777         return false;
4778       return DerivedSuccess(Result, E);
4779     }
4780     }
4781   }
4782 
4783   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4784     // Evaluate and cache the common expression. We treat it as a temporary,
4785     // even though it's not quite the same thing.
4786     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4787                   Info, E->getCommon()))
4788       return false;
4789 
4790     return HandleConditionalOperator(E);
4791   }
4792 
4793   bool VisitConditionalOperator(const ConditionalOperator *E) {
4794     bool IsBcpCall = false;
4795     // If the condition (ignoring parens) is a __builtin_constant_p call,
4796     // the result is a constant expression if it can be folded without
4797     // side-effects. This is an important GNU extension. See GCC PR38377
4798     // for discussion.
4799     if (const CallExpr *CallCE =
4800           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4801       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4802         IsBcpCall = true;
4803 
4804     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4805     // constant expression; we can't check whether it's potentially foldable.
4806     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4807       return false;
4808 
4809     FoldConstant Fold(Info, IsBcpCall);
4810     if (!HandleConditionalOperator(E)) {
4811       Fold.keepDiagnostics();
4812       return false;
4813     }
4814 
4815     return true;
4816   }
4817 
4818   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4819     if (APValue *Value = Info.CurrentCall->getCurrentTemporary(E))
4820       return DerivedSuccess(*Value, E);
4821 
4822     const Expr *Source = E->getSourceExpr();
4823     if (!Source)
4824       return Error(E);
4825     if (Source == E) { // sanity checking.
4826       assert(0 && "OpaqueValueExpr recursively refers to itself");
4827       return Error(E);
4828     }
4829     return StmtVisitorTy::Visit(Source);
4830   }
4831 
4832   bool VisitCallExpr(const CallExpr *E) {
4833     APValue Result;
4834     if (!handleCallExpr(E, Result, nullptr))
4835       return false;
4836     return DerivedSuccess(Result, E);
4837   }
4838 
4839   bool handleCallExpr(const CallExpr *E, APValue &Result,
4840                      const LValue *ResultSlot) {
4841     const Expr *Callee = E->getCallee()->IgnoreParens();
4842     QualType CalleeType = Callee->getType();
4843 
4844     const FunctionDecl *FD = nullptr;
4845     LValue *This = nullptr, ThisVal;
4846     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4847     bool HasQualifier = false;
4848 
4849     // Extract function decl and 'this' pointer from the callee.
4850     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4851       const ValueDecl *Member = nullptr;
4852       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4853         // Explicit bound member calls, such as x.f() or p->g();
4854         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4855           return false;
4856         Member = ME->getMemberDecl();
4857         This = &ThisVal;
4858         HasQualifier = ME->hasQualifier();
4859       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4860         // Indirect bound member calls ('.*' or '->*').
4861         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4862         if (!Member) return false;
4863         This = &ThisVal;
4864       } else
4865         return Error(Callee);
4866 
4867       FD = dyn_cast<FunctionDecl>(Member);
4868       if (!FD)
4869         return Error(Callee);
4870     } else if (CalleeType->isFunctionPointerType()) {
4871       LValue Call;
4872       if (!EvaluatePointer(Callee, Call, Info))
4873         return false;
4874 
4875       if (!Call.getLValueOffset().isZero())
4876         return Error(Callee);
4877       FD = dyn_cast_or_null<FunctionDecl>(
4878                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4879       if (!FD)
4880         return Error(Callee);
4881       // Don't call function pointers which have been cast to some other type.
4882       // Per DR (no number yet), the caller and callee can differ in noexcept.
4883       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4884         CalleeType->getPointeeType(), FD->getType())) {
4885         return Error(E);
4886       }
4887 
4888       // Overloaded operator calls to member functions are represented as normal
4889       // calls with '*this' as the first argument.
4890       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4891       if (MD && !MD->isStatic()) {
4892         // FIXME: When selecting an implicit conversion for an overloaded
4893         // operator delete, we sometimes try to evaluate calls to conversion
4894         // operators without a 'this' parameter!
4895         if (Args.empty())
4896           return Error(E);
4897 
4898         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4899           return false;
4900         This = &ThisVal;
4901         Args = Args.slice(1);
4902       } else if (MD && MD->isLambdaStaticInvoker()) {
4903         // Map the static invoker for the lambda back to the call operator.
4904         // Conveniently, we don't have to slice out the 'this' argument (as is
4905         // being done for the non-static case), since a static member function
4906         // doesn't have an implicit argument passed in.
4907         const CXXRecordDecl *ClosureClass = MD->getParent();
4908         assert(
4909             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4910             "Number of captures must be zero for conversion to function-ptr");
4911 
4912         const CXXMethodDecl *LambdaCallOp =
4913             ClosureClass->getLambdaCallOperator();
4914 
4915         // Set 'FD', the function that will be called below, to the call
4916         // operator.  If the closure object represents a generic lambda, find
4917         // the corresponding specialization of the call operator.
4918 
4919         if (ClosureClass->isGenericLambda()) {
4920           assert(MD->isFunctionTemplateSpecialization() &&
4921                  "A generic lambda's static-invoker function must be a "
4922                  "template specialization");
4923           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4924           FunctionTemplateDecl *CallOpTemplate =
4925               LambdaCallOp->getDescribedFunctionTemplate();
4926           void *InsertPos = nullptr;
4927           FunctionDecl *CorrespondingCallOpSpecialization =
4928               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4929           assert(CorrespondingCallOpSpecialization &&
4930                  "We must always have a function call operator specialization "
4931                  "that corresponds to our static invoker specialization");
4932           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4933         } else
4934           FD = LambdaCallOp;
4935       }
4936 
4937 
4938     } else
4939       return Error(E);
4940 
4941     if (This && !This->checkSubobject(Info, E, CSK_This))
4942       return false;
4943 
4944     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4945     // calls to such functions in constant expressions.
4946     if (This && !HasQualifier &&
4947         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4948       return Error(E, diag::note_constexpr_virtual_call);
4949 
4950     const FunctionDecl *Definition = nullptr;
4951     Stmt *Body = FD->getBody(Definition);
4952 
4953     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4954         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4955                             Result, ResultSlot))
4956       return false;
4957 
4958     return true;
4959   }
4960 
4961   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4962     return StmtVisitorTy::Visit(E->getInitializer());
4963   }
4964   bool VisitInitListExpr(const InitListExpr *E) {
4965     if (E->getNumInits() == 0)
4966       return DerivedZeroInitialization(E);
4967     if (E->getNumInits() == 1)
4968       return StmtVisitorTy::Visit(E->getInit(0));
4969     return Error(E);
4970   }
4971   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4972     return DerivedZeroInitialization(E);
4973   }
4974   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4975     return DerivedZeroInitialization(E);
4976   }
4977   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4978     return DerivedZeroInitialization(E);
4979   }
4980 
4981   /// A member expression where the object is a prvalue is itself a prvalue.
4982   bool VisitMemberExpr(const MemberExpr *E) {
4983     assert(!E->isArrow() && "missing call to bound member function?");
4984 
4985     APValue Val;
4986     if (!Evaluate(Val, Info, E->getBase()))
4987       return false;
4988 
4989     QualType BaseTy = E->getBase()->getType();
4990 
4991     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4992     if (!FD) return Error(E);
4993     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4994     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4995            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4996 
4997     CompleteObject Obj(&Val, BaseTy, true);
4998     SubobjectDesignator Designator(BaseTy);
4999     Designator.addDeclUnchecked(FD);
5000 
5001     APValue Result;
5002     return extractSubobject(Info, E, Obj, Designator, Result) &&
5003            DerivedSuccess(Result, E);
5004   }
5005 
5006   bool VisitCastExpr(const CastExpr *E) {
5007     switch (E->getCastKind()) {
5008     default:
5009       break;
5010 
5011     case CK_AtomicToNonAtomic: {
5012       APValue AtomicVal;
5013       // This does not need to be done in place even for class/array types:
5014       // atomic-to-non-atomic conversion implies copying the object
5015       // representation.
5016       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
5017         return false;
5018       return DerivedSuccess(AtomicVal, E);
5019     }
5020 
5021     case CK_NoOp:
5022     case CK_UserDefinedConversion:
5023       return StmtVisitorTy::Visit(E->getSubExpr());
5024 
5025     case CK_LValueToRValue: {
5026       LValue LVal;
5027       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
5028         return false;
5029       APValue RVal;
5030       // Note, we use the subexpression's type in order to retain cv-qualifiers.
5031       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5032                                           LVal, RVal))
5033         return false;
5034       return DerivedSuccess(RVal, E);
5035     }
5036     }
5037 
5038     return Error(E);
5039   }
5040 
5041   bool VisitUnaryPostInc(const UnaryOperator *UO) {
5042     return VisitUnaryPostIncDec(UO);
5043   }
5044   bool VisitUnaryPostDec(const UnaryOperator *UO) {
5045     return VisitUnaryPostIncDec(UO);
5046   }
5047   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
5048     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5049       return Error(UO);
5050 
5051     LValue LVal;
5052     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
5053       return false;
5054     APValue RVal;
5055     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
5056                       UO->isIncrementOp(), &RVal))
5057       return false;
5058     return DerivedSuccess(RVal, UO);
5059   }
5060 
5061   bool VisitStmtExpr(const StmtExpr *E) {
5062     // We will have checked the full-expressions inside the statement expression
5063     // when they were completed, and don't need to check them again now.
5064     if (Info.checkingForOverflow())
5065       return Error(E);
5066 
5067     BlockScopeRAII Scope(Info);
5068     const CompoundStmt *CS = E->getSubStmt();
5069     if (CS->body_empty())
5070       return true;
5071 
5072     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
5073                                            BE = CS->body_end();
5074          /**/; ++BI) {
5075       if (BI + 1 == BE) {
5076         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
5077         if (!FinalExpr) {
5078           Info.FFDiag((*BI)->getBeginLoc(),
5079                       diag::note_constexpr_stmt_expr_unsupported);
5080           return false;
5081         }
5082         return this->Visit(FinalExpr);
5083       }
5084 
5085       APValue ReturnValue;
5086       StmtResult Result = { ReturnValue, nullptr };
5087       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
5088       if (ESR != ESR_Succeeded) {
5089         // FIXME: If the statement-expression terminated due to 'return',
5090         // 'break', or 'continue', it would be nice to propagate that to
5091         // the outer statement evaluation rather than bailing out.
5092         if (ESR != ESR_Failed)
5093           Info.FFDiag((*BI)->getBeginLoc(),
5094                       diag::note_constexpr_stmt_expr_unsupported);
5095         return false;
5096       }
5097     }
5098 
5099     llvm_unreachable("Return from function from the loop above.");
5100   }
5101 
5102   /// Visit a value which is evaluated, but whose value is ignored.
5103   void VisitIgnoredValue(const Expr *E) {
5104     EvaluateIgnoredValue(Info, E);
5105   }
5106 
5107   /// Potentially visit a MemberExpr's base expression.
5108   void VisitIgnoredBaseExpression(const Expr *E) {
5109     // While MSVC doesn't evaluate the base expression, it does diagnose the
5110     // presence of side-effecting behavior.
5111     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
5112       return;
5113     VisitIgnoredValue(E);
5114   }
5115 };
5116 
5117 } // namespace
5118 
5119 //===----------------------------------------------------------------------===//
5120 // Common base class for lvalue and temporary evaluation.
5121 //===----------------------------------------------------------------------===//
5122 namespace {
5123 template<class Derived>
5124 class LValueExprEvaluatorBase
5125   : public ExprEvaluatorBase<Derived> {
5126 protected:
5127   LValue &Result;
5128   bool InvalidBaseOK;
5129   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
5130   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
5131 
5132   bool Success(APValue::LValueBase B) {
5133     Result.set(B);
5134     return true;
5135   }
5136 
5137   bool evaluatePointer(const Expr *E, LValue &Result) {
5138     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
5139   }
5140 
5141 public:
5142   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
5143       : ExprEvaluatorBaseTy(Info), Result(Result),
5144         InvalidBaseOK(InvalidBaseOK) {}
5145 
5146   bool Success(const APValue &V, const Expr *E) {
5147     Result.setFrom(this->Info.Ctx, V);
5148     return true;
5149   }
5150 
5151   bool VisitMemberExpr(const MemberExpr *E) {
5152     // Handle non-static data members.
5153     QualType BaseTy;
5154     bool EvalOK;
5155     if (E->isArrow()) {
5156       EvalOK = evaluatePointer(E->getBase(), Result);
5157       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5158     } else if (E->getBase()->isRValue()) {
5159       assert(E->getBase()->getType()->isRecordType());
5160       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5161       BaseTy = E->getBase()->getType();
5162     } else {
5163       EvalOK = this->Visit(E->getBase());
5164       BaseTy = E->getBase()->getType();
5165     }
5166     if (!EvalOK) {
5167       if (!InvalidBaseOK)
5168         return false;
5169       Result.setInvalid(E);
5170       return true;
5171     }
5172 
5173     const ValueDecl *MD = E->getMemberDecl();
5174     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5175       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5176              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5177       (void)BaseTy;
5178       if (!HandleLValueMember(this->Info, E, Result, FD))
5179         return false;
5180     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5181       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5182         return false;
5183     } else
5184       return this->Error(E);
5185 
5186     if (MD->getType()->isReferenceType()) {
5187       APValue RefValue;
5188       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5189                                           RefValue))
5190         return false;
5191       return Success(RefValue, E);
5192     }
5193     return true;
5194   }
5195 
5196   bool VisitBinaryOperator(const BinaryOperator *E) {
5197     switch (E->getOpcode()) {
5198     default:
5199       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5200 
5201     case BO_PtrMemD:
5202     case BO_PtrMemI:
5203       return HandleMemberPointerAccess(this->Info, E, Result);
5204     }
5205   }
5206 
5207   bool VisitCastExpr(const CastExpr *E) {
5208     switch (E->getCastKind()) {
5209     default:
5210       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5211 
5212     case CK_DerivedToBase:
5213     case CK_UncheckedDerivedToBase:
5214       if (!this->Visit(E->getSubExpr()))
5215         return false;
5216 
5217       // Now figure out the necessary offset to add to the base LV to get from
5218       // the derived class to the base class.
5219       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5220                                   Result);
5221     }
5222   }
5223 };
5224 }
5225 
5226 //===----------------------------------------------------------------------===//
5227 // LValue Evaluation
5228 //
5229 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5230 // function designators (in C), decl references to void objects (in C), and
5231 // temporaries (if building with -Wno-address-of-temporary).
5232 //
5233 // LValue evaluation produces values comprising a base expression of one of the
5234 // following types:
5235 // - Declarations
5236 //  * VarDecl
5237 //  * FunctionDecl
5238 // - Literals
5239 //  * CompoundLiteralExpr in C (and in global scope in C++)
5240 //  * StringLiteral
5241 //  * CXXTypeidExpr
5242 //  * PredefinedExpr
5243 //  * ObjCStringLiteralExpr
5244 //  * ObjCEncodeExpr
5245 //  * AddrLabelExpr
5246 //  * BlockExpr
5247 //  * CallExpr for a MakeStringConstant builtin
5248 // - Locals and temporaries
5249 //  * MaterializeTemporaryExpr
5250 //  * Any Expr, with a CallIndex indicating the function in which the temporary
5251 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
5252 //    from the AST (FIXME).
5253 //  * A MaterializeTemporaryExpr that has static storage duration, with no
5254 //    CallIndex, for a lifetime-extended temporary.
5255 // plus an offset in bytes.
5256 //===----------------------------------------------------------------------===//
5257 namespace {
5258 class LValueExprEvaluator
5259   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5260 public:
5261   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5262     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5263 
5264   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5265   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5266 
5267   bool VisitDeclRefExpr(const DeclRefExpr *E);
5268   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5269   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5270   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5271   bool VisitMemberExpr(const MemberExpr *E);
5272   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5273   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5274   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5275   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5276   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5277   bool VisitUnaryDeref(const UnaryOperator *E);
5278   bool VisitUnaryReal(const UnaryOperator *E);
5279   bool VisitUnaryImag(const UnaryOperator *E);
5280   bool VisitUnaryPreInc(const UnaryOperator *UO) {
5281     return VisitUnaryPreIncDec(UO);
5282   }
5283   bool VisitUnaryPreDec(const UnaryOperator *UO) {
5284     return VisitUnaryPreIncDec(UO);
5285   }
5286   bool VisitBinAssign(const BinaryOperator *BO);
5287   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5288 
5289   bool VisitCastExpr(const CastExpr *E) {
5290     switch (E->getCastKind()) {
5291     default:
5292       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5293 
5294     case CK_LValueBitCast:
5295       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5296       if (!Visit(E->getSubExpr()))
5297         return false;
5298       Result.Designator.setInvalid();
5299       return true;
5300 
5301     case CK_BaseToDerived:
5302       if (!Visit(E->getSubExpr()))
5303         return false;
5304       return HandleBaseToDerivedCast(Info, E, Result);
5305     }
5306   }
5307 };
5308 } // end anonymous namespace
5309 
5310 /// Evaluate an expression as an lvalue. This can be legitimately called on
5311 /// expressions which are not glvalues, in three cases:
5312 ///  * function designators in C, and
5313 ///  * "extern void" objects
5314 ///  * @selector() expressions in Objective-C
5315 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5316                            bool InvalidBaseOK) {
5317   assert(E->isGLValue() || E->getType()->isFunctionType() ||
5318          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5319   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5320 }
5321 
5322 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5323   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5324     return Success(FD);
5325   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5326     return VisitVarDecl(E, VD);
5327   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5328     return Visit(BD->getBinding());
5329   return Error(E);
5330 }
5331 
5332 
5333 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5334 
5335   // If we are within a lambda's call operator, check whether the 'VD' referred
5336   // to within 'E' actually represents a lambda-capture that maps to a
5337   // data-member/field within the closure object, and if so, evaluate to the
5338   // field or what the field refers to.
5339   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee) &&
5340       isa<DeclRefExpr>(E) &&
5341       cast<DeclRefExpr>(E)->refersToEnclosingVariableOrCapture()) {
5342     // We don't always have a complete capture-map when checking or inferring if
5343     // the function call operator meets the requirements of a constexpr function
5344     // - but we don't need to evaluate the captures to determine constexprness
5345     // (dcl.constexpr C++17).
5346     if (Info.checkingPotentialConstantExpression())
5347       return false;
5348 
5349     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5350       // Start with 'Result' referring to the complete closure object...
5351       Result = *Info.CurrentCall->This;
5352       // ... then update it to refer to the field of the closure object
5353       // that represents the capture.
5354       if (!HandleLValueMember(Info, E, Result, FD))
5355         return false;
5356       // And if the field is of reference type, update 'Result' to refer to what
5357       // the field refers to.
5358       if (FD->getType()->isReferenceType()) {
5359         APValue RVal;
5360         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5361                                             RVal))
5362           return false;
5363         Result.setFrom(Info.Ctx, RVal);
5364       }
5365       return true;
5366     }
5367   }
5368   CallStackFrame *Frame = nullptr;
5369   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5370     // Only if a local variable was declared in the function currently being
5371     // evaluated, do we expect to be able to find its value in the current
5372     // frame. (Otherwise it was likely declared in an enclosing context and
5373     // could either have a valid evaluatable value (for e.g. a constexpr
5374     // variable) or be ill-formed (and trigger an appropriate evaluation
5375     // diagnostic)).
5376     if (Info.CurrentCall->Callee &&
5377         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5378       Frame = Info.CurrentCall;
5379     }
5380   }
5381 
5382   if (!VD->getType()->isReferenceType()) {
5383     if (Frame) {
5384       Result.set({VD, Frame->Index,
5385                   Info.CurrentCall->getCurrentTemporaryVersion(VD)});
5386       return true;
5387     }
5388     return Success(VD);
5389   }
5390 
5391   APValue *V;
5392   if (!evaluateVarDeclInit(Info, E, VD, Frame, V, nullptr))
5393     return false;
5394   if (V->isUninit()) {
5395     if (!Info.checkingPotentialConstantExpression())
5396       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5397     return false;
5398   }
5399   return Success(*V, E);
5400 }
5401 
5402 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5403     const MaterializeTemporaryExpr *E) {
5404   // Walk through the expression to find the materialized temporary itself.
5405   SmallVector<const Expr *, 2> CommaLHSs;
5406   SmallVector<SubobjectAdjustment, 2> Adjustments;
5407   const Expr *Inner = E->GetTemporaryExpr()->
5408       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5409 
5410   // If we passed any comma operators, evaluate their LHSs.
5411   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5412     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5413       return false;
5414 
5415   // A materialized temporary with static storage duration can appear within the
5416   // result of a constant expression evaluation, so we need to preserve its
5417   // value for use outside this evaluation.
5418   APValue *Value;
5419   if (E->getStorageDuration() == SD_Static) {
5420     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5421     *Value = APValue();
5422     Result.set(E);
5423   } else {
5424     Value = &createTemporary(E, E->getStorageDuration() == SD_Automatic, Result,
5425                              *Info.CurrentCall);
5426   }
5427 
5428   QualType Type = Inner->getType();
5429 
5430   // Materialize the temporary itself.
5431   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5432       (E->getStorageDuration() == SD_Static &&
5433        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5434     *Value = APValue();
5435     return false;
5436   }
5437 
5438   // Adjust our lvalue to refer to the desired subobject.
5439   for (unsigned I = Adjustments.size(); I != 0; /**/) {
5440     --I;
5441     switch (Adjustments[I].Kind) {
5442     case SubobjectAdjustment::DerivedToBaseAdjustment:
5443       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5444                                 Type, Result))
5445         return false;
5446       Type = Adjustments[I].DerivedToBase.BasePath->getType();
5447       break;
5448 
5449     case SubobjectAdjustment::FieldAdjustment:
5450       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5451         return false;
5452       Type = Adjustments[I].Field->getType();
5453       break;
5454 
5455     case SubobjectAdjustment::MemberPointerAdjustment:
5456       if (!HandleMemberPointerAccess(this->Info, Type, Result,
5457                                      Adjustments[I].Ptr.RHS))
5458         return false;
5459       Type = Adjustments[I].Ptr.MPT->getPointeeType();
5460       break;
5461     }
5462   }
5463 
5464   return true;
5465 }
5466 
5467 bool
5468 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5469   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5470          "lvalue compound literal in c++?");
5471   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5472   // only see this when folding in C, so there's no standard to follow here.
5473   return Success(E);
5474 }
5475 
5476 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5477   if (!E->isPotentiallyEvaluated())
5478     return Success(E);
5479 
5480   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5481     << E->getExprOperand()->getType()
5482     << E->getExprOperand()->getSourceRange();
5483   return false;
5484 }
5485 
5486 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5487   return Success(E);
5488 }
5489 
5490 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5491   // Handle static data members.
5492   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5493     VisitIgnoredBaseExpression(E->getBase());
5494     return VisitVarDecl(E, VD);
5495   }
5496 
5497   // Handle static member functions.
5498   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5499     if (MD->isStatic()) {
5500       VisitIgnoredBaseExpression(E->getBase());
5501       return Success(MD);
5502     }
5503   }
5504 
5505   // Handle non-static data members.
5506   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5507 }
5508 
5509 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5510   // FIXME: Deal with vectors as array subscript bases.
5511   if (E->getBase()->getType()->isVectorType())
5512     return Error(E);
5513 
5514   bool Success = true;
5515   if (!evaluatePointer(E->getBase(), Result)) {
5516     if (!Info.noteFailure())
5517       return false;
5518     Success = false;
5519   }
5520 
5521   APSInt Index;
5522   if (!EvaluateInteger(E->getIdx(), Index, Info))
5523     return false;
5524 
5525   return Success &&
5526          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5527 }
5528 
5529 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5530   return evaluatePointer(E->getSubExpr(), Result);
5531 }
5532 
5533 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5534   if (!Visit(E->getSubExpr()))
5535     return false;
5536   // __real is a no-op on scalar lvalues.
5537   if (E->getSubExpr()->getType()->isAnyComplexType())
5538     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5539   return true;
5540 }
5541 
5542 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5543   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5544          "lvalue __imag__ on scalar?");
5545   if (!Visit(E->getSubExpr()))
5546     return false;
5547   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5548   return true;
5549 }
5550 
5551 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5552   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5553     return Error(UO);
5554 
5555   if (!this->Visit(UO->getSubExpr()))
5556     return false;
5557 
5558   return handleIncDec(
5559       this->Info, UO, Result, UO->getSubExpr()->getType(),
5560       UO->isIncrementOp(), nullptr);
5561 }
5562 
5563 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5564     const CompoundAssignOperator *CAO) {
5565   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5566     return Error(CAO);
5567 
5568   APValue RHS;
5569 
5570   // The overall lvalue result is the result of evaluating the LHS.
5571   if (!this->Visit(CAO->getLHS())) {
5572     if (Info.noteFailure())
5573       Evaluate(RHS, this->Info, CAO->getRHS());
5574     return false;
5575   }
5576 
5577   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5578     return false;
5579 
5580   return handleCompoundAssignment(
5581       this->Info, CAO,
5582       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5583       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5584 }
5585 
5586 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5587   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5588     return Error(E);
5589 
5590   APValue NewVal;
5591 
5592   if (!this->Visit(E->getLHS())) {
5593     if (Info.noteFailure())
5594       Evaluate(NewVal, this->Info, E->getRHS());
5595     return false;
5596   }
5597 
5598   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5599     return false;
5600 
5601   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5602                           NewVal);
5603 }
5604 
5605 //===----------------------------------------------------------------------===//
5606 // Pointer Evaluation
5607 //===----------------------------------------------------------------------===//
5608 
5609 /// Attempts to compute the number of bytes available at the pointer
5610 /// returned by a function with the alloc_size attribute. Returns true if we
5611 /// were successful. Places an unsigned number into `Result`.
5612 ///
5613 /// This expects the given CallExpr to be a call to a function with an
5614 /// alloc_size attribute.
5615 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5616                                             const CallExpr *Call,
5617                                             llvm::APInt &Result) {
5618   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5619 
5620   assert(AllocSize && AllocSize->getElemSizeParam().isValid());
5621   unsigned SizeArgNo = AllocSize->getElemSizeParam().getASTIndex();
5622   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5623   if (Call->getNumArgs() <= SizeArgNo)
5624     return false;
5625 
5626   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5627     if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5628       return false;
5629     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5630       return false;
5631     Into = Into.zextOrSelf(BitsInSizeT);
5632     return true;
5633   };
5634 
5635   APSInt SizeOfElem;
5636   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5637     return false;
5638 
5639   if (!AllocSize->getNumElemsParam().isValid()) {
5640     Result = std::move(SizeOfElem);
5641     return true;
5642   }
5643 
5644   APSInt NumberOfElems;
5645   unsigned NumArgNo = AllocSize->getNumElemsParam().getASTIndex();
5646   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5647     return false;
5648 
5649   bool Overflow;
5650   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5651   if (Overflow)
5652     return false;
5653 
5654   Result = std::move(BytesAvailable);
5655   return true;
5656 }
5657 
5658 /// Convenience function. LVal's base must be a call to an alloc_size
5659 /// function.
5660 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5661                                             const LValue &LVal,
5662                                             llvm::APInt &Result) {
5663   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5664          "Can't get the size of a non alloc_size function");
5665   const auto *Base = LVal.getLValueBase().get<const Expr *>();
5666   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5667   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5668 }
5669 
5670 /// Attempts to evaluate the given LValueBase as the result of a call to
5671 /// a function with the alloc_size attribute. If it was possible to do so, this
5672 /// function will return true, make Result's Base point to said function call,
5673 /// and mark Result's Base as invalid.
5674 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5675                                       LValue &Result) {
5676   if (Base.isNull())
5677     return false;
5678 
5679   // Because we do no form of static analysis, we only support const variables.
5680   //
5681   // Additionally, we can't support parameters, nor can we support static
5682   // variables (in the latter case, use-before-assign isn't UB; in the former,
5683   // we have no clue what they'll be assigned to).
5684   const auto *VD =
5685       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5686   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5687     return false;
5688 
5689   const Expr *Init = VD->getAnyInitializer();
5690   if (!Init)
5691     return false;
5692 
5693   const Expr *E = Init->IgnoreParens();
5694   if (!tryUnwrapAllocSizeCall(E))
5695     return false;
5696 
5697   // Store E instead of E unwrapped so that the type of the LValue's base is
5698   // what the user wanted.
5699   Result.setInvalid(E);
5700 
5701   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5702   Result.addUnsizedArray(Info, E, Pointee);
5703   return true;
5704 }
5705 
5706 namespace {
5707 class PointerExprEvaluator
5708   : public ExprEvaluatorBase<PointerExprEvaluator> {
5709   LValue &Result;
5710   bool InvalidBaseOK;
5711 
5712   bool Success(const Expr *E) {
5713     Result.set(E);
5714     return true;
5715   }
5716 
5717   bool evaluateLValue(const Expr *E, LValue &Result) {
5718     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5719   }
5720 
5721   bool evaluatePointer(const Expr *E, LValue &Result) {
5722     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5723   }
5724 
5725   bool visitNonBuiltinCallExpr(const CallExpr *E);
5726 public:
5727 
5728   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5729       : ExprEvaluatorBaseTy(info), Result(Result),
5730         InvalidBaseOK(InvalidBaseOK) {}
5731 
5732   bool Success(const APValue &V, const Expr *E) {
5733     Result.setFrom(Info.Ctx, V);
5734     return true;
5735   }
5736   bool ZeroInitialization(const Expr *E) {
5737     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5738     Result.setNull(E->getType(), TargetVal);
5739     return true;
5740   }
5741 
5742   bool VisitBinaryOperator(const BinaryOperator *E);
5743   bool VisitCastExpr(const CastExpr* E);
5744   bool VisitUnaryAddrOf(const UnaryOperator *E);
5745   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5746       { return Success(E); }
5747   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5748     if (Info.noteFailure())
5749       EvaluateIgnoredValue(Info, E->getSubExpr());
5750     return Error(E);
5751   }
5752   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5753       { return Success(E); }
5754   bool VisitCallExpr(const CallExpr *E);
5755   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5756   bool VisitBlockExpr(const BlockExpr *E) {
5757     if (!E->getBlockDecl()->hasCaptures())
5758       return Success(E);
5759     return Error(E);
5760   }
5761   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5762     // Can't look at 'this' when checking a potential constant expression.
5763     if (Info.checkingPotentialConstantExpression())
5764       return false;
5765     if (!Info.CurrentCall->This) {
5766       if (Info.getLangOpts().CPlusPlus11)
5767         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5768       else
5769         Info.FFDiag(E);
5770       return false;
5771     }
5772     Result = *Info.CurrentCall->This;
5773     // If we are inside a lambda's call operator, the 'this' expression refers
5774     // to the enclosing '*this' object (either by value or reference) which is
5775     // either copied into the closure object's field that represents the '*this'
5776     // or refers to '*this'.
5777     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5778       // Update 'Result' to refer to the data member/field of the closure object
5779       // that represents the '*this' capture.
5780       if (!HandleLValueMember(Info, E, Result,
5781                              Info.CurrentCall->LambdaThisCaptureField))
5782         return false;
5783       // If we captured '*this' by reference, replace the field with its referent.
5784       if (Info.CurrentCall->LambdaThisCaptureField->getType()
5785               ->isPointerType()) {
5786         APValue RVal;
5787         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5788                                             RVal))
5789           return false;
5790 
5791         Result.setFrom(Info.Ctx, RVal);
5792       }
5793     }
5794     return true;
5795   }
5796 
5797   // FIXME: Missing: @protocol, @selector
5798 };
5799 } // end anonymous namespace
5800 
5801 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5802                             bool InvalidBaseOK) {
5803   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5804   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5805 }
5806 
5807 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5808   if (E->getOpcode() != BO_Add &&
5809       E->getOpcode() != BO_Sub)
5810     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5811 
5812   const Expr *PExp = E->getLHS();
5813   const Expr *IExp = E->getRHS();
5814   if (IExp->getType()->isPointerType())
5815     std::swap(PExp, IExp);
5816 
5817   bool EvalPtrOK = evaluatePointer(PExp, Result);
5818   if (!EvalPtrOK && !Info.noteFailure())
5819     return false;
5820 
5821   llvm::APSInt Offset;
5822   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5823     return false;
5824 
5825   if (E->getOpcode() == BO_Sub)
5826     negateAsSigned(Offset);
5827 
5828   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5829   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5830 }
5831 
5832 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5833   return evaluateLValue(E->getSubExpr(), Result);
5834 }
5835 
5836 bool PointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5837   const Expr *SubExpr = E->getSubExpr();
5838 
5839   switch (E->getCastKind()) {
5840   default:
5841     break;
5842 
5843   case CK_BitCast:
5844   case CK_CPointerToObjCPointerCast:
5845   case CK_BlockPointerToObjCPointerCast:
5846   case CK_AnyPointerToBlockPointerCast:
5847   case CK_AddressSpaceConversion:
5848     if (!Visit(SubExpr))
5849       return false;
5850     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5851     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5852     // also static_casts, but we disallow them as a resolution to DR1312.
5853     if (!E->getType()->isVoidPointerType()) {
5854       Result.Designator.setInvalid();
5855       if (SubExpr->getType()->isVoidPointerType())
5856         CCEDiag(E, diag::note_constexpr_invalid_cast)
5857           << 3 << SubExpr->getType();
5858       else
5859         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5860     }
5861     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5862       ZeroInitialization(E);
5863     return true;
5864 
5865   case CK_DerivedToBase:
5866   case CK_UncheckedDerivedToBase:
5867     if (!evaluatePointer(E->getSubExpr(), Result))
5868       return false;
5869     if (!Result.Base && Result.Offset.isZero())
5870       return true;
5871 
5872     // Now figure out the necessary offset to add to the base LV to get from
5873     // the derived class to the base class.
5874     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5875                                   castAs<PointerType>()->getPointeeType(),
5876                                 Result);
5877 
5878   case CK_BaseToDerived:
5879     if (!Visit(E->getSubExpr()))
5880       return false;
5881     if (!Result.Base && Result.Offset.isZero())
5882       return true;
5883     return HandleBaseToDerivedCast(Info, E, Result);
5884 
5885   case CK_NullToPointer:
5886     VisitIgnoredValue(E->getSubExpr());
5887     return ZeroInitialization(E);
5888 
5889   case CK_IntegralToPointer: {
5890     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5891 
5892     APValue Value;
5893     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5894       break;
5895 
5896     if (Value.isInt()) {
5897       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5898       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5899       Result.Base = (Expr*)nullptr;
5900       Result.InvalidBase = false;
5901       Result.Offset = CharUnits::fromQuantity(N);
5902       Result.Designator.setInvalid();
5903       Result.IsNullPtr = false;
5904       return true;
5905     } else {
5906       // Cast is of an lvalue, no need to change value.
5907       Result.setFrom(Info.Ctx, Value);
5908       return true;
5909     }
5910   }
5911 
5912   case CK_ArrayToPointerDecay: {
5913     if (SubExpr->isGLValue()) {
5914       if (!evaluateLValue(SubExpr, Result))
5915         return false;
5916     } else {
5917       APValue &Value = createTemporary(SubExpr, false, Result,
5918                                        *Info.CurrentCall);
5919       if (!EvaluateInPlace(Value, Info, Result, SubExpr))
5920         return false;
5921     }
5922     // The result is a pointer to the first element of the array.
5923     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5924     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5925       Result.addArray(Info, E, CAT);
5926     else
5927       Result.addUnsizedArray(Info, E, AT->getElementType());
5928     return true;
5929   }
5930 
5931   case CK_FunctionToPointerDecay:
5932     return evaluateLValue(SubExpr, Result);
5933 
5934   case CK_LValueToRValue: {
5935     LValue LVal;
5936     if (!evaluateLValue(E->getSubExpr(), LVal))
5937       return false;
5938 
5939     APValue RVal;
5940     // Note, we use the subexpression's type in order to retain cv-qualifiers.
5941     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5942                                         LVal, RVal))
5943       return InvalidBaseOK &&
5944              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5945     return Success(RVal, E);
5946   }
5947   }
5948 
5949   return ExprEvaluatorBaseTy::VisitCastExpr(E);
5950 }
5951 
5952 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T,
5953                                 UnaryExprOrTypeTrait ExprKind) {
5954   // C++ [expr.alignof]p3:
5955   //     When alignof is applied to a reference type, the result is the
5956   //     alignment of the referenced type.
5957   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5958     T = Ref->getPointeeType();
5959 
5960   if (T.getQualifiers().hasUnaligned())
5961     return CharUnits::One();
5962 
5963   const bool AlignOfReturnsPreferred =
5964       Info.Ctx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
5965 
5966   // __alignof is defined to return the preferred alignment.
5967   // Before 8, clang returned the preferred alignment for alignof and _Alignof
5968   // as well.
5969   if (ExprKind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
5970     return Info.Ctx.toCharUnitsFromBits(
5971       Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5972   // alignof and _Alignof are defined to return the ABI alignment.
5973   else if (ExprKind == UETT_AlignOf)
5974     return Info.Ctx.getTypeAlignInChars(T.getTypePtr());
5975   else
5976     llvm_unreachable("GetAlignOfType on a non-alignment ExprKind");
5977 }
5978 
5979 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E,
5980                                 UnaryExprOrTypeTrait ExprKind) {
5981   E = E->IgnoreParens();
5982 
5983   // The kinds of expressions that we have special-case logic here for
5984   // should be kept up to date with the special checks for those
5985   // expressions in Sema.
5986 
5987   // alignof decl is always accepted, even if it doesn't make sense: we default
5988   // to 1 in those cases.
5989   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5990     return Info.Ctx.getDeclAlign(DRE->getDecl(),
5991                                  /*RefAsPointee*/true);
5992 
5993   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5994     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5995                                  /*RefAsPointee*/true);
5996 
5997   return GetAlignOfType(Info, E->getType(), ExprKind);
5998 }
5999 
6000 // To be clear: this happily visits unsupported builtins. Better name welcomed.
6001 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
6002   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
6003     return true;
6004 
6005   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
6006     return false;
6007 
6008   Result.setInvalid(E);
6009   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
6010   Result.addUnsizedArray(Info, E, PointeeTy);
6011   return true;
6012 }
6013 
6014 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
6015   if (IsStringLiteralCall(E))
6016     return Success(E);
6017 
6018   if (unsigned BuiltinOp = E->getBuiltinCallee())
6019     return VisitBuiltinCallExpr(E, BuiltinOp);
6020 
6021   return visitNonBuiltinCallExpr(E);
6022 }
6023 
6024 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
6025                                                 unsigned BuiltinOp) {
6026   switch (BuiltinOp) {
6027   case Builtin::BI__builtin_addressof:
6028     return evaluateLValue(E->getArg(0), Result);
6029   case Builtin::BI__builtin_assume_aligned: {
6030     // We need to be very careful here because: if the pointer does not have the
6031     // asserted alignment, then the behavior is undefined, and undefined
6032     // behavior is non-constant.
6033     if (!evaluatePointer(E->getArg(0), Result))
6034       return false;
6035 
6036     LValue OffsetResult(Result);
6037     APSInt Alignment;
6038     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
6039       return false;
6040     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
6041 
6042     if (E->getNumArgs() > 2) {
6043       APSInt Offset;
6044       if (!EvaluateInteger(E->getArg(2), Offset, Info))
6045         return false;
6046 
6047       int64_t AdditionalOffset = -Offset.getZExtValue();
6048       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
6049     }
6050 
6051     // If there is a base object, then it must have the correct alignment.
6052     if (OffsetResult.Base) {
6053       CharUnits BaseAlignment;
6054       if (const ValueDecl *VD =
6055           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
6056         BaseAlignment = Info.Ctx.getDeclAlign(VD);
6057       } else {
6058         BaseAlignment = GetAlignOfExpr(
6059             Info, OffsetResult.Base.get<const Expr *>(), UETT_AlignOf);
6060       }
6061 
6062       if (BaseAlignment < Align) {
6063         Result.Designator.setInvalid();
6064         // FIXME: Add support to Diagnostic for long / long long.
6065         CCEDiag(E->getArg(0),
6066                 diag::note_constexpr_baa_insufficient_alignment) << 0
6067           << (unsigned)BaseAlignment.getQuantity()
6068           << (unsigned)Align.getQuantity();
6069         return false;
6070       }
6071     }
6072 
6073     // The offset must also have the correct alignment.
6074     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
6075       Result.Designator.setInvalid();
6076 
6077       (OffsetResult.Base
6078            ? CCEDiag(E->getArg(0),
6079                      diag::note_constexpr_baa_insufficient_alignment) << 1
6080            : CCEDiag(E->getArg(0),
6081                      diag::note_constexpr_baa_value_insufficient_alignment))
6082         << (int)OffsetResult.Offset.getQuantity()
6083         << (unsigned)Align.getQuantity();
6084       return false;
6085     }
6086 
6087     return true;
6088   }
6089 
6090   case Builtin::BIstrchr:
6091   case Builtin::BIwcschr:
6092   case Builtin::BImemchr:
6093   case Builtin::BIwmemchr:
6094     if (Info.getLangOpts().CPlusPlus11)
6095       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6096         << /*isConstexpr*/0 << /*isConstructor*/0
6097         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6098     else
6099       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6100     LLVM_FALLTHROUGH;
6101   case Builtin::BI__builtin_strchr:
6102   case Builtin::BI__builtin_wcschr:
6103   case Builtin::BI__builtin_memchr:
6104   case Builtin::BI__builtin_char_memchr:
6105   case Builtin::BI__builtin_wmemchr: {
6106     if (!Visit(E->getArg(0)))
6107       return false;
6108     APSInt Desired;
6109     if (!EvaluateInteger(E->getArg(1), Desired, Info))
6110       return false;
6111     uint64_t MaxLength = uint64_t(-1);
6112     if (BuiltinOp != Builtin::BIstrchr &&
6113         BuiltinOp != Builtin::BIwcschr &&
6114         BuiltinOp != Builtin::BI__builtin_strchr &&
6115         BuiltinOp != Builtin::BI__builtin_wcschr) {
6116       APSInt N;
6117       if (!EvaluateInteger(E->getArg(2), N, Info))
6118         return false;
6119       MaxLength = N.getExtValue();
6120     }
6121 
6122     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6123 
6124     // Figure out what value we're actually looking for (after converting to
6125     // the corresponding unsigned type if necessary).
6126     uint64_t DesiredVal;
6127     bool StopAtNull = false;
6128     switch (BuiltinOp) {
6129     case Builtin::BIstrchr:
6130     case Builtin::BI__builtin_strchr:
6131       // strchr compares directly to the passed integer, and therefore
6132       // always fails if given an int that is not a char.
6133       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
6134                                                   E->getArg(1)->getType(),
6135                                                   Desired),
6136                                Desired))
6137         return ZeroInitialization(E);
6138       StopAtNull = true;
6139       LLVM_FALLTHROUGH;
6140     case Builtin::BImemchr:
6141     case Builtin::BI__builtin_memchr:
6142     case Builtin::BI__builtin_char_memchr:
6143       // memchr compares by converting both sides to unsigned char. That's also
6144       // correct for strchr if we get this far (to cope with plain char being
6145       // unsigned in the strchr case).
6146       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
6147       break;
6148 
6149     case Builtin::BIwcschr:
6150     case Builtin::BI__builtin_wcschr:
6151       StopAtNull = true;
6152       LLVM_FALLTHROUGH;
6153     case Builtin::BIwmemchr:
6154     case Builtin::BI__builtin_wmemchr:
6155       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
6156       DesiredVal = Desired.getZExtValue();
6157       break;
6158     }
6159 
6160     for (; MaxLength; --MaxLength) {
6161       APValue Char;
6162       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
6163           !Char.isInt())
6164         return false;
6165       if (Char.getInt().getZExtValue() == DesiredVal)
6166         return true;
6167       if (StopAtNull && !Char.getInt())
6168         break;
6169       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6170         return false;
6171     }
6172     // Not found: return nullptr.
6173     return ZeroInitialization(E);
6174   }
6175 
6176   case Builtin::BImemcpy:
6177   case Builtin::BImemmove:
6178   case Builtin::BIwmemcpy:
6179   case Builtin::BIwmemmove:
6180     if (Info.getLangOpts().CPlusPlus11)
6181       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
6182         << /*isConstexpr*/0 << /*isConstructor*/0
6183         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
6184     else
6185       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
6186     LLVM_FALLTHROUGH;
6187   case Builtin::BI__builtin_memcpy:
6188   case Builtin::BI__builtin_memmove:
6189   case Builtin::BI__builtin_wmemcpy:
6190   case Builtin::BI__builtin_wmemmove: {
6191     bool WChar = BuiltinOp == Builtin::BIwmemcpy ||
6192                  BuiltinOp == Builtin::BIwmemmove ||
6193                  BuiltinOp == Builtin::BI__builtin_wmemcpy ||
6194                  BuiltinOp == Builtin::BI__builtin_wmemmove;
6195     bool Move = BuiltinOp == Builtin::BImemmove ||
6196                 BuiltinOp == Builtin::BIwmemmove ||
6197                 BuiltinOp == Builtin::BI__builtin_memmove ||
6198                 BuiltinOp == Builtin::BI__builtin_wmemmove;
6199 
6200     // The result of mem* is the first argument.
6201     if (!Visit(E->getArg(0)))
6202       return false;
6203     LValue Dest = Result;
6204 
6205     LValue Src;
6206     if (!EvaluatePointer(E->getArg(1), Src, Info))
6207       return false;
6208 
6209     APSInt N;
6210     if (!EvaluateInteger(E->getArg(2), N, Info))
6211       return false;
6212     assert(!N.isSigned() && "memcpy and friends take an unsigned size");
6213 
6214     // If the size is zero, we treat this as always being a valid no-op.
6215     // (Even if one of the src and dest pointers is null.)
6216     if (!N)
6217       return true;
6218 
6219     // Otherwise, if either of the operands is null, we can't proceed. Don't
6220     // try to determine the type of the copied objects, because there aren't
6221     // any.
6222     if (!Src.Base || !Dest.Base) {
6223       APValue Val;
6224       (!Src.Base ? Src : Dest).moveInto(Val);
6225       Info.FFDiag(E, diag::note_constexpr_memcpy_null)
6226           << Move << WChar << !!Src.Base
6227           << Val.getAsString(Info.Ctx, E->getArg(0)->getType());
6228       return false;
6229     }
6230     if (Src.Designator.Invalid || Dest.Designator.Invalid)
6231       return false;
6232 
6233     // We require that Src and Dest are both pointers to arrays of
6234     // trivially-copyable type. (For the wide version, the designator will be
6235     // invalid if the designated object is not a wchar_t.)
6236     QualType T = Dest.Designator.getType(Info.Ctx);
6237     QualType SrcT = Src.Designator.getType(Info.Ctx);
6238     if (!Info.Ctx.hasSameUnqualifiedType(T, SrcT)) {
6239       Info.FFDiag(E, diag::note_constexpr_memcpy_type_pun) << Move << SrcT << T;
6240       return false;
6241     }
6242     if (T->isIncompleteType()) {
6243       Info.FFDiag(E, diag::note_constexpr_memcpy_incomplete_type) << Move << T;
6244       return false;
6245     }
6246     if (!T.isTriviallyCopyableType(Info.Ctx)) {
6247       Info.FFDiag(E, diag::note_constexpr_memcpy_nontrivial) << Move << T;
6248       return false;
6249     }
6250 
6251     // Figure out how many T's we're copying.
6252     uint64_t TSize = Info.Ctx.getTypeSizeInChars(T).getQuantity();
6253     if (!WChar) {
6254       uint64_t Remainder;
6255       llvm::APInt OrigN = N;
6256       llvm::APInt::udivrem(OrigN, TSize, N, Remainder);
6257       if (Remainder) {
6258         Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6259             << Move << WChar << 0 << T << OrigN.toString(10, /*Signed*/false)
6260             << (unsigned)TSize;
6261         return false;
6262       }
6263     }
6264 
6265     // Check that the copying will remain within the arrays, just so that we
6266     // can give a more meaningful diagnostic. This implicitly also checks that
6267     // N fits into 64 bits.
6268     uint64_t RemainingSrcSize = Src.Designator.validIndexAdjustments().second;
6269     uint64_t RemainingDestSize = Dest.Designator.validIndexAdjustments().second;
6270     if (N.ugt(RemainingSrcSize) || N.ugt(RemainingDestSize)) {
6271       Info.FFDiag(E, diag::note_constexpr_memcpy_unsupported)
6272           << Move << WChar << (N.ugt(RemainingSrcSize) ? 1 : 2) << T
6273           << N.toString(10, /*Signed*/false);
6274       return false;
6275     }
6276     uint64_t NElems = N.getZExtValue();
6277     uint64_t NBytes = NElems * TSize;
6278 
6279     // Check for overlap.
6280     int Direction = 1;
6281     if (HasSameBase(Src, Dest)) {
6282       uint64_t SrcOffset = Src.getLValueOffset().getQuantity();
6283       uint64_t DestOffset = Dest.getLValueOffset().getQuantity();
6284       if (DestOffset >= SrcOffset && DestOffset - SrcOffset < NBytes) {
6285         // Dest is inside the source region.
6286         if (!Move) {
6287           Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6288           return false;
6289         }
6290         // For memmove and friends, copy backwards.
6291         if (!HandleLValueArrayAdjustment(Info, E, Src, T, NElems - 1) ||
6292             !HandleLValueArrayAdjustment(Info, E, Dest, T, NElems - 1))
6293           return false;
6294         Direction = -1;
6295       } else if (!Move && SrcOffset >= DestOffset &&
6296                  SrcOffset - DestOffset < NBytes) {
6297         // Src is inside the destination region for memcpy: invalid.
6298         Info.FFDiag(E, diag::note_constexpr_memcpy_overlap) << WChar;
6299         return false;
6300       }
6301     }
6302 
6303     while (true) {
6304       APValue Val;
6305       if (!handleLValueToRValueConversion(Info, E, T, Src, Val) ||
6306           !handleAssignment(Info, E, Dest, T, Val))
6307         return false;
6308       // Do not iterate past the last element; if we're copying backwards, that
6309       // might take us off the start of the array.
6310       if (--NElems == 0)
6311         return true;
6312       if (!HandleLValueArrayAdjustment(Info, E, Src, T, Direction) ||
6313           !HandleLValueArrayAdjustment(Info, E, Dest, T, Direction))
6314         return false;
6315     }
6316   }
6317 
6318   default:
6319     return visitNonBuiltinCallExpr(E);
6320   }
6321 }
6322 
6323 //===----------------------------------------------------------------------===//
6324 // Member Pointer Evaluation
6325 //===----------------------------------------------------------------------===//
6326 
6327 namespace {
6328 class MemberPointerExprEvaluator
6329   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6330   MemberPtr &Result;
6331 
6332   bool Success(const ValueDecl *D) {
6333     Result = MemberPtr(D);
6334     return true;
6335   }
6336 public:
6337 
6338   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6339     : ExprEvaluatorBaseTy(Info), Result(Result) {}
6340 
6341   bool Success(const APValue &V, const Expr *E) {
6342     Result.setFrom(V);
6343     return true;
6344   }
6345   bool ZeroInitialization(const Expr *E) {
6346     return Success((const ValueDecl*)nullptr);
6347   }
6348 
6349   bool VisitCastExpr(const CastExpr *E);
6350   bool VisitUnaryAddrOf(const UnaryOperator *E);
6351 };
6352 } // end anonymous namespace
6353 
6354 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6355                                   EvalInfo &Info) {
6356   assert(E->isRValue() && E->getType()->isMemberPointerType());
6357   return MemberPointerExprEvaluator(Info, Result).Visit(E);
6358 }
6359 
6360 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6361   switch (E->getCastKind()) {
6362   default:
6363     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6364 
6365   case CK_NullToMemberPointer:
6366     VisitIgnoredValue(E->getSubExpr());
6367     return ZeroInitialization(E);
6368 
6369   case CK_BaseToDerivedMemberPointer: {
6370     if (!Visit(E->getSubExpr()))
6371       return false;
6372     if (E->path_empty())
6373       return true;
6374     // Base-to-derived member pointer casts store the path in derived-to-base
6375     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6376     // the wrong end of the derived->base arc, so stagger the path by one class.
6377     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6378     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6379          PathI != PathE; ++PathI) {
6380       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6381       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6382       if (!Result.castToDerived(Derived))
6383         return Error(E);
6384     }
6385     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6386     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6387       return Error(E);
6388     return true;
6389   }
6390 
6391   case CK_DerivedToBaseMemberPointer:
6392     if (!Visit(E->getSubExpr()))
6393       return false;
6394     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6395          PathE = E->path_end(); PathI != PathE; ++PathI) {
6396       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6397       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6398       if (!Result.castToBase(Base))
6399         return Error(E);
6400     }
6401     return true;
6402   }
6403 }
6404 
6405 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6406   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6407   // member can be formed.
6408   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6409 }
6410 
6411 //===----------------------------------------------------------------------===//
6412 // Record Evaluation
6413 //===----------------------------------------------------------------------===//
6414 
6415 namespace {
6416   class RecordExprEvaluator
6417   : public ExprEvaluatorBase<RecordExprEvaluator> {
6418     const LValue &This;
6419     APValue &Result;
6420   public:
6421 
6422     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6423       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6424 
6425     bool Success(const APValue &V, const Expr *E) {
6426       Result = V;
6427       return true;
6428     }
6429     bool ZeroInitialization(const Expr *E) {
6430       return ZeroInitialization(E, E->getType());
6431     }
6432     bool ZeroInitialization(const Expr *E, QualType T);
6433 
6434     bool VisitCallExpr(const CallExpr *E) {
6435       return handleCallExpr(E, Result, &This);
6436     }
6437     bool VisitCastExpr(const CastExpr *E);
6438     bool VisitInitListExpr(const InitListExpr *E);
6439     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6440       return VisitCXXConstructExpr(E, E->getType());
6441     }
6442     bool VisitLambdaExpr(const LambdaExpr *E);
6443     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6444     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6445     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6446 
6447     bool VisitBinCmp(const BinaryOperator *E);
6448   };
6449 }
6450 
6451 /// Perform zero-initialization on an object of non-union class type.
6452 /// C++11 [dcl.init]p5:
6453 ///  To zero-initialize an object or reference of type T means:
6454 ///    [...]
6455 ///    -- if T is a (possibly cv-qualified) non-union class type,
6456 ///       each non-static data member and each base-class subobject is
6457 ///       zero-initialized
6458 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6459                                           const RecordDecl *RD,
6460                                           const LValue &This, APValue &Result) {
6461   assert(!RD->isUnion() && "Expected non-union class type");
6462   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6463   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6464                    std::distance(RD->field_begin(), RD->field_end()));
6465 
6466   if (RD->isInvalidDecl()) return false;
6467   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6468 
6469   if (CD) {
6470     unsigned Index = 0;
6471     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6472            End = CD->bases_end(); I != End; ++I, ++Index) {
6473       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6474       LValue Subobject = This;
6475       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6476         return false;
6477       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6478                                          Result.getStructBase(Index)))
6479         return false;
6480     }
6481   }
6482 
6483   for (const auto *I : RD->fields()) {
6484     // -- if T is a reference type, no initialization is performed.
6485     if (I->getType()->isReferenceType())
6486       continue;
6487 
6488     LValue Subobject = This;
6489     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6490       return false;
6491 
6492     ImplicitValueInitExpr VIE(I->getType());
6493     if (!EvaluateInPlace(
6494           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6495       return false;
6496   }
6497 
6498   return true;
6499 }
6500 
6501 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6502   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6503   if (RD->isInvalidDecl()) return false;
6504   if (RD->isUnion()) {
6505     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6506     // object's first non-static named data member is zero-initialized
6507     RecordDecl::field_iterator I = RD->field_begin();
6508     if (I == RD->field_end()) {
6509       Result = APValue((const FieldDecl*)nullptr);
6510       return true;
6511     }
6512 
6513     LValue Subobject = This;
6514     if (!HandleLValueMember(Info, E, Subobject, *I))
6515       return false;
6516     Result = APValue(*I);
6517     ImplicitValueInitExpr VIE(I->getType());
6518     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6519   }
6520 
6521   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6522     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6523     return false;
6524   }
6525 
6526   return HandleClassZeroInitialization(Info, E, RD, This, Result);
6527 }
6528 
6529 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6530   switch (E->getCastKind()) {
6531   default:
6532     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6533 
6534   case CK_ConstructorConversion:
6535     return Visit(E->getSubExpr());
6536 
6537   case CK_DerivedToBase:
6538   case CK_UncheckedDerivedToBase: {
6539     APValue DerivedObject;
6540     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6541       return false;
6542     if (!DerivedObject.isStruct())
6543       return Error(E->getSubExpr());
6544 
6545     // Derived-to-base rvalue conversion: just slice off the derived part.
6546     APValue *Value = &DerivedObject;
6547     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6548     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6549          PathE = E->path_end(); PathI != PathE; ++PathI) {
6550       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6551       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6552       Value = &Value->getStructBase(getBaseIndex(RD, Base));
6553       RD = Base;
6554     }
6555     Result = *Value;
6556     return true;
6557   }
6558   }
6559 }
6560 
6561 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6562   if (E->isTransparent())
6563     return Visit(E->getInit(0));
6564 
6565   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6566   if (RD->isInvalidDecl()) return false;
6567   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6568 
6569   if (RD->isUnion()) {
6570     const FieldDecl *Field = E->getInitializedFieldInUnion();
6571     Result = APValue(Field);
6572     if (!Field)
6573       return true;
6574 
6575     // If the initializer list for a union does not contain any elements, the
6576     // first element of the union is value-initialized.
6577     // FIXME: The element should be initialized from an initializer list.
6578     //        Is this difference ever observable for initializer lists which
6579     //        we don't build?
6580     ImplicitValueInitExpr VIE(Field->getType());
6581     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6582 
6583     LValue Subobject = This;
6584     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6585       return false;
6586 
6587     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6588     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6589                                   isa<CXXDefaultInitExpr>(InitExpr));
6590 
6591     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6592   }
6593 
6594   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6595   if (Result.isUninit())
6596     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6597                      std::distance(RD->field_begin(), RD->field_end()));
6598   unsigned ElementNo = 0;
6599   bool Success = true;
6600 
6601   // Initialize base classes.
6602   if (CXXRD) {
6603     for (const auto &Base : CXXRD->bases()) {
6604       assert(ElementNo < E->getNumInits() && "missing init for base class");
6605       const Expr *Init = E->getInit(ElementNo);
6606 
6607       LValue Subobject = This;
6608       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6609         return false;
6610 
6611       APValue &FieldVal = Result.getStructBase(ElementNo);
6612       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6613         if (!Info.noteFailure())
6614           return false;
6615         Success = false;
6616       }
6617       ++ElementNo;
6618     }
6619   }
6620 
6621   // Initialize members.
6622   for (const auto *Field : RD->fields()) {
6623     // Anonymous bit-fields are not considered members of the class for
6624     // purposes of aggregate initialization.
6625     if (Field->isUnnamedBitfield())
6626       continue;
6627 
6628     LValue Subobject = This;
6629 
6630     bool HaveInit = ElementNo < E->getNumInits();
6631 
6632     // FIXME: Diagnostics here should point to the end of the initializer
6633     // list, not the start.
6634     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6635                             Subobject, Field, &Layout))
6636       return false;
6637 
6638     // Perform an implicit value-initialization for members beyond the end of
6639     // the initializer list.
6640     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6641     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6642 
6643     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6644     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6645                                   isa<CXXDefaultInitExpr>(Init));
6646 
6647     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6648     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6649         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6650                                                        FieldVal, Field))) {
6651       if (!Info.noteFailure())
6652         return false;
6653       Success = false;
6654     }
6655   }
6656 
6657   return Success;
6658 }
6659 
6660 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6661                                                 QualType T) {
6662   // Note that E's type is not necessarily the type of our class here; we might
6663   // be initializing an array element instead.
6664   const CXXConstructorDecl *FD = E->getConstructor();
6665   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6666 
6667   bool ZeroInit = E->requiresZeroInitialization();
6668   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6669     // If we've already performed zero-initialization, we're already done.
6670     if (!Result.isUninit())
6671       return true;
6672 
6673     // We can get here in two different ways:
6674     //  1) We're performing value-initialization, and should zero-initialize
6675     //     the object, or
6676     //  2) We're performing default-initialization of an object with a trivial
6677     //     constexpr default constructor, in which case we should start the
6678     //     lifetimes of all the base subobjects (there can be no data member
6679     //     subobjects in this case) per [basic.life]p1.
6680     // Either way, ZeroInitialization is appropriate.
6681     return ZeroInitialization(E, T);
6682   }
6683 
6684   const FunctionDecl *Definition = nullptr;
6685   auto Body = FD->getBody(Definition);
6686 
6687   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6688     return false;
6689 
6690   // Avoid materializing a temporary for an elidable copy/move constructor.
6691   if (E->isElidable() && !ZeroInit)
6692     if (const MaterializeTemporaryExpr *ME
6693           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6694       return Visit(ME->GetTemporaryExpr());
6695 
6696   if (ZeroInit && !ZeroInitialization(E, T))
6697     return false;
6698 
6699   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6700   return HandleConstructorCall(E, This, Args,
6701                                cast<CXXConstructorDecl>(Definition), Info,
6702                                Result);
6703 }
6704 
6705 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6706     const CXXInheritedCtorInitExpr *E) {
6707   if (!Info.CurrentCall) {
6708     assert(Info.checkingPotentialConstantExpression());
6709     return false;
6710   }
6711 
6712   const CXXConstructorDecl *FD = E->getConstructor();
6713   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6714     return false;
6715 
6716   const FunctionDecl *Definition = nullptr;
6717   auto Body = FD->getBody(Definition);
6718 
6719   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6720     return false;
6721 
6722   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6723                                cast<CXXConstructorDecl>(Definition), Info,
6724                                Result);
6725 }
6726 
6727 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6728     const CXXStdInitializerListExpr *E) {
6729   const ConstantArrayType *ArrayType =
6730       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6731 
6732   LValue Array;
6733   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6734     return false;
6735 
6736   // Get a pointer to the first element of the array.
6737   Array.addArray(Info, E, ArrayType);
6738 
6739   // FIXME: Perform the checks on the field types in SemaInit.
6740   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6741   RecordDecl::field_iterator Field = Record->field_begin();
6742   if (Field == Record->field_end())
6743     return Error(E);
6744 
6745   // Start pointer.
6746   if (!Field->getType()->isPointerType() ||
6747       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6748                             ArrayType->getElementType()))
6749     return Error(E);
6750 
6751   // FIXME: What if the initializer_list type has base classes, etc?
6752   Result = APValue(APValue::UninitStruct(), 0, 2);
6753   Array.moveInto(Result.getStructField(0));
6754 
6755   if (++Field == Record->field_end())
6756     return Error(E);
6757 
6758   if (Field->getType()->isPointerType() &&
6759       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6760                            ArrayType->getElementType())) {
6761     // End pointer.
6762     if (!HandleLValueArrayAdjustment(Info, E, Array,
6763                                      ArrayType->getElementType(),
6764                                      ArrayType->getSize().getZExtValue()))
6765       return false;
6766     Array.moveInto(Result.getStructField(1));
6767   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6768     // Length.
6769     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6770   else
6771     return Error(E);
6772 
6773   if (++Field != Record->field_end())
6774     return Error(E);
6775 
6776   return true;
6777 }
6778 
6779 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6780   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6781   if (ClosureClass->isInvalidDecl()) return false;
6782 
6783   if (Info.checkingPotentialConstantExpression()) return true;
6784 
6785   const size_t NumFields =
6786       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6787 
6788   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6789                                             E->capture_init_end()) &&
6790          "The number of lambda capture initializers should equal the number of "
6791          "fields within the closure type");
6792 
6793   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6794   // Iterate through all the lambda's closure object's fields and initialize
6795   // them.
6796   auto *CaptureInitIt = E->capture_init_begin();
6797   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6798   bool Success = true;
6799   for (const auto *Field : ClosureClass->fields()) {
6800     assert(CaptureInitIt != E->capture_init_end());
6801     // Get the initializer for this field
6802     Expr *const CurFieldInit = *CaptureInitIt++;
6803 
6804     // If there is no initializer, either this is a VLA or an error has
6805     // occurred.
6806     if (!CurFieldInit)
6807       return Error(E);
6808 
6809     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6810     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6811       if (!Info.keepEvaluatingAfterFailure())
6812         return false;
6813       Success = false;
6814     }
6815     ++CaptureIt;
6816   }
6817   return Success;
6818 }
6819 
6820 static bool EvaluateRecord(const Expr *E, const LValue &This,
6821                            APValue &Result, EvalInfo &Info) {
6822   assert(E->isRValue() && E->getType()->isRecordType() &&
6823          "can't evaluate expression as a record rvalue");
6824   return RecordExprEvaluator(Info, This, Result).Visit(E);
6825 }
6826 
6827 //===----------------------------------------------------------------------===//
6828 // Temporary Evaluation
6829 //
6830 // Temporaries are represented in the AST as rvalues, but generally behave like
6831 // lvalues. The full-object of which the temporary is a subobject is implicitly
6832 // materialized so that a reference can bind to it.
6833 //===----------------------------------------------------------------------===//
6834 namespace {
6835 class TemporaryExprEvaluator
6836   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6837 public:
6838   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6839     LValueExprEvaluatorBaseTy(Info, Result, false) {}
6840 
6841   /// Visit an expression which constructs the value of this temporary.
6842   bool VisitConstructExpr(const Expr *E) {
6843     APValue &Value = createTemporary(E, false, Result, *Info.CurrentCall);
6844     return EvaluateInPlace(Value, Info, Result, E);
6845   }
6846 
6847   bool VisitCastExpr(const CastExpr *E) {
6848     switch (E->getCastKind()) {
6849     default:
6850       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6851 
6852     case CK_ConstructorConversion:
6853       return VisitConstructExpr(E->getSubExpr());
6854     }
6855   }
6856   bool VisitInitListExpr(const InitListExpr *E) {
6857     return VisitConstructExpr(E);
6858   }
6859   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6860     return VisitConstructExpr(E);
6861   }
6862   bool VisitCallExpr(const CallExpr *E) {
6863     return VisitConstructExpr(E);
6864   }
6865   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6866     return VisitConstructExpr(E);
6867   }
6868   bool VisitLambdaExpr(const LambdaExpr *E) {
6869     return VisitConstructExpr(E);
6870   }
6871 };
6872 } // end anonymous namespace
6873 
6874 /// Evaluate an expression of record type as a temporary.
6875 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6876   assert(E->isRValue() && E->getType()->isRecordType());
6877   return TemporaryExprEvaluator(Info, Result).Visit(E);
6878 }
6879 
6880 //===----------------------------------------------------------------------===//
6881 // Vector Evaluation
6882 //===----------------------------------------------------------------------===//
6883 
6884 namespace {
6885   class VectorExprEvaluator
6886   : public ExprEvaluatorBase<VectorExprEvaluator> {
6887     APValue &Result;
6888   public:
6889 
6890     VectorExprEvaluator(EvalInfo &info, APValue &Result)
6891       : ExprEvaluatorBaseTy(info), Result(Result) {}
6892 
6893     bool Success(ArrayRef<APValue> V, const Expr *E) {
6894       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6895       // FIXME: remove this APValue copy.
6896       Result = APValue(V.data(), V.size());
6897       return true;
6898     }
6899     bool Success(const APValue &V, const Expr *E) {
6900       assert(V.isVector());
6901       Result = V;
6902       return true;
6903     }
6904     bool ZeroInitialization(const Expr *E);
6905 
6906     bool VisitUnaryReal(const UnaryOperator *E)
6907       { return Visit(E->getSubExpr()); }
6908     bool VisitCastExpr(const CastExpr* E);
6909     bool VisitInitListExpr(const InitListExpr *E);
6910     bool VisitUnaryImag(const UnaryOperator *E);
6911     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6912     //                 binary comparisons, binary and/or/xor,
6913     //                 shufflevector, ExtVectorElementExpr
6914   };
6915 } // end anonymous namespace
6916 
6917 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6918   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6919   return VectorExprEvaluator(Info, Result).Visit(E);
6920 }
6921 
6922 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6923   const VectorType *VTy = E->getType()->castAs<VectorType>();
6924   unsigned NElts = VTy->getNumElements();
6925 
6926   const Expr *SE = E->getSubExpr();
6927   QualType SETy = SE->getType();
6928 
6929   switch (E->getCastKind()) {
6930   case CK_VectorSplat: {
6931     APValue Val = APValue();
6932     if (SETy->isIntegerType()) {
6933       APSInt IntResult;
6934       if (!EvaluateInteger(SE, IntResult, Info))
6935         return false;
6936       Val = APValue(std::move(IntResult));
6937     } else if (SETy->isRealFloatingType()) {
6938       APFloat FloatResult(0.0);
6939       if (!EvaluateFloat(SE, FloatResult, Info))
6940         return false;
6941       Val = APValue(std::move(FloatResult));
6942     } else {
6943       return Error(E);
6944     }
6945 
6946     // Splat and create vector APValue.
6947     SmallVector<APValue, 4> Elts(NElts, Val);
6948     return Success(Elts, E);
6949   }
6950   case CK_BitCast: {
6951     // Evaluate the operand into an APInt we can extract from.
6952     llvm::APInt SValInt;
6953     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6954       return false;
6955     // Extract the elements
6956     QualType EltTy = VTy->getElementType();
6957     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6958     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6959     SmallVector<APValue, 4> Elts;
6960     if (EltTy->isRealFloatingType()) {
6961       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6962       unsigned FloatEltSize = EltSize;
6963       if (&Sem == &APFloat::x87DoubleExtended())
6964         FloatEltSize = 80;
6965       for (unsigned i = 0; i < NElts; i++) {
6966         llvm::APInt Elt;
6967         if (BigEndian)
6968           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6969         else
6970           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6971         Elts.push_back(APValue(APFloat(Sem, Elt)));
6972       }
6973     } else if (EltTy->isIntegerType()) {
6974       for (unsigned i = 0; i < NElts; i++) {
6975         llvm::APInt Elt;
6976         if (BigEndian)
6977           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6978         else
6979           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6980         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6981       }
6982     } else {
6983       return Error(E);
6984     }
6985     return Success(Elts, E);
6986   }
6987   default:
6988     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6989   }
6990 }
6991 
6992 bool
6993 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6994   const VectorType *VT = E->getType()->castAs<VectorType>();
6995   unsigned NumInits = E->getNumInits();
6996   unsigned NumElements = VT->getNumElements();
6997 
6998   QualType EltTy = VT->getElementType();
6999   SmallVector<APValue, 4> Elements;
7000 
7001   // The number of initializers can be less than the number of
7002   // vector elements. For OpenCL, this can be due to nested vector
7003   // initialization. For GCC compatibility, missing trailing elements
7004   // should be initialized with zeroes.
7005   unsigned CountInits = 0, CountElts = 0;
7006   while (CountElts < NumElements) {
7007     // Handle nested vector initialization.
7008     if (CountInits < NumInits
7009         && E->getInit(CountInits)->getType()->isVectorType()) {
7010       APValue v;
7011       if (!EvaluateVector(E->getInit(CountInits), v, Info))
7012         return Error(E);
7013       unsigned vlen = v.getVectorLength();
7014       for (unsigned j = 0; j < vlen; j++)
7015         Elements.push_back(v.getVectorElt(j));
7016       CountElts += vlen;
7017     } else if (EltTy->isIntegerType()) {
7018       llvm::APSInt sInt(32);
7019       if (CountInits < NumInits) {
7020         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
7021           return false;
7022       } else // trailing integer zero.
7023         sInt = Info.Ctx.MakeIntValue(0, EltTy);
7024       Elements.push_back(APValue(sInt));
7025       CountElts++;
7026     } else {
7027       llvm::APFloat f(0.0);
7028       if (CountInits < NumInits) {
7029         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
7030           return false;
7031       } else // trailing float zero.
7032         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
7033       Elements.push_back(APValue(f));
7034       CountElts++;
7035     }
7036     CountInits++;
7037   }
7038   return Success(Elements, E);
7039 }
7040 
7041 bool
7042 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
7043   const VectorType *VT = E->getType()->getAs<VectorType>();
7044   QualType EltTy = VT->getElementType();
7045   APValue ZeroElement;
7046   if (EltTy->isIntegerType())
7047     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
7048   else
7049     ZeroElement =
7050         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
7051 
7052   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
7053   return Success(Elements, E);
7054 }
7055 
7056 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
7057   VisitIgnoredValue(E->getSubExpr());
7058   return ZeroInitialization(E);
7059 }
7060 
7061 //===----------------------------------------------------------------------===//
7062 // Array Evaluation
7063 //===----------------------------------------------------------------------===//
7064 
7065 namespace {
7066   class ArrayExprEvaluator
7067   : public ExprEvaluatorBase<ArrayExprEvaluator> {
7068     const LValue &This;
7069     APValue &Result;
7070   public:
7071 
7072     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
7073       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
7074 
7075     bool Success(const APValue &V, const Expr *E) {
7076       assert((V.isArray() || V.isLValue()) &&
7077              "expected array or string literal");
7078       Result = V;
7079       return true;
7080     }
7081 
7082     bool ZeroInitialization(const Expr *E) {
7083       const ConstantArrayType *CAT =
7084           Info.Ctx.getAsConstantArrayType(E->getType());
7085       if (!CAT)
7086         return Error(E);
7087 
7088       Result = APValue(APValue::UninitArray(), 0,
7089                        CAT->getSize().getZExtValue());
7090       if (!Result.hasArrayFiller()) return true;
7091 
7092       // Zero-initialize all elements.
7093       LValue Subobject = This;
7094       Subobject.addArray(Info, E, CAT);
7095       ImplicitValueInitExpr VIE(CAT->getElementType());
7096       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
7097     }
7098 
7099     bool VisitCallExpr(const CallExpr *E) {
7100       return handleCallExpr(E, Result, &This);
7101     }
7102     bool VisitInitListExpr(const InitListExpr *E);
7103     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
7104     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
7105     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
7106                                const LValue &Subobject,
7107                                APValue *Value, QualType Type);
7108   };
7109 } // end anonymous namespace
7110 
7111 static bool EvaluateArray(const Expr *E, const LValue &This,
7112                           APValue &Result, EvalInfo &Info) {
7113   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
7114   return ArrayExprEvaluator(Info, This, Result).Visit(E);
7115 }
7116 
7117 // Return true iff the given array filler may depend on the element index.
7118 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
7119   // For now, just whitelist non-class value-initialization and initialization
7120   // lists comprised of them.
7121   if (isa<ImplicitValueInitExpr>(FillerExpr))
7122     return false;
7123   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
7124     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
7125       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
7126         return true;
7127     }
7128     return false;
7129   }
7130   return true;
7131 }
7132 
7133 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7134   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
7135   if (!CAT)
7136     return Error(E);
7137 
7138   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
7139   // an appropriately-typed string literal enclosed in braces.
7140   if (E->isStringLiteralInit()) {
7141     LValue LV;
7142     if (!EvaluateLValue(E->getInit(0), LV, Info))
7143       return false;
7144     APValue Val;
7145     LV.moveInto(Val);
7146     return Success(Val, E);
7147   }
7148 
7149   bool Success = true;
7150 
7151   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
7152          "zero-initialized array shouldn't have any initialized elts");
7153   APValue Filler;
7154   if (Result.isArray() && Result.hasArrayFiller())
7155     Filler = Result.getArrayFiller();
7156 
7157   unsigned NumEltsToInit = E->getNumInits();
7158   unsigned NumElts = CAT->getSize().getZExtValue();
7159   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
7160 
7161   // If the initializer might depend on the array index, run it for each
7162   // array element.
7163   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
7164     NumEltsToInit = NumElts;
7165 
7166   LLVM_DEBUG(llvm::dbgs() << "The number of elements to initialize: "
7167                           << NumEltsToInit << ".\n");
7168 
7169   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
7170 
7171   // If the array was previously zero-initialized, preserve the
7172   // zero-initialized values.
7173   if (!Filler.isUninit()) {
7174     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
7175       Result.getArrayInitializedElt(I) = Filler;
7176     if (Result.hasArrayFiller())
7177       Result.getArrayFiller() = Filler;
7178   }
7179 
7180   LValue Subobject = This;
7181   Subobject.addArray(Info, E, CAT);
7182   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
7183     const Expr *Init =
7184         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
7185     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7186                          Info, Subobject, Init) ||
7187         !HandleLValueArrayAdjustment(Info, Init, Subobject,
7188                                      CAT->getElementType(), 1)) {
7189       if (!Info.noteFailure())
7190         return false;
7191       Success = false;
7192     }
7193   }
7194 
7195   if (!Result.hasArrayFiller())
7196     return Success;
7197 
7198   // If we get here, we have a trivial filler, which we can just evaluate
7199   // once and splat over the rest of the array elements.
7200   assert(FillerExpr && "no array filler for incomplete init list");
7201   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
7202                          FillerExpr) && Success;
7203 }
7204 
7205 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
7206   if (E->getCommonExpr() &&
7207       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
7208                 Info, E->getCommonExpr()->getSourceExpr()))
7209     return false;
7210 
7211   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
7212 
7213   uint64_t Elements = CAT->getSize().getZExtValue();
7214   Result = APValue(APValue::UninitArray(), Elements, Elements);
7215 
7216   LValue Subobject = This;
7217   Subobject.addArray(Info, E, CAT);
7218 
7219   bool Success = true;
7220   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
7221     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
7222                          Info, Subobject, E->getSubExpr()) ||
7223         !HandleLValueArrayAdjustment(Info, E, Subobject,
7224                                      CAT->getElementType(), 1)) {
7225       if (!Info.noteFailure())
7226         return false;
7227       Success = false;
7228     }
7229   }
7230 
7231   return Success;
7232 }
7233 
7234 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
7235   return VisitCXXConstructExpr(E, This, &Result, E->getType());
7236 }
7237 
7238 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
7239                                                const LValue &Subobject,
7240                                                APValue *Value,
7241                                                QualType Type) {
7242   bool HadZeroInit = !Value->isUninit();
7243 
7244   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
7245     unsigned N = CAT->getSize().getZExtValue();
7246 
7247     // Preserve the array filler if we had prior zero-initialization.
7248     APValue Filler =
7249       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
7250                                              : APValue();
7251 
7252     *Value = APValue(APValue::UninitArray(), N, N);
7253 
7254     if (HadZeroInit)
7255       for (unsigned I = 0; I != N; ++I)
7256         Value->getArrayInitializedElt(I) = Filler;
7257 
7258     // Initialize the elements.
7259     LValue ArrayElt = Subobject;
7260     ArrayElt.addArray(Info, E, CAT);
7261     for (unsigned I = 0; I != N; ++I)
7262       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
7263                                  CAT->getElementType()) ||
7264           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
7265                                        CAT->getElementType(), 1))
7266         return false;
7267 
7268     return true;
7269   }
7270 
7271   if (!Type->isRecordType())
7272     return Error(E);
7273 
7274   return RecordExprEvaluator(Info, Subobject, *Value)
7275              .VisitCXXConstructExpr(E, Type);
7276 }
7277 
7278 //===----------------------------------------------------------------------===//
7279 // Integer Evaluation
7280 //
7281 // As a GNU extension, we support casting pointers to sufficiently-wide integer
7282 // types and back in constant folding. Integer values are thus represented
7283 // either as an integer-valued APValue, or as an lvalue-valued APValue.
7284 //===----------------------------------------------------------------------===//
7285 
7286 namespace {
7287 class IntExprEvaluator
7288         : public ExprEvaluatorBase<IntExprEvaluator> {
7289   APValue &Result;
7290 public:
7291   IntExprEvaluator(EvalInfo &info, APValue &result)
7292       : ExprEvaluatorBaseTy(info), Result(result) {}
7293 
7294   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7295     assert(E->getType()->isIntegralOrEnumerationType() &&
7296            "Invalid evaluation result.");
7297     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
7298            "Invalid evaluation result.");
7299     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7300            "Invalid evaluation result.");
7301     Result = APValue(SI);
7302     return true;
7303   }
7304   bool Success(const llvm::APSInt &SI, const Expr *E) {
7305     return Success(SI, E, Result);
7306   }
7307 
7308   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7309     assert(E->getType()->isIntegralOrEnumerationType() &&
7310            "Invalid evaluation result.");
7311     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7312            "Invalid evaluation result.");
7313     Result = APValue(APSInt(I));
7314     Result.getInt().setIsUnsigned(
7315                             E->getType()->isUnsignedIntegerOrEnumerationType());
7316     return true;
7317   }
7318   bool Success(const llvm::APInt &I, const Expr *E) {
7319     return Success(I, E, Result);
7320   }
7321 
7322   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7323     assert(E->getType()->isIntegralOrEnumerationType() &&
7324            "Invalid evaluation result.");
7325     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7326     return true;
7327   }
7328   bool Success(uint64_t Value, const Expr *E) {
7329     return Success(Value, E, Result);
7330   }
7331 
7332   bool Success(CharUnits Size, const Expr *E) {
7333     return Success(Size.getQuantity(), E);
7334   }
7335 
7336   bool Success(const APValue &V, const Expr *E) {
7337     if (V.isLValue() || V.isAddrLabelDiff()) {
7338       Result = V;
7339       return true;
7340     }
7341     return Success(V.getInt(), E);
7342   }
7343 
7344   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7345 
7346   //===--------------------------------------------------------------------===//
7347   //                            Visitor Methods
7348   //===--------------------------------------------------------------------===//
7349 
7350   bool VisitIntegerLiteral(const IntegerLiteral *E) {
7351     return Success(E->getValue(), E);
7352   }
7353   bool VisitCharacterLiteral(const CharacterLiteral *E) {
7354     return Success(E->getValue(), E);
7355   }
7356 
7357   bool CheckReferencedDecl(const Expr *E, const Decl *D);
7358   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7359     if (CheckReferencedDecl(E, E->getDecl()))
7360       return true;
7361 
7362     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7363   }
7364   bool VisitMemberExpr(const MemberExpr *E) {
7365     if (CheckReferencedDecl(E, E->getMemberDecl())) {
7366       VisitIgnoredBaseExpression(E->getBase());
7367       return true;
7368     }
7369 
7370     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7371   }
7372 
7373   bool VisitCallExpr(const CallExpr *E);
7374   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7375   bool VisitBinaryOperator(const BinaryOperator *E);
7376   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7377   bool VisitUnaryOperator(const UnaryOperator *E);
7378 
7379   bool VisitCastExpr(const CastExpr* E);
7380   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7381 
7382   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7383     return Success(E->getValue(), E);
7384   }
7385 
7386   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7387     return Success(E->getValue(), E);
7388   }
7389 
7390   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7391     if (Info.ArrayInitIndex == uint64_t(-1)) {
7392       // We were asked to evaluate this subexpression independent of the
7393       // enclosing ArrayInitLoopExpr. We can't do that.
7394       Info.FFDiag(E);
7395       return false;
7396     }
7397     return Success(Info.ArrayInitIndex, E);
7398   }
7399 
7400   // Note, GNU defines __null as an integer, not a pointer.
7401   bool VisitGNUNullExpr(const GNUNullExpr *E) {
7402     return ZeroInitialization(E);
7403   }
7404 
7405   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7406     return Success(E->getValue(), E);
7407   }
7408 
7409   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7410     return Success(E->getValue(), E);
7411   }
7412 
7413   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7414     return Success(E->getValue(), E);
7415   }
7416 
7417   bool VisitUnaryReal(const UnaryOperator *E);
7418   bool VisitUnaryImag(const UnaryOperator *E);
7419 
7420   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7421   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7422 
7423   // FIXME: Missing: array subscript of vector, member of vector
7424 };
7425 
7426 class FixedPointExprEvaluator
7427     : public ExprEvaluatorBase<FixedPointExprEvaluator> {
7428   APValue &Result;
7429 
7430  public:
7431   FixedPointExprEvaluator(EvalInfo &info, APValue &result)
7432       : ExprEvaluatorBaseTy(info), Result(result) {}
7433 
7434   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
7435     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7436     assert(SI.isSigned() == E->getType()->isSignedFixedPointType() &&
7437            "Invalid evaluation result.");
7438     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7439            "Invalid evaluation result.");
7440     Result = APValue(SI);
7441     return true;
7442   }
7443   bool Success(const llvm::APSInt &SI, const Expr *E) {
7444     return Success(SI, E, Result);
7445   }
7446 
7447   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7448     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7449     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7450            "Invalid evaluation result.");
7451     Result = APValue(APSInt(I));
7452     Result.getInt().setIsUnsigned(E->getType()->isUnsignedFixedPointType());
7453     return true;
7454   }
7455   bool Success(const llvm::APInt &I, const Expr *E) {
7456     return Success(I, E, Result);
7457   }
7458 
7459   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7460     assert(E->getType()->isFixedPointType() && "Invalid evaluation result.");
7461     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7462     return true;
7463   }
7464   bool Success(uint64_t Value, const Expr *E) {
7465     return Success(Value, E, Result);
7466   }
7467 
7468   bool Success(CharUnits Size, const Expr *E) {
7469     return Success(Size.getQuantity(), E);
7470   }
7471 
7472   bool Success(const APValue &V, const Expr *E) {
7473     if (V.isLValue() || V.isAddrLabelDiff()) {
7474       Result = V;
7475       return true;
7476     }
7477     return Success(V.getInt(), E);
7478   }
7479 
7480   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7481 
7482   //===--------------------------------------------------------------------===//
7483   //                            Visitor Methods
7484   //===--------------------------------------------------------------------===//
7485 
7486   bool VisitFixedPointLiteral(const FixedPointLiteral *E) {
7487     return Success(E->getValue(), E);
7488   }
7489 
7490   bool VisitUnaryOperator(const UnaryOperator *E);
7491 };
7492 } // end anonymous namespace
7493 
7494 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7495 /// produce either the integer value or a pointer.
7496 ///
7497 /// GCC has a heinous extension which folds casts between pointer types and
7498 /// pointer-sized integral types. We support this by allowing the evaluation of
7499 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7500 /// Some simple arithmetic on such values is supported (they are treated much
7501 /// like char*).
7502 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7503                                     EvalInfo &Info) {
7504   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7505   return IntExprEvaluator(Info, Result).Visit(E);
7506 }
7507 
7508 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7509   APValue Val;
7510   if (!EvaluateIntegerOrLValue(E, Val, Info))
7511     return false;
7512   if (!Val.isInt()) {
7513     // FIXME: It would be better to produce the diagnostic for casting
7514     //        a pointer to an integer.
7515     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7516     return false;
7517   }
7518   Result = Val.getInt();
7519   return true;
7520 }
7521 
7522 /// Check whether the given declaration can be directly converted to an integral
7523 /// rvalue. If not, no diagnostic is produced; there are other things we can
7524 /// try.
7525 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7526   // Enums are integer constant exprs.
7527   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7528     // Check for signedness/width mismatches between E type and ECD value.
7529     bool SameSign = (ECD->getInitVal().isSigned()
7530                      == E->getType()->isSignedIntegerOrEnumerationType());
7531     bool SameWidth = (ECD->getInitVal().getBitWidth()
7532                       == Info.Ctx.getIntWidth(E->getType()));
7533     if (SameSign && SameWidth)
7534       return Success(ECD->getInitVal(), E);
7535     else {
7536       // Get rid of mismatch (otherwise Success assertions will fail)
7537       // by computing a new value matching the type of E.
7538       llvm::APSInt Val = ECD->getInitVal();
7539       if (!SameSign)
7540         Val.setIsSigned(!ECD->getInitVal().isSigned());
7541       if (!SameWidth)
7542         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7543       return Success(Val, E);
7544     }
7545   }
7546   return false;
7547 }
7548 
7549 /// Values returned by __builtin_classify_type, chosen to match the values
7550 /// produced by GCC's builtin.
7551 enum class GCCTypeClass {
7552   None = -1,
7553   Void = 0,
7554   Integer = 1,
7555   // GCC reserves 2 for character types, but instead classifies them as
7556   // integers.
7557   Enum = 3,
7558   Bool = 4,
7559   Pointer = 5,
7560   // GCC reserves 6 for references, but appears to never use it (because
7561   // expressions never have reference type, presumably).
7562   PointerToDataMember = 7,
7563   RealFloat = 8,
7564   Complex = 9,
7565   // GCC reserves 10 for functions, but does not use it since GCC version 6 due
7566   // to decay to pointer. (Prior to version 6 it was only used in C++ mode).
7567   // GCC claims to reserve 11 for pointers to member functions, but *actually*
7568   // uses 12 for that purpose, same as for a class or struct. Maybe it
7569   // internally implements a pointer to member as a struct?  Who knows.
7570   PointerToMemberFunction = 12, // Not a bug, see above.
7571   ClassOrStruct = 12,
7572   Union = 13,
7573   // GCC reserves 14 for arrays, but does not use it since GCC version 6 due to
7574   // decay to pointer. (Prior to version 6 it was only used in C++ mode).
7575   // GCC reserves 15 for strings, but actually uses 5 (pointer) for string
7576   // literals.
7577 };
7578 
7579 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7580 /// as GCC.
7581 static GCCTypeClass
7582 EvaluateBuiltinClassifyType(QualType T, const LangOptions &LangOpts) {
7583   assert(!T->isDependentType() && "unexpected dependent type");
7584 
7585   QualType CanTy = T.getCanonicalType();
7586   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7587 
7588   switch (CanTy->getTypeClass()) {
7589 #define TYPE(ID, BASE)
7590 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7591 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7592 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7593 #include "clang/AST/TypeNodes.def"
7594   case Type::Auto:
7595   case Type::DeducedTemplateSpecialization:
7596       llvm_unreachable("unexpected non-canonical or dependent type");
7597 
7598   case Type::Builtin:
7599     switch (BT->getKind()) {
7600 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7601 #define SIGNED_TYPE(ID, SINGLETON_ID) \
7602     case BuiltinType::ID: return GCCTypeClass::Integer;
7603 #define FLOATING_TYPE(ID, SINGLETON_ID) \
7604     case BuiltinType::ID: return GCCTypeClass::RealFloat;
7605 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) \
7606     case BuiltinType::ID: break;
7607 #include "clang/AST/BuiltinTypes.def"
7608     case BuiltinType::Void:
7609       return GCCTypeClass::Void;
7610 
7611     case BuiltinType::Bool:
7612       return GCCTypeClass::Bool;
7613 
7614     case BuiltinType::Char_U:
7615     case BuiltinType::UChar:
7616     case BuiltinType::WChar_U:
7617     case BuiltinType::Char8:
7618     case BuiltinType::Char16:
7619     case BuiltinType::Char32:
7620     case BuiltinType::UShort:
7621     case BuiltinType::UInt:
7622     case BuiltinType::ULong:
7623     case BuiltinType::ULongLong:
7624     case BuiltinType::UInt128:
7625       return GCCTypeClass::Integer;
7626 
7627     case BuiltinType::UShortAccum:
7628     case BuiltinType::UAccum:
7629     case BuiltinType::ULongAccum:
7630     case BuiltinType::UShortFract:
7631     case BuiltinType::UFract:
7632     case BuiltinType::ULongFract:
7633     case BuiltinType::SatUShortAccum:
7634     case BuiltinType::SatUAccum:
7635     case BuiltinType::SatULongAccum:
7636     case BuiltinType::SatUShortFract:
7637     case BuiltinType::SatUFract:
7638     case BuiltinType::SatULongFract:
7639       return GCCTypeClass::None;
7640 
7641     case BuiltinType::NullPtr:
7642 
7643     case BuiltinType::ObjCId:
7644     case BuiltinType::ObjCClass:
7645     case BuiltinType::ObjCSel:
7646 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7647     case BuiltinType::Id:
7648 #include "clang/Basic/OpenCLImageTypes.def"
7649 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
7650     case BuiltinType::Id:
7651 #include "clang/Basic/OpenCLExtensionTypes.def"
7652     case BuiltinType::OCLSampler:
7653     case BuiltinType::OCLEvent:
7654     case BuiltinType::OCLClkEvent:
7655     case BuiltinType::OCLQueue:
7656     case BuiltinType::OCLReserveID:
7657       return GCCTypeClass::None;
7658 
7659     case BuiltinType::Dependent:
7660       llvm_unreachable("unexpected dependent type");
7661     };
7662     llvm_unreachable("unexpected placeholder type");
7663 
7664   case Type::Enum:
7665     return LangOpts.CPlusPlus ? GCCTypeClass::Enum : GCCTypeClass::Integer;
7666 
7667   case Type::Pointer:
7668   case Type::ConstantArray:
7669   case Type::VariableArray:
7670   case Type::IncompleteArray:
7671   case Type::FunctionNoProto:
7672   case Type::FunctionProto:
7673     return GCCTypeClass::Pointer;
7674 
7675   case Type::MemberPointer:
7676     return CanTy->isMemberDataPointerType()
7677                ? GCCTypeClass::PointerToDataMember
7678                : GCCTypeClass::PointerToMemberFunction;
7679 
7680   case Type::Complex:
7681     return GCCTypeClass::Complex;
7682 
7683   case Type::Record:
7684     return CanTy->isUnionType() ? GCCTypeClass::Union
7685                                 : GCCTypeClass::ClassOrStruct;
7686 
7687   case Type::Atomic:
7688     // GCC classifies _Atomic T the same as T.
7689     return EvaluateBuiltinClassifyType(
7690         CanTy->castAs<AtomicType>()->getValueType(), LangOpts);
7691 
7692   case Type::BlockPointer:
7693   case Type::Vector:
7694   case Type::ExtVector:
7695   case Type::ObjCObject:
7696   case Type::ObjCInterface:
7697   case Type::ObjCObjectPointer:
7698   case Type::Pipe:
7699     // GCC classifies vectors as None. We follow its lead and classify all
7700     // other types that don't fit into the regular classification the same way.
7701     return GCCTypeClass::None;
7702 
7703   case Type::LValueReference:
7704   case Type::RValueReference:
7705     llvm_unreachable("invalid type for expression");
7706   }
7707 
7708   llvm_unreachable("unexpected type class");
7709 }
7710 
7711 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7712 /// as GCC.
7713 static GCCTypeClass
7714 EvaluateBuiltinClassifyType(const CallExpr *E, const LangOptions &LangOpts) {
7715   // If no argument was supplied, default to None. This isn't
7716   // ideal, however it is what gcc does.
7717   if (E->getNumArgs() == 0)
7718     return GCCTypeClass::None;
7719 
7720   // FIXME: Bizarrely, GCC treats a call with more than one argument as not
7721   // being an ICE, but still folds it to a constant using the type of the first
7722   // argument.
7723   return EvaluateBuiltinClassifyType(E->getArg(0)->getType(), LangOpts);
7724 }
7725 
7726 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7727 /// __builtin_constant_p when applied to the given lvalue.
7728 ///
7729 /// An lvalue is only "constant" if it is a pointer or reference to the first
7730 /// character of a string literal.
7731 template<typename LValue>
7732 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7733   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7734   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7735 }
7736 
7737 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7738 /// GCC as we can manage.
7739 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7740   QualType ArgType = Arg->getType();
7741 
7742   // __builtin_constant_p always has one operand. The rules which gcc follows
7743   // are not precisely documented, but are as follows:
7744   //
7745   //  - If the operand is of integral, floating, complex or enumeration type,
7746   //    and can be folded to a known value of that type, it returns 1.
7747   //  - If the operand and can be folded to a pointer to the first character
7748   //    of a string literal (or such a pointer cast to an integral type), it
7749   //    returns 1.
7750   //
7751   // Otherwise, it returns 0.
7752   //
7753   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7754   // its support for this does not currently work.
7755   if (ArgType->isIntegralOrEnumerationType()) {
7756     Expr::EvalResult Result;
7757     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7758       return false;
7759 
7760     APValue &V = Result.Val;
7761     if (V.getKind() == APValue::Int)
7762       return true;
7763     if (V.getKind() == APValue::LValue)
7764       return EvaluateBuiltinConstantPForLValue(V);
7765   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7766     return Arg->isEvaluatable(Ctx);
7767   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7768     LValue LV;
7769     Expr::EvalStatus Status;
7770     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7771     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7772                           : EvaluatePointer(Arg, LV, Info)) &&
7773         !Status.HasSideEffects)
7774       return EvaluateBuiltinConstantPForLValue(LV);
7775   }
7776 
7777   // Anything else isn't considered to be sufficiently constant.
7778   return false;
7779 }
7780 
7781 /// Retrieves the "underlying object type" of the given expression,
7782 /// as used by __builtin_object_size.
7783 static QualType getObjectType(APValue::LValueBase B) {
7784   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7785     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7786       return VD->getType();
7787   } else if (const Expr *E = B.get<const Expr*>()) {
7788     if (isa<CompoundLiteralExpr>(E))
7789       return E->getType();
7790   }
7791 
7792   return QualType();
7793 }
7794 
7795 /// A more selective version of E->IgnoreParenCasts for
7796 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7797 /// to change the type of E.
7798 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7799 ///
7800 /// Always returns an RValue with a pointer representation.
7801 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7802   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7803 
7804   auto *NoParens = E->IgnoreParens();
7805   auto *Cast = dyn_cast<CastExpr>(NoParens);
7806   if (Cast == nullptr)
7807     return NoParens;
7808 
7809   // We only conservatively allow a few kinds of casts, because this code is
7810   // inherently a simple solution that seeks to support the common case.
7811   auto CastKind = Cast->getCastKind();
7812   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7813       CastKind != CK_AddressSpaceConversion)
7814     return NoParens;
7815 
7816   auto *SubExpr = Cast->getSubExpr();
7817   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7818     return NoParens;
7819   return ignorePointerCastsAndParens(SubExpr);
7820 }
7821 
7822 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7823 /// record layout. e.g.
7824 ///   struct { struct { int a, b; } fst, snd; } obj;
7825 ///   obj.fst   // no
7826 ///   obj.snd   // yes
7827 ///   obj.fst.a // no
7828 ///   obj.fst.b // no
7829 ///   obj.snd.a // no
7830 ///   obj.snd.b // yes
7831 ///
7832 /// Please note: this function is specialized for how __builtin_object_size
7833 /// views "objects".
7834 ///
7835 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7836 /// correct result, it will always return true.
7837 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7838   assert(!LVal.Designator.Invalid);
7839 
7840   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7841     const RecordDecl *Parent = FD->getParent();
7842     Invalid = Parent->isInvalidDecl();
7843     if (Invalid || Parent->isUnion())
7844       return true;
7845     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7846     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7847   };
7848 
7849   auto &Base = LVal.getLValueBase();
7850   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7851     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7852       bool Invalid;
7853       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7854         return Invalid;
7855     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7856       for (auto *FD : IFD->chain()) {
7857         bool Invalid;
7858         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7859           return Invalid;
7860       }
7861     }
7862   }
7863 
7864   unsigned I = 0;
7865   QualType BaseType = getType(Base);
7866   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7867     // If we don't know the array bound, conservatively assume we're looking at
7868     // the final array element.
7869     ++I;
7870     if (BaseType->isIncompleteArrayType())
7871       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7872     else
7873       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7874   }
7875 
7876   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7877     const auto &Entry = LVal.Designator.Entries[I];
7878     if (BaseType->isArrayType()) {
7879       // Because __builtin_object_size treats arrays as objects, we can ignore
7880       // the index iff this is the last array in the Designator.
7881       if (I + 1 == E)
7882         return true;
7883       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7884       uint64_t Index = Entry.ArrayIndex;
7885       if (Index + 1 != CAT->getSize())
7886         return false;
7887       BaseType = CAT->getElementType();
7888     } else if (BaseType->isAnyComplexType()) {
7889       const auto *CT = BaseType->castAs<ComplexType>();
7890       uint64_t Index = Entry.ArrayIndex;
7891       if (Index != 1)
7892         return false;
7893       BaseType = CT->getElementType();
7894     } else if (auto *FD = getAsField(Entry)) {
7895       bool Invalid;
7896       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7897         return Invalid;
7898       BaseType = FD->getType();
7899     } else {
7900       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7901       return false;
7902     }
7903   }
7904   return true;
7905 }
7906 
7907 /// Tests to see if the LValue has a user-specified designator (that isn't
7908 /// necessarily valid). Note that this always returns 'true' if the LValue has
7909 /// an unsized array as its first designator entry, because there's currently no
7910 /// way to tell if the user typed *foo or foo[0].
7911 static bool refersToCompleteObject(const LValue &LVal) {
7912   if (LVal.Designator.Invalid)
7913     return false;
7914 
7915   if (!LVal.Designator.Entries.empty())
7916     return LVal.Designator.isMostDerivedAnUnsizedArray();
7917 
7918   if (!LVal.InvalidBase)
7919     return true;
7920 
7921   // If `E` is a MemberExpr, then the first part of the designator is hiding in
7922   // the LValueBase.
7923   const auto *E = LVal.Base.dyn_cast<const Expr *>();
7924   return !E || !isa<MemberExpr>(E);
7925 }
7926 
7927 /// Attempts to detect a user writing into a piece of memory that's impossible
7928 /// to figure out the size of by just using types.
7929 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7930   const SubobjectDesignator &Designator = LVal.Designator;
7931   // Notes:
7932   // - Users can only write off of the end when we have an invalid base. Invalid
7933   //   bases imply we don't know where the memory came from.
7934   // - We used to be a bit more aggressive here; we'd only be conservative if
7935   //   the array at the end was flexible, or if it had 0 or 1 elements. This
7936   //   broke some common standard library extensions (PR30346), but was
7937   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
7938   //   with some sort of whitelist. OTOH, it seems that GCC is always
7939   //   conservative with the last element in structs (if it's an array), so our
7940   //   current behavior is more compatible than a whitelisting approach would
7941   //   be.
7942   return LVal.InvalidBase &&
7943          Designator.Entries.size() == Designator.MostDerivedPathLength &&
7944          Designator.MostDerivedIsArrayElement &&
7945          isDesignatorAtObjectEnd(Ctx, LVal);
7946 }
7947 
7948 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7949 /// Fails if the conversion would cause loss of precision.
7950 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7951                                             CharUnits &Result) {
7952   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7953   if (Int.ugt(CharUnitsMax))
7954     return false;
7955   Result = CharUnits::fromQuantity(Int.getZExtValue());
7956   return true;
7957 }
7958 
7959 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7960 /// determine how many bytes exist from the beginning of the object to either
7961 /// the end of the current subobject, or the end of the object itself, depending
7962 /// on what the LValue looks like + the value of Type.
7963 ///
7964 /// If this returns false, the value of Result is undefined.
7965 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7966                                unsigned Type, const LValue &LVal,
7967                                CharUnits &EndOffset) {
7968   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7969 
7970   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7971     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7972       return false;
7973     return HandleSizeof(Info, ExprLoc, Ty, Result);
7974   };
7975 
7976   // We want to evaluate the size of the entire object. This is a valid fallback
7977   // for when Type=1 and the designator is invalid, because we're asked for an
7978   // upper-bound.
7979   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7980     // Type=3 wants a lower bound, so we can't fall back to this.
7981     if (Type == 3 && !DetermineForCompleteObject)
7982       return false;
7983 
7984     llvm::APInt APEndOffset;
7985     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7986         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7987       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7988 
7989     if (LVal.InvalidBase)
7990       return false;
7991 
7992     QualType BaseTy = getObjectType(LVal.getLValueBase());
7993     return CheckedHandleSizeof(BaseTy, EndOffset);
7994   }
7995 
7996   // We want to evaluate the size of a subobject.
7997   const SubobjectDesignator &Designator = LVal.Designator;
7998 
7999   // The following is a moderately common idiom in C:
8000   //
8001   // struct Foo { int a; char c[1]; };
8002   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
8003   // strcpy(&F->c[0], Bar);
8004   //
8005   // In order to not break too much legacy code, we need to support it.
8006   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
8007     // If we can resolve this to an alloc_size call, we can hand that back,
8008     // because we know for certain how many bytes there are to write to.
8009     llvm::APInt APEndOffset;
8010     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
8011         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
8012       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
8013 
8014     // If we cannot determine the size of the initial allocation, then we can't
8015     // given an accurate upper-bound. However, we are still able to give
8016     // conservative lower-bounds for Type=3.
8017     if (Type == 1)
8018       return false;
8019   }
8020 
8021   CharUnits BytesPerElem;
8022   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
8023     return false;
8024 
8025   // According to the GCC documentation, we want the size of the subobject
8026   // denoted by the pointer. But that's not quite right -- what we actually
8027   // want is the size of the immediately-enclosing array, if there is one.
8028   int64_t ElemsRemaining;
8029   if (Designator.MostDerivedIsArrayElement &&
8030       Designator.Entries.size() == Designator.MostDerivedPathLength) {
8031     uint64_t ArraySize = Designator.getMostDerivedArraySize();
8032     uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
8033     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
8034   } else {
8035     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
8036   }
8037 
8038   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
8039   return true;
8040 }
8041 
8042 /// Tries to evaluate the __builtin_object_size for @p E. If successful,
8043 /// returns true and stores the result in @p Size.
8044 ///
8045 /// If @p WasError is non-null, this will report whether the failure to evaluate
8046 /// is to be treated as an Error in IntExprEvaluator.
8047 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
8048                                          EvalInfo &Info, uint64_t &Size) {
8049   // Determine the denoted object.
8050   LValue LVal;
8051   {
8052     // The operand of __builtin_object_size is never evaluated for side-effects.
8053     // If there are any, but we can determine the pointed-to object anyway, then
8054     // ignore the side-effects.
8055     SpeculativeEvaluationRAII SpeculativeEval(Info);
8056     IgnoreSideEffectsRAII Fold(Info);
8057 
8058     if (E->isGLValue()) {
8059       // It's possible for us to be given GLValues if we're called via
8060       // Expr::tryEvaluateObjectSize.
8061       APValue RVal;
8062       if (!EvaluateAsRValue(Info, E, RVal))
8063         return false;
8064       LVal.setFrom(Info.Ctx, RVal);
8065     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
8066                                 /*InvalidBaseOK=*/true))
8067       return false;
8068   }
8069 
8070   // If we point to before the start of the object, there are no accessible
8071   // bytes.
8072   if (LVal.getLValueOffset().isNegative()) {
8073     Size = 0;
8074     return true;
8075   }
8076 
8077   CharUnits EndOffset;
8078   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
8079     return false;
8080 
8081   // If we've fallen outside of the end offset, just pretend there's nothing to
8082   // write to/read from.
8083   if (EndOffset <= LVal.getLValueOffset())
8084     Size = 0;
8085   else
8086     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
8087   return true;
8088 }
8089 
8090 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
8091   if (unsigned BuiltinOp = E->getBuiltinCallee())
8092     return VisitBuiltinCallExpr(E, BuiltinOp);
8093 
8094   return ExprEvaluatorBaseTy::VisitCallExpr(E);
8095 }
8096 
8097 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
8098                                             unsigned BuiltinOp) {
8099   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
8100   default:
8101     return ExprEvaluatorBaseTy::VisitCallExpr(E);
8102 
8103   case Builtin::BI__builtin_object_size: {
8104     // The type was checked when we built the expression.
8105     unsigned Type =
8106         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8107     assert(Type <= 3 && "unexpected type");
8108 
8109     uint64_t Size;
8110     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
8111       return Success(Size, E);
8112 
8113     if (E->getArg(0)->HasSideEffects(Info.Ctx))
8114       return Success((Type & 2) ? 0 : -1, E);
8115 
8116     // Expression had no side effects, but we couldn't statically determine the
8117     // size of the referenced object.
8118     switch (Info.EvalMode) {
8119     case EvalInfo::EM_ConstantExpression:
8120     case EvalInfo::EM_PotentialConstantExpression:
8121     case EvalInfo::EM_ConstantFold:
8122     case EvalInfo::EM_EvaluateForOverflow:
8123     case EvalInfo::EM_IgnoreSideEffects:
8124       // Leave it to IR generation.
8125       return Error(E);
8126     case EvalInfo::EM_ConstantExpressionUnevaluated:
8127     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
8128       // Reduce it to a constant now.
8129       return Success((Type & 2) ? 0 : -1, E);
8130     }
8131 
8132     llvm_unreachable("unexpected EvalMode");
8133   }
8134 
8135   case Builtin::BI__builtin_os_log_format_buffer_size: {
8136     analyze_os_log::OSLogBufferLayout Layout;
8137     analyze_os_log::computeOSLogBufferLayout(Info.Ctx, E, Layout);
8138     return Success(Layout.size().getQuantity(), E);
8139   }
8140 
8141   case Builtin::BI__builtin_bswap16:
8142   case Builtin::BI__builtin_bswap32:
8143   case Builtin::BI__builtin_bswap64: {
8144     APSInt Val;
8145     if (!EvaluateInteger(E->getArg(0), Val, Info))
8146       return false;
8147 
8148     return Success(Val.byteSwap(), E);
8149   }
8150 
8151   case Builtin::BI__builtin_classify_type:
8152     return Success((int)EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
8153 
8154   case Builtin::BI__builtin_clrsb:
8155   case Builtin::BI__builtin_clrsbl:
8156   case Builtin::BI__builtin_clrsbll: {
8157     APSInt Val;
8158     if (!EvaluateInteger(E->getArg(0), Val, Info))
8159       return false;
8160 
8161     return Success(Val.getBitWidth() - Val.getMinSignedBits(), E);
8162   }
8163 
8164   case Builtin::BI__builtin_clz:
8165   case Builtin::BI__builtin_clzl:
8166   case Builtin::BI__builtin_clzll:
8167   case Builtin::BI__builtin_clzs: {
8168     APSInt Val;
8169     if (!EvaluateInteger(E->getArg(0), Val, Info))
8170       return false;
8171     if (!Val)
8172       return Error(E);
8173 
8174     return Success(Val.countLeadingZeros(), E);
8175   }
8176 
8177   case Builtin::BI__builtin_constant_p:
8178     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
8179 
8180   case Builtin::BI__builtin_ctz:
8181   case Builtin::BI__builtin_ctzl:
8182   case Builtin::BI__builtin_ctzll:
8183   case Builtin::BI__builtin_ctzs: {
8184     APSInt Val;
8185     if (!EvaluateInteger(E->getArg(0), Val, Info))
8186       return false;
8187     if (!Val)
8188       return Error(E);
8189 
8190     return Success(Val.countTrailingZeros(), E);
8191   }
8192 
8193   case Builtin::BI__builtin_eh_return_data_regno: {
8194     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
8195     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
8196     return Success(Operand, E);
8197   }
8198 
8199   case Builtin::BI__builtin_expect:
8200     return Visit(E->getArg(0));
8201 
8202   case Builtin::BI__builtin_ffs:
8203   case Builtin::BI__builtin_ffsl:
8204   case Builtin::BI__builtin_ffsll: {
8205     APSInt Val;
8206     if (!EvaluateInteger(E->getArg(0), Val, Info))
8207       return false;
8208 
8209     unsigned N = Val.countTrailingZeros();
8210     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
8211   }
8212 
8213   case Builtin::BI__builtin_fpclassify: {
8214     APFloat Val(0.0);
8215     if (!EvaluateFloat(E->getArg(5), Val, Info))
8216       return false;
8217     unsigned Arg;
8218     switch (Val.getCategory()) {
8219     case APFloat::fcNaN: Arg = 0; break;
8220     case APFloat::fcInfinity: Arg = 1; break;
8221     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
8222     case APFloat::fcZero: Arg = 4; break;
8223     }
8224     return Visit(E->getArg(Arg));
8225   }
8226 
8227   case Builtin::BI__builtin_isinf_sign: {
8228     APFloat Val(0.0);
8229     return EvaluateFloat(E->getArg(0), Val, Info) &&
8230            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
8231   }
8232 
8233   case Builtin::BI__builtin_isinf: {
8234     APFloat Val(0.0);
8235     return EvaluateFloat(E->getArg(0), Val, Info) &&
8236            Success(Val.isInfinity() ? 1 : 0, E);
8237   }
8238 
8239   case Builtin::BI__builtin_isfinite: {
8240     APFloat Val(0.0);
8241     return EvaluateFloat(E->getArg(0), Val, Info) &&
8242            Success(Val.isFinite() ? 1 : 0, E);
8243   }
8244 
8245   case Builtin::BI__builtin_isnan: {
8246     APFloat Val(0.0);
8247     return EvaluateFloat(E->getArg(0), Val, Info) &&
8248            Success(Val.isNaN() ? 1 : 0, E);
8249   }
8250 
8251   case Builtin::BI__builtin_isnormal: {
8252     APFloat Val(0.0);
8253     return EvaluateFloat(E->getArg(0), Val, Info) &&
8254            Success(Val.isNormal() ? 1 : 0, E);
8255   }
8256 
8257   case Builtin::BI__builtin_parity:
8258   case Builtin::BI__builtin_parityl:
8259   case Builtin::BI__builtin_parityll: {
8260     APSInt Val;
8261     if (!EvaluateInteger(E->getArg(0), Val, Info))
8262       return false;
8263 
8264     return Success(Val.countPopulation() % 2, E);
8265   }
8266 
8267   case Builtin::BI__builtin_popcount:
8268   case Builtin::BI__builtin_popcountl:
8269   case Builtin::BI__builtin_popcountll: {
8270     APSInt Val;
8271     if (!EvaluateInteger(E->getArg(0), Val, Info))
8272       return false;
8273 
8274     return Success(Val.countPopulation(), E);
8275   }
8276 
8277   case Builtin::BIstrlen:
8278   case Builtin::BIwcslen:
8279     // A call to strlen is not a constant expression.
8280     if (Info.getLangOpts().CPlusPlus11)
8281       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8282         << /*isConstexpr*/0 << /*isConstructor*/0
8283         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8284     else
8285       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8286     LLVM_FALLTHROUGH;
8287   case Builtin::BI__builtin_strlen:
8288   case Builtin::BI__builtin_wcslen: {
8289     // As an extension, we support __builtin_strlen() as a constant expression,
8290     // and support folding strlen() to a constant.
8291     LValue String;
8292     if (!EvaluatePointer(E->getArg(0), String, Info))
8293       return false;
8294 
8295     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8296 
8297     // Fast path: if it's a string literal, search the string value.
8298     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
8299             String.getLValueBase().dyn_cast<const Expr *>())) {
8300       // The string literal may have embedded null characters. Find the first
8301       // one and truncate there.
8302       StringRef Str = S->getBytes();
8303       int64_t Off = String.Offset.getQuantity();
8304       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
8305           S->getCharByteWidth() == 1 &&
8306           // FIXME: Add fast-path for wchar_t too.
8307           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
8308         Str = Str.substr(Off);
8309 
8310         StringRef::size_type Pos = Str.find(0);
8311         if (Pos != StringRef::npos)
8312           Str = Str.substr(0, Pos);
8313 
8314         return Success(Str.size(), E);
8315       }
8316 
8317       // Fall through to slow path to issue appropriate diagnostic.
8318     }
8319 
8320     // Slow path: scan the bytes of the string looking for the terminating 0.
8321     for (uint64_t Strlen = 0; /**/; ++Strlen) {
8322       APValue Char;
8323       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
8324           !Char.isInt())
8325         return false;
8326       if (!Char.getInt())
8327         return Success(Strlen, E);
8328       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
8329         return false;
8330     }
8331   }
8332 
8333   case Builtin::BIstrcmp:
8334   case Builtin::BIwcscmp:
8335   case Builtin::BIstrncmp:
8336   case Builtin::BIwcsncmp:
8337   case Builtin::BImemcmp:
8338   case Builtin::BIwmemcmp:
8339     // A call to strlen is not a constant expression.
8340     if (Info.getLangOpts().CPlusPlus11)
8341       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
8342         << /*isConstexpr*/0 << /*isConstructor*/0
8343         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
8344     else
8345       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
8346     LLVM_FALLTHROUGH;
8347   case Builtin::BI__builtin_strcmp:
8348   case Builtin::BI__builtin_wcscmp:
8349   case Builtin::BI__builtin_strncmp:
8350   case Builtin::BI__builtin_wcsncmp:
8351   case Builtin::BI__builtin_memcmp:
8352   case Builtin::BI__builtin_wmemcmp: {
8353     LValue String1, String2;
8354     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
8355         !EvaluatePointer(E->getArg(1), String2, Info))
8356       return false;
8357 
8358     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
8359 
8360     uint64_t MaxLength = uint64_t(-1);
8361     if (BuiltinOp != Builtin::BIstrcmp &&
8362         BuiltinOp != Builtin::BIwcscmp &&
8363         BuiltinOp != Builtin::BI__builtin_strcmp &&
8364         BuiltinOp != Builtin::BI__builtin_wcscmp) {
8365       APSInt N;
8366       if (!EvaluateInteger(E->getArg(2), N, Info))
8367         return false;
8368       MaxLength = N.getExtValue();
8369     }
8370     bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
8371                        BuiltinOp != Builtin::BIwmemcmp &&
8372                        BuiltinOp != Builtin::BI__builtin_memcmp &&
8373                        BuiltinOp != Builtin::BI__builtin_wmemcmp);
8374     bool IsWide = BuiltinOp == Builtin::BIwcscmp ||
8375                   BuiltinOp == Builtin::BIwcsncmp ||
8376                   BuiltinOp == Builtin::BIwmemcmp ||
8377                   BuiltinOp == Builtin::BI__builtin_wcscmp ||
8378                   BuiltinOp == Builtin::BI__builtin_wcsncmp ||
8379                   BuiltinOp == Builtin::BI__builtin_wmemcmp;
8380     for (; MaxLength; --MaxLength) {
8381       APValue Char1, Char2;
8382       if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
8383           !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
8384           !Char1.isInt() || !Char2.isInt())
8385         return false;
8386       if (Char1.getInt() != Char2.getInt()) {
8387         if (IsWide) // wmemcmp compares with wchar_t signedness.
8388           return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
8389         // memcmp always compares unsigned chars.
8390         return Success(Char1.getInt().ult(Char2.getInt()) ? -1 : 1, E);
8391       }
8392       if (StopAtNull && !Char1.getInt())
8393         return Success(0, E);
8394       assert(!(StopAtNull && !Char2.getInt()));
8395       if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
8396           !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
8397         return false;
8398     }
8399     // We hit the strncmp / memcmp limit.
8400     return Success(0, E);
8401   }
8402 
8403   case Builtin::BI__atomic_always_lock_free:
8404   case Builtin::BI__atomic_is_lock_free:
8405   case Builtin::BI__c11_atomic_is_lock_free: {
8406     APSInt SizeVal;
8407     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
8408       return false;
8409 
8410     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
8411     // of two less than the maximum inline atomic width, we know it is
8412     // lock-free.  If the size isn't a power of two, or greater than the
8413     // maximum alignment where we promote atomics, we know it is not lock-free
8414     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
8415     // the answer can only be determined at runtime; for example, 16-byte
8416     // atomics have lock-free implementations on some, but not all,
8417     // x86-64 processors.
8418 
8419     // Check power-of-two.
8420     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
8421     if (Size.isPowerOfTwo()) {
8422       // Check against inlining width.
8423       unsigned InlineWidthBits =
8424           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
8425       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
8426         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
8427             Size == CharUnits::One() ||
8428             E->getArg(1)->isNullPointerConstant(Info.Ctx,
8429                                                 Expr::NPC_NeverValueDependent))
8430           // OK, we will inline appropriately-aligned operations of this size,
8431           // and _Atomic(T) is appropriately-aligned.
8432           return Success(1, E);
8433 
8434         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8435           castAs<PointerType>()->getPointeeType();
8436         if (!PointeeType->isIncompleteType() &&
8437             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8438           // OK, we will inline operations on this object.
8439           return Success(1, E);
8440         }
8441       }
8442     }
8443 
8444     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8445         Success(0, E) : Error(E);
8446   }
8447   case Builtin::BIomp_is_initial_device:
8448     // We can decide statically which value the runtime would return if called.
8449     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
8450   case Builtin::BI__builtin_add_overflow:
8451   case Builtin::BI__builtin_sub_overflow:
8452   case Builtin::BI__builtin_mul_overflow:
8453   case Builtin::BI__builtin_sadd_overflow:
8454   case Builtin::BI__builtin_uadd_overflow:
8455   case Builtin::BI__builtin_uaddl_overflow:
8456   case Builtin::BI__builtin_uaddll_overflow:
8457   case Builtin::BI__builtin_usub_overflow:
8458   case Builtin::BI__builtin_usubl_overflow:
8459   case Builtin::BI__builtin_usubll_overflow:
8460   case Builtin::BI__builtin_umul_overflow:
8461   case Builtin::BI__builtin_umull_overflow:
8462   case Builtin::BI__builtin_umulll_overflow:
8463   case Builtin::BI__builtin_saddl_overflow:
8464   case Builtin::BI__builtin_saddll_overflow:
8465   case Builtin::BI__builtin_ssub_overflow:
8466   case Builtin::BI__builtin_ssubl_overflow:
8467   case Builtin::BI__builtin_ssubll_overflow:
8468   case Builtin::BI__builtin_smul_overflow:
8469   case Builtin::BI__builtin_smull_overflow:
8470   case Builtin::BI__builtin_smulll_overflow: {
8471     LValue ResultLValue;
8472     APSInt LHS, RHS;
8473 
8474     QualType ResultType = E->getArg(2)->getType()->getPointeeType();
8475     if (!EvaluateInteger(E->getArg(0), LHS, Info) ||
8476         !EvaluateInteger(E->getArg(1), RHS, Info) ||
8477         !EvaluatePointer(E->getArg(2), ResultLValue, Info))
8478       return false;
8479 
8480     APSInt Result;
8481     bool DidOverflow = false;
8482 
8483     // If the types don't have to match, enlarge all 3 to the largest of them.
8484     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8485         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8486         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8487       bool IsSigned = LHS.isSigned() || RHS.isSigned() ||
8488                       ResultType->isSignedIntegerOrEnumerationType();
8489       bool AllSigned = LHS.isSigned() && RHS.isSigned() &&
8490                       ResultType->isSignedIntegerOrEnumerationType();
8491       uint64_t LHSSize = LHS.getBitWidth();
8492       uint64_t RHSSize = RHS.getBitWidth();
8493       uint64_t ResultSize = Info.Ctx.getTypeSize(ResultType);
8494       uint64_t MaxBits = std::max(std::max(LHSSize, RHSSize), ResultSize);
8495 
8496       // Add an additional bit if the signedness isn't uniformly agreed to. We
8497       // could do this ONLY if there is a signed and an unsigned that both have
8498       // MaxBits, but the code to check that is pretty nasty.  The issue will be
8499       // caught in the shrink-to-result later anyway.
8500       if (IsSigned && !AllSigned)
8501         ++MaxBits;
8502 
8503       LHS = APSInt(IsSigned ? LHS.sextOrSelf(MaxBits) : LHS.zextOrSelf(MaxBits),
8504                    !IsSigned);
8505       RHS = APSInt(IsSigned ? RHS.sextOrSelf(MaxBits) : RHS.zextOrSelf(MaxBits),
8506                    !IsSigned);
8507       Result = APSInt(MaxBits, !IsSigned);
8508     }
8509 
8510     // Find largest int.
8511     switch (BuiltinOp) {
8512     default:
8513       llvm_unreachable("Invalid value for BuiltinOp");
8514     case Builtin::BI__builtin_add_overflow:
8515     case Builtin::BI__builtin_sadd_overflow:
8516     case Builtin::BI__builtin_saddl_overflow:
8517     case Builtin::BI__builtin_saddll_overflow:
8518     case Builtin::BI__builtin_uadd_overflow:
8519     case Builtin::BI__builtin_uaddl_overflow:
8520     case Builtin::BI__builtin_uaddll_overflow:
8521       Result = LHS.isSigned() ? LHS.sadd_ov(RHS, DidOverflow)
8522                               : LHS.uadd_ov(RHS, DidOverflow);
8523       break;
8524     case Builtin::BI__builtin_sub_overflow:
8525     case Builtin::BI__builtin_ssub_overflow:
8526     case Builtin::BI__builtin_ssubl_overflow:
8527     case Builtin::BI__builtin_ssubll_overflow:
8528     case Builtin::BI__builtin_usub_overflow:
8529     case Builtin::BI__builtin_usubl_overflow:
8530     case Builtin::BI__builtin_usubll_overflow:
8531       Result = LHS.isSigned() ? LHS.ssub_ov(RHS, DidOverflow)
8532                               : LHS.usub_ov(RHS, DidOverflow);
8533       break;
8534     case Builtin::BI__builtin_mul_overflow:
8535     case Builtin::BI__builtin_smul_overflow:
8536     case Builtin::BI__builtin_smull_overflow:
8537     case Builtin::BI__builtin_smulll_overflow:
8538     case Builtin::BI__builtin_umul_overflow:
8539     case Builtin::BI__builtin_umull_overflow:
8540     case Builtin::BI__builtin_umulll_overflow:
8541       Result = LHS.isSigned() ? LHS.smul_ov(RHS, DidOverflow)
8542                               : LHS.umul_ov(RHS, DidOverflow);
8543       break;
8544     }
8545 
8546     // In the case where multiple sizes are allowed, truncate and see if
8547     // the values are the same.
8548     if (BuiltinOp == Builtin::BI__builtin_add_overflow ||
8549         BuiltinOp == Builtin::BI__builtin_sub_overflow ||
8550         BuiltinOp == Builtin::BI__builtin_mul_overflow) {
8551       // APSInt doesn't have a TruncOrSelf, so we use extOrTrunc instead,
8552       // since it will give us the behavior of a TruncOrSelf in the case where
8553       // its parameter <= its size.  We previously set Result to be at least the
8554       // type-size of the result, so getTypeSize(ResultType) <= Result.BitWidth
8555       // will work exactly like TruncOrSelf.
8556       APSInt Temp = Result.extOrTrunc(Info.Ctx.getTypeSize(ResultType));
8557       Temp.setIsSigned(ResultType->isSignedIntegerOrEnumerationType());
8558 
8559       if (!APSInt::isSameValue(Temp, Result))
8560         DidOverflow = true;
8561       Result = Temp;
8562     }
8563 
8564     APValue APV{Result};
8565     if (!handleAssignment(Info, E, ResultLValue, ResultType, APV))
8566       return false;
8567     return Success(DidOverflow, E);
8568   }
8569   }
8570 }
8571 
8572 /// Determine whether this is a pointer past the end of the complete
8573 /// object referred to by the lvalue.
8574 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8575                                             const LValue &LV) {
8576   // A null pointer can be viewed as being "past the end" but we don't
8577   // choose to look at it that way here.
8578   if (!LV.getLValueBase())
8579     return false;
8580 
8581   // If the designator is valid and refers to a subobject, we're not pointing
8582   // past the end.
8583   if (!LV.getLValueDesignator().Invalid &&
8584       !LV.getLValueDesignator().isOnePastTheEnd())
8585     return false;
8586 
8587   // A pointer to an incomplete type might be past-the-end if the type's size is
8588   // zero.  We cannot tell because the type is incomplete.
8589   QualType Ty = getType(LV.getLValueBase());
8590   if (Ty->isIncompleteType())
8591     return true;
8592 
8593   // We're a past-the-end pointer if we point to the byte after the object,
8594   // no matter what our type or path is.
8595   auto Size = Ctx.getTypeSizeInChars(Ty);
8596   return LV.getLValueOffset() == Size;
8597 }
8598 
8599 namespace {
8600 
8601 /// Data recursive integer evaluator of certain binary operators.
8602 ///
8603 /// We use a data recursive algorithm for binary operators so that we are able
8604 /// to handle extreme cases of chained binary operators without causing stack
8605 /// overflow.
8606 class DataRecursiveIntBinOpEvaluator {
8607   struct EvalResult {
8608     APValue Val;
8609     bool Failed;
8610 
8611     EvalResult() : Failed(false) { }
8612 
8613     void swap(EvalResult &RHS) {
8614       Val.swap(RHS.Val);
8615       Failed = RHS.Failed;
8616       RHS.Failed = false;
8617     }
8618   };
8619 
8620   struct Job {
8621     const Expr *E;
8622     EvalResult LHSResult; // meaningful only for binary operator expression.
8623     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8624 
8625     Job() = default;
8626     Job(Job &&) = default;
8627 
8628     void startSpeculativeEval(EvalInfo &Info) {
8629       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8630     }
8631 
8632   private:
8633     SpeculativeEvaluationRAII SpecEvalRAII;
8634   };
8635 
8636   SmallVector<Job, 16> Queue;
8637 
8638   IntExprEvaluator &IntEval;
8639   EvalInfo &Info;
8640   APValue &FinalResult;
8641 
8642 public:
8643   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8644     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8645 
8646   /// True if \param E is a binary operator that we are going to handle
8647   /// data recursively.
8648   /// We handle binary operators that are comma, logical, or that have operands
8649   /// with integral or enumeration type.
8650   static bool shouldEnqueue(const BinaryOperator *E) {
8651     return E->getOpcode() == BO_Comma || E->isLogicalOp() ||
8652            (E->isRValue() && E->getType()->isIntegralOrEnumerationType() &&
8653             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8654             E->getRHS()->getType()->isIntegralOrEnumerationType());
8655   }
8656 
8657   bool Traverse(const BinaryOperator *E) {
8658     enqueue(E);
8659     EvalResult PrevResult;
8660     while (!Queue.empty())
8661       process(PrevResult);
8662 
8663     if (PrevResult.Failed) return false;
8664 
8665     FinalResult.swap(PrevResult.Val);
8666     return true;
8667   }
8668 
8669 private:
8670   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8671     return IntEval.Success(Value, E, Result);
8672   }
8673   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8674     return IntEval.Success(Value, E, Result);
8675   }
8676   bool Error(const Expr *E) {
8677     return IntEval.Error(E);
8678   }
8679   bool Error(const Expr *E, diag::kind D) {
8680     return IntEval.Error(E, D);
8681   }
8682 
8683   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8684     return Info.CCEDiag(E, D);
8685   }
8686 
8687   // Returns true if visiting the RHS is necessary, false otherwise.
8688   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8689                          bool &SuppressRHSDiags);
8690 
8691   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8692                   const BinaryOperator *E, APValue &Result);
8693 
8694   void EvaluateExpr(const Expr *E, EvalResult &Result) {
8695     Result.Failed = !Evaluate(Result.Val, Info, E);
8696     if (Result.Failed)
8697       Result.Val = APValue();
8698   }
8699 
8700   void process(EvalResult &Result);
8701 
8702   void enqueue(const Expr *E) {
8703     E = E->IgnoreParens();
8704     Queue.resize(Queue.size()+1);
8705     Queue.back().E = E;
8706     Queue.back().Kind = Job::AnyExprKind;
8707   }
8708 };
8709 
8710 }
8711 
8712 bool DataRecursiveIntBinOpEvaluator::
8713        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8714                          bool &SuppressRHSDiags) {
8715   if (E->getOpcode() == BO_Comma) {
8716     // Ignore LHS but note if we could not evaluate it.
8717     if (LHSResult.Failed)
8718       return Info.noteSideEffect();
8719     return true;
8720   }
8721 
8722   if (E->isLogicalOp()) {
8723     bool LHSAsBool;
8724     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8725       // We were able to evaluate the LHS, see if we can get away with not
8726       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8727       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8728         Success(LHSAsBool, E, LHSResult.Val);
8729         return false; // Ignore RHS
8730       }
8731     } else {
8732       LHSResult.Failed = true;
8733 
8734       // Since we weren't able to evaluate the left hand side, it
8735       // might have had side effects.
8736       if (!Info.noteSideEffect())
8737         return false;
8738 
8739       // We can't evaluate the LHS; however, sometimes the result
8740       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8741       // Don't ignore RHS and suppress diagnostics from this arm.
8742       SuppressRHSDiags = true;
8743     }
8744 
8745     return true;
8746   }
8747 
8748   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8749          E->getRHS()->getType()->isIntegralOrEnumerationType());
8750 
8751   if (LHSResult.Failed && !Info.noteFailure())
8752     return false; // Ignore RHS;
8753 
8754   return true;
8755 }
8756 
8757 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8758                                     bool IsSub) {
8759   // Compute the new offset in the appropriate width, wrapping at 64 bits.
8760   // FIXME: When compiling for a 32-bit target, we should use 32-bit
8761   // offsets.
8762   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8763   CharUnits &Offset = LVal.getLValueOffset();
8764   uint64_t Offset64 = Offset.getQuantity();
8765   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8766   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8767                                          : Offset64 + Index64);
8768 }
8769 
8770 bool DataRecursiveIntBinOpEvaluator::
8771        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8772                   const BinaryOperator *E, APValue &Result) {
8773   if (E->getOpcode() == BO_Comma) {
8774     if (RHSResult.Failed)
8775       return false;
8776     Result = RHSResult.Val;
8777     return true;
8778   }
8779 
8780   if (E->isLogicalOp()) {
8781     bool lhsResult, rhsResult;
8782     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8783     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8784 
8785     if (LHSIsOK) {
8786       if (RHSIsOK) {
8787         if (E->getOpcode() == BO_LOr)
8788           return Success(lhsResult || rhsResult, E, Result);
8789         else
8790           return Success(lhsResult && rhsResult, E, Result);
8791       }
8792     } else {
8793       if (RHSIsOK) {
8794         // We can't evaluate the LHS; however, sometimes the result
8795         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8796         if (rhsResult == (E->getOpcode() == BO_LOr))
8797           return Success(rhsResult, E, Result);
8798       }
8799     }
8800 
8801     return false;
8802   }
8803 
8804   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8805          E->getRHS()->getType()->isIntegralOrEnumerationType());
8806 
8807   if (LHSResult.Failed || RHSResult.Failed)
8808     return false;
8809 
8810   const APValue &LHSVal = LHSResult.Val;
8811   const APValue &RHSVal = RHSResult.Val;
8812 
8813   // Handle cases like (unsigned long)&a + 4.
8814   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8815     Result = LHSVal;
8816     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8817     return true;
8818   }
8819 
8820   // Handle cases like 4 + (unsigned long)&a
8821   if (E->getOpcode() == BO_Add &&
8822       RHSVal.isLValue() && LHSVal.isInt()) {
8823     Result = RHSVal;
8824     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8825     return true;
8826   }
8827 
8828   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8829     // Handle (intptr_t)&&A - (intptr_t)&&B.
8830     if (!LHSVal.getLValueOffset().isZero() ||
8831         !RHSVal.getLValueOffset().isZero())
8832       return false;
8833     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8834     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8835     if (!LHSExpr || !RHSExpr)
8836       return false;
8837     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8838     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8839     if (!LHSAddrExpr || !RHSAddrExpr)
8840       return false;
8841     // Make sure both labels come from the same function.
8842     if (LHSAddrExpr->getLabel()->getDeclContext() !=
8843         RHSAddrExpr->getLabel()->getDeclContext())
8844       return false;
8845     Result = APValue(LHSAddrExpr, RHSAddrExpr);
8846     return true;
8847   }
8848 
8849   // All the remaining cases expect both operands to be an integer
8850   if (!LHSVal.isInt() || !RHSVal.isInt())
8851     return Error(E);
8852 
8853   // Set up the width and signedness manually, in case it can't be deduced
8854   // from the operation we're performing.
8855   // FIXME: Don't do this in the cases where we can deduce it.
8856   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8857                E->getType()->isUnsignedIntegerOrEnumerationType());
8858   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8859                          RHSVal.getInt(), Value))
8860     return false;
8861   return Success(Value, E, Result);
8862 }
8863 
8864 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8865   Job &job = Queue.back();
8866 
8867   switch (job.Kind) {
8868     case Job::AnyExprKind: {
8869       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8870         if (shouldEnqueue(Bop)) {
8871           job.Kind = Job::BinOpKind;
8872           enqueue(Bop->getLHS());
8873           return;
8874         }
8875       }
8876 
8877       EvaluateExpr(job.E, Result);
8878       Queue.pop_back();
8879       return;
8880     }
8881 
8882     case Job::BinOpKind: {
8883       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8884       bool SuppressRHSDiags = false;
8885       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8886         Queue.pop_back();
8887         return;
8888       }
8889       if (SuppressRHSDiags)
8890         job.startSpeculativeEval(Info);
8891       job.LHSResult.swap(Result);
8892       job.Kind = Job::BinOpVisitedLHSKind;
8893       enqueue(Bop->getRHS());
8894       return;
8895     }
8896 
8897     case Job::BinOpVisitedLHSKind: {
8898       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8899       EvalResult RHS;
8900       RHS.swap(Result);
8901       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8902       Queue.pop_back();
8903       return;
8904     }
8905   }
8906 
8907   llvm_unreachable("Invalid Job::Kind!");
8908 }
8909 
8910 namespace {
8911 /// Used when we determine that we should fail, but can keep evaluating prior to
8912 /// noting that we had a failure.
8913 class DelayedNoteFailureRAII {
8914   EvalInfo &Info;
8915   bool NoteFailure;
8916 
8917 public:
8918   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8919       : Info(Info), NoteFailure(NoteFailure) {}
8920   ~DelayedNoteFailureRAII() {
8921     if (NoteFailure) {
8922       bool ContinueAfterFailure = Info.noteFailure();
8923       (void)ContinueAfterFailure;
8924       assert(ContinueAfterFailure &&
8925              "Shouldn't have kept evaluating on failure.");
8926     }
8927   }
8928 };
8929 }
8930 
8931 template <class SuccessCB, class AfterCB>
8932 static bool
8933 EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
8934                                  SuccessCB &&Success, AfterCB &&DoAfter) {
8935   assert(E->isComparisonOp() && "expected comparison operator");
8936   assert((E->getOpcode() == BO_Cmp ||
8937           E->getType()->isIntegralOrEnumerationType()) &&
8938          "unsupported binary expression evaluation");
8939   auto Error = [&](const Expr *E) {
8940     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
8941     return false;
8942   };
8943 
8944   using CCR = ComparisonCategoryResult;
8945   bool IsRelational = E->isRelationalOp();
8946   bool IsEquality = E->isEqualityOp();
8947   if (E->getOpcode() == BO_Cmp) {
8948     const ComparisonCategoryInfo &CmpInfo =
8949         Info.Ctx.CompCategories.getInfoForType(E->getType());
8950     IsRelational = CmpInfo.isOrdered();
8951     IsEquality = CmpInfo.isEquality();
8952   }
8953 
8954   QualType LHSTy = E->getLHS()->getType();
8955   QualType RHSTy = E->getRHS()->getType();
8956 
8957   if (LHSTy->isIntegralOrEnumerationType() &&
8958       RHSTy->isIntegralOrEnumerationType()) {
8959     APSInt LHS, RHS;
8960     bool LHSOK = EvaluateInteger(E->getLHS(), LHS, Info);
8961     if (!LHSOK && !Info.noteFailure())
8962       return false;
8963     if (!EvaluateInteger(E->getRHS(), RHS, Info) || !LHSOK)
8964       return false;
8965     if (LHS < RHS)
8966       return Success(CCR::Less, E);
8967     if (LHS > RHS)
8968       return Success(CCR::Greater, E);
8969     return Success(CCR::Equal, E);
8970   }
8971 
8972   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8973     ComplexValue LHS, RHS;
8974     bool LHSOK;
8975     if (E->isAssignmentOp()) {
8976       LValue LV;
8977       EvaluateLValue(E->getLHS(), LV, Info);
8978       LHSOK = false;
8979     } else if (LHSTy->isRealFloatingType()) {
8980       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8981       if (LHSOK) {
8982         LHS.makeComplexFloat();
8983         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8984       }
8985     } else {
8986       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8987     }
8988     if (!LHSOK && !Info.noteFailure())
8989       return false;
8990 
8991     if (E->getRHS()->getType()->isRealFloatingType()) {
8992       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8993         return false;
8994       RHS.makeComplexFloat();
8995       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8996     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8997       return false;
8998 
8999     if (LHS.isComplexFloat()) {
9000       APFloat::cmpResult CR_r =
9001         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
9002       APFloat::cmpResult CR_i =
9003         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
9004       bool IsEqual = CR_r == APFloat::cmpEqual && CR_i == APFloat::cmpEqual;
9005       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9006     } else {
9007       assert(IsEquality && "invalid complex comparison");
9008       bool IsEqual = LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
9009                      LHS.getComplexIntImag() == RHS.getComplexIntImag();
9010       return Success(IsEqual ? CCR::Equal : CCR::Nonequal, E);
9011     }
9012   }
9013 
9014   if (LHSTy->isRealFloatingType() &&
9015       RHSTy->isRealFloatingType()) {
9016     APFloat RHS(0.0), LHS(0.0);
9017 
9018     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
9019     if (!LHSOK && !Info.noteFailure())
9020       return false;
9021 
9022     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
9023       return false;
9024 
9025     assert(E->isComparisonOp() && "Invalid binary operator!");
9026     auto GetCmpRes = [&]() {
9027       switch (LHS.compare(RHS)) {
9028       case APFloat::cmpEqual:
9029         return CCR::Equal;
9030       case APFloat::cmpLessThan:
9031         return CCR::Less;
9032       case APFloat::cmpGreaterThan:
9033         return CCR::Greater;
9034       case APFloat::cmpUnordered:
9035         return CCR::Unordered;
9036       }
9037       llvm_unreachable("Unrecognised APFloat::cmpResult enum");
9038     };
9039     return Success(GetCmpRes(), E);
9040   }
9041 
9042   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
9043     LValue LHSValue, RHSValue;
9044 
9045     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9046     if (!LHSOK && !Info.noteFailure())
9047       return false;
9048 
9049     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9050       return false;
9051 
9052     // Reject differing bases from the normal codepath; we special-case
9053     // comparisons to null.
9054     if (!HasSameBase(LHSValue, RHSValue)) {
9055       // Inequalities and subtractions between unrelated pointers have
9056       // unspecified or undefined behavior.
9057       if (!IsEquality)
9058         return Error(E);
9059       // A constant address may compare equal to the address of a symbol.
9060       // The one exception is that address of an object cannot compare equal
9061       // to a null pointer constant.
9062       if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
9063           (!RHSValue.Base && !RHSValue.Offset.isZero()))
9064         return Error(E);
9065       // It's implementation-defined whether distinct literals will have
9066       // distinct addresses. In clang, the result of such a comparison is
9067       // unspecified, so it is not a constant expression. However, we do know
9068       // that the address of a literal will be non-null.
9069       if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
9070           LHSValue.Base && RHSValue.Base)
9071         return Error(E);
9072       // We can't tell whether weak symbols will end up pointing to the same
9073       // object.
9074       if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
9075         return Error(E);
9076       // We can't compare the address of the start of one object with the
9077       // past-the-end address of another object, per C++ DR1652.
9078       if ((LHSValue.Base && LHSValue.Offset.isZero() &&
9079            isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
9080           (RHSValue.Base && RHSValue.Offset.isZero() &&
9081            isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
9082         return Error(E);
9083       // We can't tell whether an object is at the same address as another
9084       // zero sized object.
9085       if ((RHSValue.Base && isZeroSized(LHSValue)) ||
9086           (LHSValue.Base && isZeroSized(RHSValue)))
9087         return Error(E);
9088       return Success(CCR::Nonequal, E);
9089     }
9090 
9091     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9092     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9093 
9094     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9095     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9096 
9097     // C++11 [expr.rel]p3:
9098     //   Pointers to void (after pointer conversions) can be compared, with a
9099     //   result defined as follows: If both pointers represent the same
9100     //   address or are both the null pointer value, the result is true if the
9101     //   operator is <= or >= and false otherwise; otherwise the result is
9102     //   unspecified.
9103     // We interpret this as applying to pointers to *cv* void.
9104     if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset && IsRelational)
9105       Info.CCEDiag(E, diag::note_constexpr_void_comparison);
9106 
9107     // C++11 [expr.rel]p2:
9108     // - If two pointers point to non-static data members of the same object,
9109     //   or to subobjects or array elements fo such members, recursively, the
9110     //   pointer to the later declared member compares greater provided the
9111     //   two members have the same access control and provided their class is
9112     //   not a union.
9113     //   [...]
9114     // - Otherwise pointer comparisons are unspecified.
9115     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
9116       bool WasArrayIndex;
9117       unsigned Mismatch = FindDesignatorMismatch(
9118           getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
9119       // At the point where the designators diverge, the comparison has a
9120       // specified value if:
9121       //  - we are comparing array indices
9122       //  - we are comparing fields of a union, or fields with the same access
9123       // Otherwise, the result is unspecified and thus the comparison is not a
9124       // constant expression.
9125       if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
9126           Mismatch < RHSDesignator.Entries.size()) {
9127         const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
9128         const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
9129         if (!LF && !RF)
9130           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
9131         else if (!LF)
9132           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9133               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
9134               << RF->getParent() << RF;
9135         else if (!RF)
9136           Info.CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
9137               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
9138               << LF->getParent() << LF;
9139         else if (!LF->getParent()->isUnion() &&
9140                  LF->getAccess() != RF->getAccess())
9141           Info.CCEDiag(E,
9142                        diag::note_constexpr_pointer_comparison_differing_access)
9143               << LF << LF->getAccess() << RF << RF->getAccess()
9144               << LF->getParent();
9145       }
9146     }
9147 
9148     // The comparison here must be unsigned, and performed with the same
9149     // width as the pointer.
9150     unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
9151     uint64_t CompareLHS = LHSOffset.getQuantity();
9152     uint64_t CompareRHS = RHSOffset.getQuantity();
9153     assert(PtrSize <= 64 && "Unexpected pointer width");
9154     uint64_t Mask = ~0ULL >> (64 - PtrSize);
9155     CompareLHS &= Mask;
9156     CompareRHS &= Mask;
9157 
9158     // If there is a base and this is a relational operator, we can only
9159     // compare pointers within the object in question; otherwise, the result
9160     // depends on where the object is located in memory.
9161     if (!LHSValue.Base.isNull() && IsRelational) {
9162       QualType BaseTy = getType(LHSValue.Base);
9163       if (BaseTy->isIncompleteType())
9164         return Error(E);
9165       CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
9166       uint64_t OffsetLimit = Size.getQuantity();
9167       if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
9168         return Error(E);
9169     }
9170 
9171     if (CompareLHS < CompareRHS)
9172       return Success(CCR::Less, E);
9173     if (CompareLHS > CompareRHS)
9174       return Success(CCR::Greater, E);
9175     return Success(CCR::Equal, E);
9176   }
9177 
9178   if (LHSTy->isMemberPointerType()) {
9179     assert(IsEquality && "unexpected member pointer operation");
9180     assert(RHSTy->isMemberPointerType() && "invalid comparison");
9181 
9182     MemberPtr LHSValue, RHSValue;
9183 
9184     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
9185     if (!LHSOK && !Info.noteFailure())
9186       return false;
9187 
9188     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9189       return false;
9190 
9191     // C++11 [expr.eq]p2:
9192     //   If both operands are null, they compare equal. Otherwise if only one is
9193     //   null, they compare unequal.
9194     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
9195       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
9196       return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9197     }
9198 
9199     //   Otherwise if either is a pointer to a virtual member function, the
9200     //   result is unspecified.
9201     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
9202       if (MD->isVirtual())
9203         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9204     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
9205       if (MD->isVirtual())
9206         Info.CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
9207 
9208     //   Otherwise they compare equal if and only if they would refer to the
9209     //   same member of the same most derived object or the same subobject if
9210     //   they were dereferenced with a hypothetical object of the associated
9211     //   class type.
9212     bool Equal = LHSValue == RHSValue;
9213     return Success(Equal ? CCR::Equal : CCR::Nonequal, E);
9214   }
9215 
9216   if (LHSTy->isNullPtrType()) {
9217     assert(E->isComparisonOp() && "unexpected nullptr operation");
9218     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
9219     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
9220     // are compared, the result is true of the operator is <=, >= or ==, and
9221     // false otherwise.
9222     return Success(CCR::Equal, E);
9223   }
9224 
9225   return DoAfter();
9226 }
9227 
9228 bool RecordExprEvaluator::VisitBinCmp(const BinaryOperator *E) {
9229   if (!CheckLiteralType(Info, E))
9230     return false;
9231 
9232   auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9233                        const BinaryOperator *E) {
9234     // Evaluation succeeded. Lookup the information for the comparison category
9235     // type and fetch the VarDecl for the result.
9236     const ComparisonCategoryInfo &CmpInfo =
9237         Info.Ctx.CompCategories.getInfoForType(E->getType());
9238     const VarDecl *VD =
9239         CmpInfo.getValueInfo(CmpInfo.makeWeakResult(ResKind))->VD;
9240     // Check and evaluate the result as a constant expression.
9241     LValue LV;
9242     LV.set(VD);
9243     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
9244       return false;
9245     return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
9246   };
9247   return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9248     return ExprEvaluatorBaseTy::VisitBinCmp(E);
9249   });
9250 }
9251 
9252 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9253   // We don't call noteFailure immediately because the assignment happens after
9254   // we evaluate LHS and RHS.
9255   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
9256     return Error(E);
9257 
9258   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
9259   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
9260     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
9261 
9262   assert((!E->getLHS()->getType()->isIntegralOrEnumerationType() ||
9263           !E->getRHS()->getType()->isIntegralOrEnumerationType()) &&
9264          "DataRecursiveIntBinOpEvaluator should have handled integral types");
9265 
9266   if (E->isComparisonOp()) {
9267     // Evaluate builtin binary comparisons by evaluating them as C++2a three-way
9268     // comparisons and then translating the result.
9269     auto OnSuccess = [&](ComparisonCategoryResult ResKind,
9270                          const BinaryOperator *E) {
9271       using CCR = ComparisonCategoryResult;
9272       bool IsEqual   = ResKind == CCR::Equal,
9273            IsLess    = ResKind == CCR::Less,
9274            IsGreater = ResKind == CCR::Greater;
9275       auto Op = E->getOpcode();
9276       switch (Op) {
9277       default:
9278         llvm_unreachable("unsupported binary operator");
9279       case BO_EQ:
9280       case BO_NE:
9281         return Success(IsEqual == (Op == BO_EQ), E);
9282       case BO_LT: return Success(IsLess, E);
9283       case BO_GT: return Success(IsGreater, E);
9284       case BO_LE: return Success(IsEqual || IsLess, E);
9285       case BO_GE: return Success(IsEqual || IsGreater, E);
9286       }
9287     };
9288     return EvaluateComparisonBinaryOperator(Info, E, OnSuccess, [&]() {
9289       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9290     });
9291   }
9292 
9293   QualType LHSTy = E->getLHS()->getType();
9294   QualType RHSTy = E->getRHS()->getType();
9295 
9296   if (LHSTy->isPointerType() && RHSTy->isPointerType() &&
9297       E->getOpcode() == BO_Sub) {
9298     LValue LHSValue, RHSValue;
9299 
9300     bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
9301     if (!LHSOK && !Info.noteFailure())
9302       return false;
9303 
9304     if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
9305       return false;
9306 
9307     // Reject differing bases from the normal codepath; we special-case
9308     // comparisons to null.
9309     if (!HasSameBase(LHSValue, RHSValue)) {
9310       // Handle &&A - &&B.
9311       if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
9312         return Error(E);
9313       const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr *>();
9314       const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr *>();
9315       if (!LHSExpr || !RHSExpr)
9316         return Error(E);
9317       const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
9318       const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
9319       if (!LHSAddrExpr || !RHSAddrExpr)
9320         return Error(E);
9321       // Make sure both labels come from the same function.
9322       if (LHSAddrExpr->getLabel()->getDeclContext() !=
9323           RHSAddrExpr->getLabel()->getDeclContext())
9324         return Error(E);
9325       return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
9326     }
9327     const CharUnits &LHSOffset = LHSValue.getLValueOffset();
9328     const CharUnits &RHSOffset = RHSValue.getLValueOffset();
9329 
9330     SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
9331     SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
9332 
9333     // C++11 [expr.add]p6:
9334     //   Unless both pointers point to elements of the same array object, or
9335     //   one past the last element of the array object, the behavior is
9336     //   undefined.
9337     if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
9338         !AreElementsOfSameArray(getType(LHSValue.Base), LHSDesignator,
9339                                 RHSDesignator))
9340       Info.CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
9341 
9342     QualType Type = E->getLHS()->getType();
9343     QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
9344 
9345     CharUnits ElementSize;
9346     if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
9347       return false;
9348 
9349     // As an extension, a type may have zero size (empty struct or union in
9350     // C, array of zero length). Pointer subtraction in such cases has
9351     // undefined behavior, so is not constant.
9352     if (ElementSize.isZero()) {
9353       Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
9354           << ElementType;
9355       return false;
9356     }
9357 
9358     // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
9359     // and produce incorrect results when it overflows. Such behavior
9360     // appears to be non-conforming, but is common, so perhaps we should
9361     // assume the standard intended for such cases to be undefined behavior
9362     // and check for them.
9363 
9364     // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
9365     // overflow in the final conversion to ptrdiff_t.
9366     APSInt LHS(llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
9367     APSInt RHS(llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
9368     APSInt ElemSize(llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true),
9369                     false);
9370     APSInt TrueResult = (LHS - RHS) / ElemSize;
9371     APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
9372 
9373     if (Result.extend(65) != TrueResult &&
9374         !HandleOverflow(Info, E, TrueResult, E->getType()))
9375       return false;
9376     return Success(Result, E);
9377   }
9378 
9379   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9380 }
9381 
9382 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
9383 /// a result as the expression's type.
9384 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
9385                                     const UnaryExprOrTypeTraitExpr *E) {
9386   switch(E->getKind()) {
9387   case UETT_PreferredAlignOf:
9388   case UETT_AlignOf: {
9389     if (E->isArgumentType())
9390       return Success(GetAlignOfType(Info, E->getArgumentType(), E->getKind()),
9391                      E);
9392     else
9393       return Success(GetAlignOfExpr(Info, E->getArgumentExpr(), E->getKind()),
9394                      E);
9395   }
9396 
9397   case UETT_VecStep: {
9398     QualType Ty = E->getTypeOfArgument();
9399 
9400     if (Ty->isVectorType()) {
9401       unsigned n = Ty->castAs<VectorType>()->getNumElements();
9402 
9403       // The vec_step built-in functions that take a 3-component
9404       // vector return 4. (OpenCL 1.1 spec 6.11.12)
9405       if (n == 3)
9406         n = 4;
9407 
9408       return Success(n, E);
9409     } else
9410       return Success(1, E);
9411   }
9412 
9413   case UETT_SizeOf: {
9414     QualType SrcTy = E->getTypeOfArgument();
9415     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
9416     //   the result is the size of the referenced type."
9417     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
9418       SrcTy = Ref->getPointeeType();
9419 
9420     CharUnits Sizeof;
9421     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
9422       return false;
9423     return Success(Sizeof, E);
9424   }
9425   case UETT_OpenMPRequiredSimdAlign:
9426     assert(E->isArgumentType());
9427     return Success(
9428         Info.Ctx.toCharUnitsFromBits(
9429                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
9430             .getQuantity(),
9431         E);
9432   }
9433 
9434   llvm_unreachable("unknown expr/type trait");
9435 }
9436 
9437 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
9438   CharUnits Result;
9439   unsigned n = OOE->getNumComponents();
9440   if (n == 0)
9441     return Error(OOE);
9442   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
9443   for (unsigned i = 0; i != n; ++i) {
9444     OffsetOfNode ON = OOE->getComponent(i);
9445     switch (ON.getKind()) {
9446     case OffsetOfNode::Array: {
9447       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
9448       APSInt IdxResult;
9449       if (!EvaluateInteger(Idx, IdxResult, Info))
9450         return false;
9451       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
9452       if (!AT)
9453         return Error(OOE);
9454       CurrentType = AT->getElementType();
9455       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
9456       Result += IdxResult.getSExtValue() * ElementSize;
9457       break;
9458     }
9459 
9460     case OffsetOfNode::Field: {
9461       FieldDecl *MemberDecl = ON.getField();
9462       const RecordType *RT = CurrentType->getAs<RecordType>();
9463       if (!RT)
9464         return Error(OOE);
9465       RecordDecl *RD = RT->getDecl();
9466       if (RD->isInvalidDecl()) return false;
9467       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9468       unsigned i = MemberDecl->getFieldIndex();
9469       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
9470       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
9471       CurrentType = MemberDecl->getType().getNonReferenceType();
9472       break;
9473     }
9474 
9475     case OffsetOfNode::Identifier:
9476       llvm_unreachable("dependent __builtin_offsetof");
9477 
9478     case OffsetOfNode::Base: {
9479       CXXBaseSpecifier *BaseSpec = ON.getBase();
9480       if (BaseSpec->isVirtual())
9481         return Error(OOE);
9482 
9483       // Find the layout of the class whose base we are looking into.
9484       const RecordType *RT = CurrentType->getAs<RecordType>();
9485       if (!RT)
9486         return Error(OOE);
9487       RecordDecl *RD = RT->getDecl();
9488       if (RD->isInvalidDecl()) return false;
9489       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
9490 
9491       // Find the base class itself.
9492       CurrentType = BaseSpec->getType();
9493       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
9494       if (!BaseRT)
9495         return Error(OOE);
9496 
9497       // Add the offset to the base.
9498       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
9499       break;
9500     }
9501     }
9502   }
9503   return Success(Result, OOE);
9504 }
9505 
9506 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9507   switch (E->getOpcode()) {
9508   default:
9509     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
9510     // See C99 6.6p3.
9511     return Error(E);
9512   case UO_Extension:
9513     // FIXME: Should extension allow i-c-e extension expressions in its scope?
9514     // If so, we could clear the diagnostic ID.
9515     return Visit(E->getSubExpr());
9516   case UO_Plus:
9517     // The result is just the value.
9518     return Visit(E->getSubExpr());
9519   case UO_Minus: {
9520     if (!Visit(E->getSubExpr()))
9521       return false;
9522     if (!Result.isInt()) return Error(E);
9523     const APSInt &Value = Result.getInt();
9524     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
9525         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
9526                         E->getType()))
9527       return false;
9528     return Success(-Value, E);
9529   }
9530   case UO_Not: {
9531     if (!Visit(E->getSubExpr()))
9532       return false;
9533     if (!Result.isInt()) return Error(E);
9534     return Success(~Result.getInt(), E);
9535   }
9536   case UO_LNot: {
9537     bool bres;
9538     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9539       return false;
9540     return Success(!bres, E);
9541   }
9542   }
9543 }
9544 
9545 /// HandleCast - This is used to evaluate implicit or explicit casts where the
9546 /// result type is integer.
9547 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
9548   const Expr *SubExpr = E->getSubExpr();
9549   QualType DestType = E->getType();
9550   QualType SrcType = SubExpr->getType();
9551 
9552   switch (E->getCastKind()) {
9553   case CK_BaseToDerived:
9554   case CK_DerivedToBase:
9555   case CK_UncheckedDerivedToBase:
9556   case CK_Dynamic:
9557   case CK_ToUnion:
9558   case CK_ArrayToPointerDecay:
9559   case CK_FunctionToPointerDecay:
9560   case CK_NullToPointer:
9561   case CK_NullToMemberPointer:
9562   case CK_BaseToDerivedMemberPointer:
9563   case CK_DerivedToBaseMemberPointer:
9564   case CK_ReinterpretMemberPointer:
9565   case CK_ConstructorConversion:
9566   case CK_IntegralToPointer:
9567   case CK_ToVoid:
9568   case CK_VectorSplat:
9569   case CK_IntegralToFloating:
9570   case CK_FloatingCast:
9571   case CK_CPointerToObjCPointerCast:
9572   case CK_BlockPointerToObjCPointerCast:
9573   case CK_AnyPointerToBlockPointerCast:
9574   case CK_ObjCObjectLValueCast:
9575   case CK_FloatingRealToComplex:
9576   case CK_FloatingComplexToReal:
9577   case CK_FloatingComplexCast:
9578   case CK_FloatingComplexToIntegralComplex:
9579   case CK_IntegralRealToComplex:
9580   case CK_IntegralComplexCast:
9581   case CK_IntegralComplexToFloatingComplex:
9582   case CK_BuiltinFnToFnPtr:
9583   case CK_ZeroToOCLOpaqueType:
9584   case CK_NonAtomicToAtomic:
9585   case CK_AddressSpaceConversion:
9586   case CK_IntToOCLSampler:
9587   case CK_FixedPointCast:
9588     llvm_unreachable("invalid cast kind for integral value");
9589 
9590   case CK_BitCast:
9591   case CK_Dependent:
9592   case CK_LValueBitCast:
9593   case CK_ARCProduceObject:
9594   case CK_ARCConsumeObject:
9595   case CK_ARCReclaimReturnedObject:
9596   case CK_ARCExtendBlockObject:
9597   case CK_CopyAndAutoreleaseBlockObject:
9598     return Error(E);
9599 
9600   case CK_UserDefinedConversion:
9601   case CK_LValueToRValue:
9602   case CK_AtomicToNonAtomic:
9603   case CK_NoOp:
9604     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9605 
9606   case CK_MemberPointerToBoolean:
9607   case CK_PointerToBoolean:
9608   case CK_IntegralToBoolean:
9609   case CK_FloatingToBoolean:
9610   case CK_BooleanToSignedIntegral:
9611   case CK_FloatingComplexToBoolean:
9612   case CK_IntegralComplexToBoolean: {
9613     bool BoolResult;
9614     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
9615       return false;
9616     uint64_t IntResult = BoolResult;
9617     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9618       IntResult = (uint64_t)-1;
9619     return Success(IntResult, E);
9620   }
9621 
9622   case CK_FixedPointToBoolean: {
9623     // Unsigned padding does not affect this.
9624     APValue Val;
9625     if (!Evaluate(Val, Info, SubExpr))
9626       return false;
9627     return Success(Val.getInt().getBoolValue(), E);
9628   }
9629 
9630   case CK_IntegralCast: {
9631     if (!Visit(SubExpr))
9632       return false;
9633 
9634     if (!Result.isInt()) {
9635       // Allow casts of address-of-label differences if they are no-ops
9636       // or narrowing.  (The narrowing case isn't actually guaranteed to
9637       // be constant-evaluatable except in some narrow cases which are hard
9638       // to detect here.  We let it through on the assumption the user knows
9639       // what they are doing.)
9640       if (Result.isAddrLabelDiff())
9641         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
9642       // Only allow casts of lvalues if they are lossless.
9643       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9644     }
9645 
9646     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9647                                       Result.getInt()), E);
9648   }
9649 
9650   case CK_PointerToIntegral: {
9651     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9652 
9653     LValue LV;
9654     if (!EvaluatePointer(SubExpr, LV, Info))
9655       return false;
9656 
9657     if (LV.getLValueBase()) {
9658       // Only allow based lvalue casts if they are lossless.
9659       // FIXME: Allow a larger integer size than the pointer size, and allow
9660       // narrowing back down to pointer width in subsequent integral casts.
9661       // FIXME: Check integer type's active bits, not its type size.
9662       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9663         return Error(E);
9664 
9665       LV.Designator.setInvalid();
9666       LV.moveInto(Result);
9667       return true;
9668     }
9669 
9670     uint64_t V;
9671     if (LV.isNullPointer())
9672       V = Info.Ctx.getTargetNullPointerValue(SrcType);
9673     else
9674       V = LV.getLValueOffset().getQuantity();
9675 
9676     APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9677     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9678   }
9679 
9680   case CK_IntegralComplexToReal: {
9681     ComplexValue C;
9682     if (!EvaluateComplex(SubExpr, C, Info))
9683       return false;
9684     return Success(C.getComplexIntReal(), E);
9685   }
9686 
9687   case CK_FloatingToIntegral: {
9688     APFloat F(0.0);
9689     if (!EvaluateFloat(SubExpr, F, Info))
9690       return false;
9691 
9692     APSInt Value;
9693     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9694       return false;
9695     return Success(Value, E);
9696   }
9697   }
9698 
9699   llvm_unreachable("unknown cast resulting in integral value");
9700 }
9701 
9702 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9703   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9704     ComplexValue LV;
9705     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9706       return false;
9707     if (!LV.isComplexInt())
9708       return Error(E);
9709     return Success(LV.getComplexIntReal(), E);
9710   }
9711 
9712   return Visit(E->getSubExpr());
9713 }
9714 
9715 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9716   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9717     ComplexValue LV;
9718     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9719       return false;
9720     if (!LV.isComplexInt())
9721       return Error(E);
9722     return Success(LV.getComplexIntImag(), E);
9723   }
9724 
9725   VisitIgnoredValue(E->getSubExpr());
9726   return Success(0, E);
9727 }
9728 
9729 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9730   return Success(E->getPackLength(), E);
9731 }
9732 
9733 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9734   return Success(E->getValue(), E);
9735 }
9736 
9737 bool FixedPointExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9738   switch (E->getOpcode()) {
9739     default:
9740       // Invalid unary operators
9741       return Error(E);
9742     case UO_Plus:
9743       // The result is just the value.
9744       return Visit(E->getSubExpr());
9745     case UO_Minus: {
9746       if (!Visit(E->getSubExpr())) return false;
9747       if (!Result.isInt()) return Error(E);
9748       const APSInt &Value = Result.getInt();
9749       if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow()) {
9750         SmallString<64> S;
9751         FixedPointValueToString(S, Value,
9752                                 Info.Ctx.getTypeInfo(E->getType()).Width);
9753         Info.CCEDiag(E, diag::note_constexpr_overflow) << S << E->getType();
9754         if (Info.noteUndefinedBehavior()) return false;
9755       }
9756       return Success(-Value, E);
9757     }
9758     case UO_LNot: {
9759       bool bres;
9760       if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
9761         return false;
9762       return Success(!bres, E);
9763     }
9764   }
9765 }
9766 
9767 //===----------------------------------------------------------------------===//
9768 // Float Evaluation
9769 //===----------------------------------------------------------------------===//
9770 
9771 namespace {
9772 class FloatExprEvaluator
9773   : public ExprEvaluatorBase<FloatExprEvaluator> {
9774   APFloat &Result;
9775 public:
9776   FloatExprEvaluator(EvalInfo &info, APFloat &result)
9777     : ExprEvaluatorBaseTy(info), Result(result) {}
9778 
9779   bool Success(const APValue &V, const Expr *e) {
9780     Result = V.getFloat();
9781     return true;
9782   }
9783 
9784   bool ZeroInitialization(const Expr *E) {
9785     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9786     return true;
9787   }
9788 
9789   bool VisitCallExpr(const CallExpr *E);
9790 
9791   bool VisitUnaryOperator(const UnaryOperator *E);
9792   bool VisitBinaryOperator(const BinaryOperator *E);
9793   bool VisitFloatingLiteral(const FloatingLiteral *E);
9794   bool VisitCastExpr(const CastExpr *E);
9795 
9796   bool VisitUnaryReal(const UnaryOperator *E);
9797   bool VisitUnaryImag(const UnaryOperator *E);
9798 
9799   // FIXME: Missing: array subscript of vector, member of vector
9800 };
9801 } // end anonymous namespace
9802 
9803 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9804   assert(E->isRValue() && E->getType()->isRealFloatingType());
9805   return FloatExprEvaluator(Info, Result).Visit(E);
9806 }
9807 
9808 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9809                                   QualType ResultTy,
9810                                   const Expr *Arg,
9811                                   bool SNaN,
9812                                   llvm::APFloat &Result) {
9813   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9814   if (!S) return false;
9815 
9816   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9817 
9818   llvm::APInt fill;
9819 
9820   // Treat empty strings as if they were zero.
9821   if (S->getString().empty())
9822     fill = llvm::APInt(32, 0);
9823   else if (S->getString().getAsInteger(0, fill))
9824     return false;
9825 
9826   if (Context.getTargetInfo().isNan2008()) {
9827     if (SNaN)
9828       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9829     else
9830       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9831   } else {
9832     // Prior to IEEE 754-2008, architectures were allowed to choose whether
9833     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9834     // a different encoding to what became a standard in 2008, and for pre-
9835     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9836     // sNaN. This is now known as "legacy NaN" encoding.
9837     if (SNaN)
9838       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9839     else
9840       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9841   }
9842 
9843   return true;
9844 }
9845 
9846 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9847   switch (E->getBuiltinCallee()) {
9848   default:
9849     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9850 
9851   case Builtin::BI__builtin_huge_val:
9852   case Builtin::BI__builtin_huge_valf:
9853   case Builtin::BI__builtin_huge_vall:
9854   case Builtin::BI__builtin_huge_valf128:
9855   case Builtin::BI__builtin_inf:
9856   case Builtin::BI__builtin_inff:
9857   case Builtin::BI__builtin_infl:
9858   case Builtin::BI__builtin_inff128: {
9859     const llvm::fltSemantics &Sem =
9860       Info.Ctx.getFloatTypeSemantics(E->getType());
9861     Result = llvm::APFloat::getInf(Sem);
9862     return true;
9863   }
9864 
9865   case Builtin::BI__builtin_nans:
9866   case Builtin::BI__builtin_nansf:
9867   case Builtin::BI__builtin_nansl:
9868   case Builtin::BI__builtin_nansf128:
9869     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9870                                true, Result))
9871       return Error(E);
9872     return true;
9873 
9874   case Builtin::BI__builtin_nan:
9875   case Builtin::BI__builtin_nanf:
9876   case Builtin::BI__builtin_nanl:
9877   case Builtin::BI__builtin_nanf128:
9878     // If this is __builtin_nan() turn this into a nan, otherwise we
9879     // can't constant fold it.
9880     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9881                                false, Result))
9882       return Error(E);
9883     return true;
9884 
9885   case Builtin::BI__builtin_fabs:
9886   case Builtin::BI__builtin_fabsf:
9887   case Builtin::BI__builtin_fabsl:
9888   case Builtin::BI__builtin_fabsf128:
9889     if (!EvaluateFloat(E->getArg(0), Result, Info))
9890       return false;
9891 
9892     if (Result.isNegative())
9893       Result.changeSign();
9894     return true;
9895 
9896   // FIXME: Builtin::BI__builtin_powi
9897   // FIXME: Builtin::BI__builtin_powif
9898   // FIXME: Builtin::BI__builtin_powil
9899 
9900   case Builtin::BI__builtin_copysign:
9901   case Builtin::BI__builtin_copysignf:
9902   case Builtin::BI__builtin_copysignl:
9903   case Builtin::BI__builtin_copysignf128: {
9904     APFloat RHS(0.);
9905     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9906         !EvaluateFloat(E->getArg(1), RHS, Info))
9907       return false;
9908     Result.copySign(RHS);
9909     return true;
9910   }
9911   }
9912 }
9913 
9914 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9915   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9916     ComplexValue CV;
9917     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9918       return false;
9919     Result = CV.FloatReal;
9920     return true;
9921   }
9922 
9923   return Visit(E->getSubExpr());
9924 }
9925 
9926 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9927   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9928     ComplexValue CV;
9929     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9930       return false;
9931     Result = CV.FloatImag;
9932     return true;
9933   }
9934 
9935   VisitIgnoredValue(E->getSubExpr());
9936   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9937   Result = llvm::APFloat::getZero(Sem);
9938   return true;
9939 }
9940 
9941 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9942   switch (E->getOpcode()) {
9943   default: return Error(E);
9944   case UO_Plus:
9945     return EvaluateFloat(E->getSubExpr(), Result, Info);
9946   case UO_Minus:
9947     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9948       return false;
9949     Result.changeSign();
9950     return true;
9951   }
9952 }
9953 
9954 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9955   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9956     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9957 
9958   APFloat RHS(0.0);
9959   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9960   if (!LHSOK && !Info.noteFailure())
9961     return false;
9962   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9963          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9964 }
9965 
9966 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9967   Result = E->getValue();
9968   return true;
9969 }
9970 
9971 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9972   const Expr* SubExpr = E->getSubExpr();
9973 
9974   switch (E->getCastKind()) {
9975   default:
9976     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9977 
9978   case CK_IntegralToFloating: {
9979     APSInt IntResult;
9980     return EvaluateInteger(SubExpr, IntResult, Info) &&
9981            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9982                                 E->getType(), Result);
9983   }
9984 
9985   case CK_FloatingCast: {
9986     if (!Visit(SubExpr))
9987       return false;
9988     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9989                                   Result);
9990   }
9991 
9992   case CK_FloatingComplexToReal: {
9993     ComplexValue V;
9994     if (!EvaluateComplex(SubExpr, V, Info))
9995       return false;
9996     Result = V.getComplexFloatReal();
9997     return true;
9998   }
9999   }
10000 }
10001 
10002 //===----------------------------------------------------------------------===//
10003 // Complex Evaluation (for float and integer)
10004 //===----------------------------------------------------------------------===//
10005 
10006 namespace {
10007 class ComplexExprEvaluator
10008   : public ExprEvaluatorBase<ComplexExprEvaluator> {
10009   ComplexValue &Result;
10010 
10011 public:
10012   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
10013     : ExprEvaluatorBaseTy(info), Result(Result) {}
10014 
10015   bool Success(const APValue &V, const Expr *e) {
10016     Result.setFrom(V);
10017     return true;
10018   }
10019 
10020   bool ZeroInitialization(const Expr *E);
10021 
10022   //===--------------------------------------------------------------------===//
10023   //                            Visitor Methods
10024   //===--------------------------------------------------------------------===//
10025 
10026   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
10027   bool VisitCastExpr(const CastExpr *E);
10028   bool VisitBinaryOperator(const BinaryOperator *E);
10029   bool VisitUnaryOperator(const UnaryOperator *E);
10030   bool VisitInitListExpr(const InitListExpr *E);
10031 };
10032 } // end anonymous namespace
10033 
10034 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
10035                             EvalInfo &Info) {
10036   assert(E->isRValue() && E->getType()->isAnyComplexType());
10037   return ComplexExprEvaluator(Info, Result).Visit(E);
10038 }
10039 
10040 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
10041   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
10042   if (ElemTy->isRealFloatingType()) {
10043     Result.makeComplexFloat();
10044     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
10045     Result.FloatReal = Zero;
10046     Result.FloatImag = Zero;
10047   } else {
10048     Result.makeComplexInt();
10049     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
10050     Result.IntReal = Zero;
10051     Result.IntImag = Zero;
10052   }
10053   return true;
10054 }
10055 
10056 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
10057   const Expr* SubExpr = E->getSubExpr();
10058 
10059   if (SubExpr->getType()->isRealFloatingType()) {
10060     Result.makeComplexFloat();
10061     APFloat &Imag = Result.FloatImag;
10062     if (!EvaluateFloat(SubExpr, Imag, Info))
10063       return false;
10064 
10065     Result.FloatReal = APFloat(Imag.getSemantics());
10066     return true;
10067   } else {
10068     assert(SubExpr->getType()->isIntegerType() &&
10069            "Unexpected imaginary literal.");
10070 
10071     Result.makeComplexInt();
10072     APSInt &Imag = Result.IntImag;
10073     if (!EvaluateInteger(SubExpr, Imag, Info))
10074       return false;
10075 
10076     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
10077     return true;
10078   }
10079 }
10080 
10081 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
10082 
10083   switch (E->getCastKind()) {
10084   case CK_BitCast:
10085   case CK_BaseToDerived:
10086   case CK_DerivedToBase:
10087   case CK_UncheckedDerivedToBase:
10088   case CK_Dynamic:
10089   case CK_ToUnion:
10090   case CK_ArrayToPointerDecay:
10091   case CK_FunctionToPointerDecay:
10092   case CK_NullToPointer:
10093   case CK_NullToMemberPointer:
10094   case CK_BaseToDerivedMemberPointer:
10095   case CK_DerivedToBaseMemberPointer:
10096   case CK_MemberPointerToBoolean:
10097   case CK_ReinterpretMemberPointer:
10098   case CK_ConstructorConversion:
10099   case CK_IntegralToPointer:
10100   case CK_PointerToIntegral:
10101   case CK_PointerToBoolean:
10102   case CK_ToVoid:
10103   case CK_VectorSplat:
10104   case CK_IntegralCast:
10105   case CK_BooleanToSignedIntegral:
10106   case CK_IntegralToBoolean:
10107   case CK_IntegralToFloating:
10108   case CK_FloatingToIntegral:
10109   case CK_FloatingToBoolean:
10110   case CK_FloatingCast:
10111   case CK_CPointerToObjCPointerCast:
10112   case CK_BlockPointerToObjCPointerCast:
10113   case CK_AnyPointerToBlockPointerCast:
10114   case CK_ObjCObjectLValueCast:
10115   case CK_FloatingComplexToReal:
10116   case CK_FloatingComplexToBoolean:
10117   case CK_IntegralComplexToReal:
10118   case CK_IntegralComplexToBoolean:
10119   case CK_ARCProduceObject:
10120   case CK_ARCConsumeObject:
10121   case CK_ARCReclaimReturnedObject:
10122   case CK_ARCExtendBlockObject:
10123   case CK_CopyAndAutoreleaseBlockObject:
10124   case CK_BuiltinFnToFnPtr:
10125   case CK_ZeroToOCLOpaqueType:
10126   case CK_NonAtomicToAtomic:
10127   case CK_AddressSpaceConversion:
10128   case CK_IntToOCLSampler:
10129   case CK_FixedPointCast:
10130   case CK_FixedPointToBoolean:
10131     llvm_unreachable("invalid cast kind for complex value");
10132 
10133   case CK_LValueToRValue:
10134   case CK_AtomicToNonAtomic:
10135   case CK_NoOp:
10136     return ExprEvaluatorBaseTy::VisitCastExpr(E);
10137 
10138   case CK_Dependent:
10139   case CK_LValueBitCast:
10140   case CK_UserDefinedConversion:
10141     return Error(E);
10142 
10143   case CK_FloatingRealToComplex: {
10144     APFloat &Real = Result.FloatReal;
10145     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
10146       return false;
10147 
10148     Result.makeComplexFloat();
10149     Result.FloatImag = APFloat(Real.getSemantics());
10150     return true;
10151   }
10152 
10153   case CK_FloatingComplexCast: {
10154     if (!Visit(E->getSubExpr()))
10155       return false;
10156 
10157     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10158     QualType From
10159       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10160 
10161     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
10162            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
10163   }
10164 
10165   case CK_FloatingComplexToIntegralComplex: {
10166     if (!Visit(E->getSubExpr()))
10167       return false;
10168 
10169     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10170     QualType From
10171       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10172     Result.makeComplexInt();
10173     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
10174                                 To, Result.IntReal) &&
10175            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
10176                                 To, Result.IntImag);
10177   }
10178 
10179   case CK_IntegralRealToComplex: {
10180     APSInt &Real = Result.IntReal;
10181     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
10182       return false;
10183 
10184     Result.makeComplexInt();
10185     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
10186     return true;
10187   }
10188 
10189   case CK_IntegralComplexCast: {
10190     if (!Visit(E->getSubExpr()))
10191       return false;
10192 
10193     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
10194     QualType From
10195       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
10196 
10197     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
10198     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
10199     return true;
10200   }
10201 
10202   case CK_IntegralComplexToFloatingComplex: {
10203     if (!Visit(E->getSubExpr()))
10204       return false;
10205 
10206     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
10207     QualType From
10208       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
10209     Result.makeComplexFloat();
10210     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
10211                                 To, Result.FloatReal) &&
10212            HandleIntToFloatCast(Info, E, From, Result.IntImag,
10213                                 To, Result.FloatImag);
10214   }
10215   }
10216 
10217   llvm_unreachable("unknown cast resulting in complex value");
10218 }
10219 
10220 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
10221   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
10222     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
10223 
10224   // Track whether the LHS or RHS is real at the type system level. When this is
10225   // the case we can simplify our evaluation strategy.
10226   bool LHSReal = false, RHSReal = false;
10227 
10228   bool LHSOK;
10229   if (E->getLHS()->getType()->isRealFloatingType()) {
10230     LHSReal = true;
10231     APFloat &Real = Result.FloatReal;
10232     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
10233     if (LHSOK) {
10234       Result.makeComplexFloat();
10235       Result.FloatImag = APFloat(Real.getSemantics());
10236     }
10237   } else {
10238     LHSOK = Visit(E->getLHS());
10239   }
10240   if (!LHSOK && !Info.noteFailure())
10241     return false;
10242 
10243   ComplexValue RHS;
10244   if (E->getRHS()->getType()->isRealFloatingType()) {
10245     RHSReal = true;
10246     APFloat &Real = RHS.FloatReal;
10247     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
10248       return false;
10249     RHS.makeComplexFloat();
10250     RHS.FloatImag = APFloat(Real.getSemantics());
10251   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
10252     return false;
10253 
10254   assert(!(LHSReal && RHSReal) &&
10255          "Cannot have both operands of a complex operation be real.");
10256   switch (E->getOpcode()) {
10257   default: return Error(E);
10258   case BO_Add:
10259     if (Result.isComplexFloat()) {
10260       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
10261                                        APFloat::rmNearestTiesToEven);
10262       if (LHSReal)
10263         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10264       else if (!RHSReal)
10265         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
10266                                          APFloat::rmNearestTiesToEven);
10267     } else {
10268       Result.getComplexIntReal() += RHS.getComplexIntReal();
10269       Result.getComplexIntImag() += RHS.getComplexIntImag();
10270     }
10271     break;
10272   case BO_Sub:
10273     if (Result.isComplexFloat()) {
10274       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
10275                                             APFloat::rmNearestTiesToEven);
10276       if (LHSReal) {
10277         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
10278         Result.getComplexFloatImag().changeSign();
10279       } else if (!RHSReal) {
10280         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
10281                                               APFloat::rmNearestTiesToEven);
10282       }
10283     } else {
10284       Result.getComplexIntReal() -= RHS.getComplexIntReal();
10285       Result.getComplexIntImag() -= RHS.getComplexIntImag();
10286     }
10287     break;
10288   case BO_Mul:
10289     if (Result.isComplexFloat()) {
10290       // This is an implementation of complex multiplication according to the
10291       // constraints laid out in C11 Annex G. The implemention uses the
10292       // following naming scheme:
10293       //   (a + ib) * (c + id)
10294       ComplexValue LHS = Result;
10295       APFloat &A = LHS.getComplexFloatReal();
10296       APFloat &B = LHS.getComplexFloatImag();
10297       APFloat &C = RHS.getComplexFloatReal();
10298       APFloat &D = RHS.getComplexFloatImag();
10299       APFloat &ResR = Result.getComplexFloatReal();
10300       APFloat &ResI = Result.getComplexFloatImag();
10301       if (LHSReal) {
10302         assert(!RHSReal && "Cannot have two real operands for a complex op!");
10303         ResR = A * C;
10304         ResI = A * D;
10305       } else if (RHSReal) {
10306         ResR = C * A;
10307         ResI = C * B;
10308       } else {
10309         // In the fully general case, we need to handle NaNs and infinities
10310         // robustly.
10311         APFloat AC = A * C;
10312         APFloat BD = B * D;
10313         APFloat AD = A * D;
10314         APFloat BC = B * C;
10315         ResR = AC - BD;
10316         ResI = AD + BC;
10317         if (ResR.isNaN() && ResI.isNaN()) {
10318           bool Recalc = false;
10319           if (A.isInfinity() || B.isInfinity()) {
10320             A = APFloat::copySign(
10321                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10322             B = APFloat::copySign(
10323                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10324             if (C.isNaN())
10325               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10326             if (D.isNaN())
10327               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10328             Recalc = true;
10329           }
10330           if (C.isInfinity() || D.isInfinity()) {
10331             C = APFloat::copySign(
10332                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10333             D = APFloat::copySign(
10334                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10335             if (A.isNaN())
10336               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10337             if (B.isNaN())
10338               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10339             Recalc = true;
10340           }
10341           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
10342                           AD.isInfinity() || BC.isInfinity())) {
10343             if (A.isNaN())
10344               A = APFloat::copySign(APFloat(A.getSemantics()), A);
10345             if (B.isNaN())
10346               B = APFloat::copySign(APFloat(B.getSemantics()), B);
10347             if (C.isNaN())
10348               C = APFloat::copySign(APFloat(C.getSemantics()), C);
10349             if (D.isNaN())
10350               D = APFloat::copySign(APFloat(D.getSemantics()), D);
10351             Recalc = true;
10352           }
10353           if (Recalc) {
10354             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
10355             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
10356           }
10357         }
10358       }
10359     } else {
10360       ComplexValue LHS = Result;
10361       Result.getComplexIntReal() =
10362         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
10363          LHS.getComplexIntImag() * RHS.getComplexIntImag());
10364       Result.getComplexIntImag() =
10365         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
10366          LHS.getComplexIntImag() * RHS.getComplexIntReal());
10367     }
10368     break;
10369   case BO_Div:
10370     if (Result.isComplexFloat()) {
10371       // This is an implementation of complex division according to the
10372       // constraints laid out in C11 Annex G. The implemention uses the
10373       // following naming scheme:
10374       //   (a + ib) / (c + id)
10375       ComplexValue LHS = Result;
10376       APFloat &A = LHS.getComplexFloatReal();
10377       APFloat &B = LHS.getComplexFloatImag();
10378       APFloat &C = RHS.getComplexFloatReal();
10379       APFloat &D = RHS.getComplexFloatImag();
10380       APFloat &ResR = Result.getComplexFloatReal();
10381       APFloat &ResI = Result.getComplexFloatImag();
10382       if (RHSReal) {
10383         ResR = A / C;
10384         ResI = B / C;
10385       } else {
10386         if (LHSReal) {
10387           // No real optimizations we can do here, stub out with zero.
10388           B = APFloat::getZero(A.getSemantics());
10389         }
10390         int DenomLogB = 0;
10391         APFloat MaxCD = maxnum(abs(C), abs(D));
10392         if (MaxCD.isFinite()) {
10393           DenomLogB = ilogb(MaxCD);
10394           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
10395           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
10396         }
10397         APFloat Denom = C * C + D * D;
10398         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
10399                       APFloat::rmNearestTiesToEven);
10400         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
10401                       APFloat::rmNearestTiesToEven);
10402         if (ResR.isNaN() && ResI.isNaN()) {
10403           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
10404             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
10405             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
10406           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
10407                      D.isFinite()) {
10408             A = APFloat::copySign(
10409                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
10410             B = APFloat::copySign(
10411                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
10412             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
10413             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
10414           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
10415             C = APFloat::copySign(
10416                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
10417             D = APFloat::copySign(
10418                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
10419             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
10420             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
10421           }
10422         }
10423       }
10424     } else {
10425       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
10426         return Error(E, diag::note_expr_divide_by_zero);
10427 
10428       ComplexValue LHS = Result;
10429       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
10430         RHS.getComplexIntImag() * RHS.getComplexIntImag();
10431       Result.getComplexIntReal() =
10432         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
10433          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
10434       Result.getComplexIntImag() =
10435         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
10436          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
10437     }
10438     break;
10439   }
10440 
10441   return true;
10442 }
10443 
10444 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
10445   // Get the operand value into 'Result'.
10446   if (!Visit(E->getSubExpr()))
10447     return false;
10448 
10449   switch (E->getOpcode()) {
10450   default:
10451     return Error(E);
10452   case UO_Extension:
10453     return true;
10454   case UO_Plus:
10455     // The result is always just the subexpr.
10456     return true;
10457   case UO_Minus:
10458     if (Result.isComplexFloat()) {
10459       Result.getComplexFloatReal().changeSign();
10460       Result.getComplexFloatImag().changeSign();
10461     }
10462     else {
10463       Result.getComplexIntReal() = -Result.getComplexIntReal();
10464       Result.getComplexIntImag() = -Result.getComplexIntImag();
10465     }
10466     return true;
10467   case UO_Not:
10468     if (Result.isComplexFloat())
10469       Result.getComplexFloatImag().changeSign();
10470     else
10471       Result.getComplexIntImag() = -Result.getComplexIntImag();
10472     return true;
10473   }
10474 }
10475 
10476 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
10477   if (E->getNumInits() == 2) {
10478     if (E->getType()->isComplexType()) {
10479       Result.makeComplexFloat();
10480       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
10481         return false;
10482       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
10483         return false;
10484     } else {
10485       Result.makeComplexInt();
10486       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
10487         return false;
10488       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
10489         return false;
10490     }
10491     return true;
10492   }
10493   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
10494 }
10495 
10496 //===----------------------------------------------------------------------===//
10497 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
10498 // implicit conversion.
10499 //===----------------------------------------------------------------------===//
10500 
10501 namespace {
10502 class AtomicExprEvaluator :
10503     public ExprEvaluatorBase<AtomicExprEvaluator> {
10504   const LValue *This;
10505   APValue &Result;
10506 public:
10507   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
10508       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
10509 
10510   bool Success(const APValue &V, const Expr *E) {
10511     Result = V;
10512     return true;
10513   }
10514 
10515   bool ZeroInitialization(const Expr *E) {
10516     ImplicitValueInitExpr VIE(
10517         E->getType()->castAs<AtomicType>()->getValueType());
10518     // For atomic-qualified class (and array) types in C++, initialize the
10519     // _Atomic-wrapped subobject directly, in-place.
10520     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
10521                 : Evaluate(Result, Info, &VIE);
10522   }
10523 
10524   bool VisitCastExpr(const CastExpr *E) {
10525     switch (E->getCastKind()) {
10526     default:
10527       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10528     case CK_NonAtomicToAtomic:
10529       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
10530                   : Evaluate(Result, Info, E->getSubExpr());
10531     }
10532   }
10533 };
10534 } // end anonymous namespace
10535 
10536 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
10537                            EvalInfo &Info) {
10538   assert(E->isRValue() && E->getType()->isAtomicType());
10539   return AtomicExprEvaluator(Info, This, Result).Visit(E);
10540 }
10541 
10542 //===----------------------------------------------------------------------===//
10543 // Void expression evaluation, primarily for a cast to void on the LHS of a
10544 // comma operator
10545 //===----------------------------------------------------------------------===//
10546 
10547 namespace {
10548 class VoidExprEvaluator
10549   : public ExprEvaluatorBase<VoidExprEvaluator> {
10550 public:
10551   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
10552 
10553   bool Success(const APValue &V, const Expr *e) { return true; }
10554 
10555   bool ZeroInitialization(const Expr *E) { return true; }
10556 
10557   bool VisitCastExpr(const CastExpr *E) {
10558     switch (E->getCastKind()) {
10559     default:
10560       return ExprEvaluatorBaseTy::VisitCastExpr(E);
10561     case CK_ToVoid:
10562       VisitIgnoredValue(E->getSubExpr());
10563       return true;
10564     }
10565   }
10566 
10567   bool VisitCallExpr(const CallExpr *E) {
10568     switch (E->getBuiltinCallee()) {
10569     default:
10570       return ExprEvaluatorBaseTy::VisitCallExpr(E);
10571     case Builtin::BI__assume:
10572     case Builtin::BI__builtin_assume:
10573       // The argument is not evaluated!
10574       return true;
10575     }
10576   }
10577 };
10578 } // end anonymous namespace
10579 
10580 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
10581   assert(E->isRValue() && E->getType()->isVoidType());
10582   return VoidExprEvaluator(Info).Visit(E);
10583 }
10584 
10585 //===----------------------------------------------------------------------===//
10586 // Top level Expr::EvaluateAsRValue method.
10587 //===----------------------------------------------------------------------===//
10588 
10589 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
10590   // In C, function designators are not lvalues, but we evaluate them as if they
10591   // are.
10592   QualType T = E->getType();
10593   if (E->isGLValue() || T->isFunctionType()) {
10594     LValue LV;
10595     if (!EvaluateLValue(E, LV, Info))
10596       return false;
10597     LV.moveInto(Result);
10598   } else if (T->isVectorType()) {
10599     if (!EvaluateVector(E, Result, Info))
10600       return false;
10601   } else if (T->isIntegralOrEnumerationType()) {
10602     if (!IntExprEvaluator(Info, Result).Visit(E))
10603       return false;
10604   } else if (T->hasPointerRepresentation()) {
10605     LValue LV;
10606     if (!EvaluatePointer(E, LV, Info))
10607       return false;
10608     LV.moveInto(Result);
10609   } else if (T->isRealFloatingType()) {
10610     llvm::APFloat F(0.0);
10611     if (!EvaluateFloat(E, F, Info))
10612       return false;
10613     Result = APValue(F);
10614   } else if (T->isAnyComplexType()) {
10615     ComplexValue C;
10616     if (!EvaluateComplex(E, C, Info))
10617       return false;
10618     C.moveInto(Result);
10619   } else if (T->isFixedPointType()) {
10620     if (!FixedPointExprEvaluator(Info, Result).Visit(E)) return false;
10621   } else if (T->isMemberPointerType()) {
10622     MemberPtr P;
10623     if (!EvaluateMemberPointer(E, P, Info))
10624       return false;
10625     P.moveInto(Result);
10626     return true;
10627   } else if (T->isArrayType()) {
10628     LValue LV;
10629     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10630     if (!EvaluateArray(E, LV, Value, Info))
10631       return false;
10632     Result = Value;
10633   } else if (T->isRecordType()) {
10634     LValue LV;
10635     APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10636     if (!EvaluateRecord(E, LV, Value, Info))
10637       return false;
10638     Result = Value;
10639   } else if (T->isVoidType()) {
10640     if (!Info.getLangOpts().CPlusPlus11)
10641       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
10642         << E->getType();
10643     if (!EvaluateVoid(E, Info))
10644       return false;
10645   } else if (T->isAtomicType()) {
10646     QualType Unqual = T.getAtomicUnqualifiedType();
10647     if (Unqual->isArrayType() || Unqual->isRecordType()) {
10648       LValue LV;
10649       APValue &Value = createTemporary(E, false, LV, *Info.CurrentCall);
10650       if (!EvaluateAtomic(E, &LV, Value, Info))
10651         return false;
10652     } else {
10653       if (!EvaluateAtomic(E, nullptr, Result, Info))
10654         return false;
10655     }
10656   } else if (Info.getLangOpts().CPlusPlus11) {
10657     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
10658     return false;
10659   } else {
10660     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10661     return false;
10662   }
10663 
10664   return true;
10665 }
10666 
10667 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10668 /// cases, the in-place evaluation is essential, since later initializers for
10669 /// an object can indirectly refer to subobjects which were initialized earlier.
10670 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
10671                             const Expr *E, bool AllowNonLiteralTypes) {
10672   assert(!E->isValueDependent());
10673 
10674   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
10675     return false;
10676 
10677   if (E->isRValue()) {
10678     // Evaluate arrays and record types in-place, so that later initializers can
10679     // refer to earlier-initialized members of the object.
10680     QualType T = E->getType();
10681     if (T->isArrayType())
10682       return EvaluateArray(E, This, Result, Info);
10683     else if (T->isRecordType())
10684       return EvaluateRecord(E, This, Result, Info);
10685     else if (T->isAtomicType()) {
10686       QualType Unqual = T.getAtomicUnqualifiedType();
10687       if (Unqual->isArrayType() || Unqual->isRecordType())
10688         return EvaluateAtomic(E, &This, Result, Info);
10689     }
10690   }
10691 
10692   // For any other type, in-place evaluation is unimportant.
10693   return Evaluate(Result, Info, E);
10694 }
10695 
10696 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10697 /// lvalue-to-rvalue cast if it is an lvalue.
10698 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10699   if (E->getType().isNull())
10700     return false;
10701 
10702   if (!CheckLiteralType(Info, E))
10703     return false;
10704 
10705   if (!::Evaluate(Result, Info, E))
10706     return false;
10707 
10708   if (E->isGLValue()) {
10709     LValue LV;
10710     LV.setFrom(Info.Ctx, Result);
10711     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10712       return false;
10713   }
10714 
10715   // Check this core constant expression is a constant expression.
10716   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10717 }
10718 
10719 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10720                                  const ASTContext &Ctx, bool &IsConst) {
10721   // Fast-path evaluations of integer literals, since we sometimes see files
10722   // containing vast quantities of these.
10723   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10724     Result.Val = APValue(APSInt(L->getValue(),
10725                                 L->getType()->isUnsignedIntegerType()));
10726     IsConst = true;
10727     return true;
10728   }
10729 
10730   // This case should be rare, but we need to check it before we check on
10731   // the type below.
10732   if (Exp->getType().isNull()) {
10733     IsConst = false;
10734     return true;
10735   }
10736 
10737   // FIXME: Evaluating values of large array and record types can cause
10738   // performance problems. Only do so in C++11 for now.
10739   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10740                           Exp->getType()->isRecordType()) &&
10741       !Ctx.getLangOpts().CPlusPlus11) {
10742     IsConst = false;
10743     return true;
10744   }
10745   return false;
10746 }
10747 
10748 
10749 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10750 /// any crazy technique (that has nothing to do with language standards) that
10751 /// we want to.  If this function returns true, it returns the folded constant
10752 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10753 /// will be applied to the result.
10754 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
10755   bool IsConst;
10756   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
10757     return IsConst;
10758 
10759   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10760   return ::EvaluateAsRValue(Info, this, Result.Val);
10761 }
10762 
10763 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10764                                       const ASTContext &Ctx) const {
10765   EvalResult Scratch;
10766   return EvaluateAsRValue(Scratch, Ctx) &&
10767          HandleConversionToBool(Scratch.Val, Result);
10768 }
10769 
10770 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10771                                       Expr::SideEffectsKind SEK) {
10772   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10773          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10774 }
10775 
10776 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10777                          SideEffectsKind AllowSideEffects) const {
10778   if (!getType()->isIntegralOrEnumerationType())
10779     return false;
10780 
10781   EvalResult ExprResult;
10782   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10783       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10784     return false;
10785 
10786   Result = ExprResult.Val.getInt();
10787   return true;
10788 }
10789 
10790 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10791                            SideEffectsKind AllowSideEffects) const {
10792   if (!getType()->isRealFloatingType())
10793     return false;
10794 
10795   EvalResult ExprResult;
10796   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10797       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10798     return false;
10799 
10800   Result = ExprResult.Val.getFloat();
10801   return true;
10802 }
10803 
10804 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10805   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10806 
10807   LValue LV;
10808   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10809       !CheckLValueConstantExpression(Info, getExprLoc(),
10810                                      Ctx.getLValueReferenceType(getType()), LV,
10811                                      Expr::EvaluateForCodeGen))
10812     return false;
10813 
10814   LV.moveInto(Result.Val);
10815   return true;
10816 }
10817 
10818 bool Expr::EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
10819                                   const ASTContext &Ctx) const {
10820   EvalInfo::EvaluationMode EM = EvalInfo::EM_ConstantExpression;
10821   EvalInfo Info(Ctx, Result, EM);
10822   if (!::Evaluate(Result.Val, Info, this))
10823     return false;
10824 
10825   return CheckConstantExpression(Info, getExprLoc(), getType(), Result.Val,
10826                                  Usage);
10827 }
10828 
10829 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10830                                  const VarDecl *VD,
10831                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10832   // FIXME: Evaluating initializers for large array and record types can cause
10833   // performance problems. Only do so in C++11 for now.
10834   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10835       !Ctx.getLangOpts().CPlusPlus11)
10836     return false;
10837 
10838   Expr::EvalStatus EStatus;
10839   EStatus.Diag = &Notes;
10840 
10841   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10842                                       ? EvalInfo::EM_ConstantExpression
10843                                       : EvalInfo::EM_ConstantFold);
10844   InitInfo.setEvaluatingDecl(VD, Value);
10845 
10846   LValue LVal;
10847   LVal.set(VD);
10848 
10849   // C++11 [basic.start.init]p2:
10850   //  Variables with static storage duration or thread storage duration shall be
10851   //  zero-initialized before any other initialization takes place.
10852   // This behavior is not present in C.
10853   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10854       !VD->getType()->isReferenceType()) {
10855     ImplicitValueInitExpr VIE(VD->getType());
10856     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10857                          /*AllowNonLiteralTypes=*/true))
10858       return false;
10859   }
10860 
10861   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10862                        /*AllowNonLiteralTypes=*/true) ||
10863       EStatus.HasSideEffects)
10864     return false;
10865 
10866   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10867                                  Value);
10868 }
10869 
10870 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10871 /// constant folded, but discard the result.
10872 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10873   EvalResult Result;
10874   return EvaluateAsRValue(Result, Ctx) &&
10875          !hasUnacceptableSideEffect(Result, SEK);
10876 }
10877 
10878 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10879                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10880   EvalResult EvalResult;
10881   EvalResult.Diag = Diag;
10882   bool Result = EvaluateAsRValue(EvalResult, Ctx);
10883   (void)Result;
10884   assert(Result && "Could not evaluate expression");
10885   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10886 
10887   return EvalResult.Val.getInt();
10888 }
10889 
10890 APSInt Expr::EvaluateKnownConstIntCheckOverflow(
10891     const ASTContext &Ctx, SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10892   EvalResult EvalResult;
10893   EvalResult.Diag = Diag;
10894   EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10895   bool Result = ::EvaluateAsRValue(Info, this, EvalResult.Val);
10896   (void)Result;
10897   assert(Result && "Could not evaluate expression");
10898   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10899 
10900   return EvalResult.Val.getInt();
10901 }
10902 
10903 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10904   bool IsConst;
10905   EvalResult EvalResult;
10906   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10907     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10908     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10909   }
10910 }
10911 
10912 bool Expr::EvalResult::isGlobalLValue() const {
10913   assert(Val.isLValue());
10914   return IsGlobalLValue(Val.getLValueBase());
10915 }
10916 
10917 
10918 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10919 /// an integer constant expression.
10920 
10921 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10922 /// comma, etc
10923 
10924 // CheckICE - This function does the fundamental ICE checking: the returned
10925 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10926 // and a (possibly null) SourceLocation indicating the location of the problem.
10927 //
10928 // Note that to reduce code duplication, this helper does no evaluation
10929 // itself; the caller checks whether the expression is evaluatable, and
10930 // in the rare cases where CheckICE actually cares about the evaluated
10931 // value, it calls into Evaluate.
10932 
10933 namespace {
10934 
10935 enum ICEKind {
10936   /// This expression is an ICE.
10937   IK_ICE,
10938   /// This expression is not an ICE, but if it isn't evaluated, it's
10939   /// a legal subexpression for an ICE. This return value is used to handle
10940   /// the comma operator in C99 mode, and non-constant subexpressions.
10941   IK_ICEIfUnevaluated,
10942   /// This expression is not an ICE, and is not a legal subexpression for one.
10943   IK_NotICE
10944 };
10945 
10946 struct ICEDiag {
10947   ICEKind Kind;
10948   SourceLocation Loc;
10949 
10950   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10951 };
10952 
10953 }
10954 
10955 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10956 
10957 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10958 
10959 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10960   Expr::EvalResult EVResult;
10961   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10962       !EVResult.Val.isInt())
10963     return ICEDiag(IK_NotICE, E->getBeginLoc());
10964 
10965   return NoDiag();
10966 }
10967 
10968 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10969   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10970   if (!E->getType()->isIntegralOrEnumerationType())
10971     return ICEDiag(IK_NotICE, E->getBeginLoc());
10972 
10973   switch (E->getStmtClass()) {
10974 #define ABSTRACT_STMT(Node)
10975 #define STMT(Node, Base) case Expr::Node##Class:
10976 #define EXPR(Node, Base)
10977 #include "clang/AST/StmtNodes.inc"
10978   case Expr::PredefinedExprClass:
10979   case Expr::FloatingLiteralClass:
10980   case Expr::ImaginaryLiteralClass:
10981   case Expr::StringLiteralClass:
10982   case Expr::ArraySubscriptExprClass:
10983   case Expr::OMPArraySectionExprClass:
10984   case Expr::MemberExprClass:
10985   case Expr::CompoundAssignOperatorClass:
10986   case Expr::CompoundLiteralExprClass:
10987   case Expr::ExtVectorElementExprClass:
10988   case Expr::DesignatedInitExprClass:
10989   case Expr::ArrayInitLoopExprClass:
10990   case Expr::ArrayInitIndexExprClass:
10991   case Expr::NoInitExprClass:
10992   case Expr::DesignatedInitUpdateExprClass:
10993   case Expr::ImplicitValueInitExprClass:
10994   case Expr::ParenListExprClass:
10995   case Expr::VAArgExprClass:
10996   case Expr::AddrLabelExprClass:
10997   case Expr::StmtExprClass:
10998   case Expr::CXXMemberCallExprClass:
10999   case Expr::CUDAKernelCallExprClass:
11000   case Expr::CXXDynamicCastExprClass:
11001   case Expr::CXXTypeidExprClass:
11002   case Expr::CXXUuidofExprClass:
11003   case Expr::MSPropertyRefExprClass:
11004   case Expr::MSPropertySubscriptExprClass:
11005   case Expr::CXXNullPtrLiteralExprClass:
11006   case Expr::UserDefinedLiteralClass:
11007   case Expr::CXXThisExprClass:
11008   case Expr::CXXThrowExprClass:
11009   case Expr::CXXNewExprClass:
11010   case Expr::CXXDeleteExprClass:
11011   case Expr::CXXPseudoDestructorExprClass:
11012   case Expr::UnresolvedLookupExprClass:
11013   case Expr::TypoExprClass:
11014   case Expr::DependentScopeDeclRefExprClass:
11015   case Expr::CXXConstructExprClass:
11016   case Expr::CXXInheritedCtorInitExprClass:
11017   case Expr::CXXStdInitializerListExprClass:
11018   case Expr::CXXBindTemporaryExprClass:
11019   case Expr::ExprWithCleanupsClass:
11020   case Expr::CXXTemporaryObjectExprClass:
11021   case Expr::CXXUnresolvedConstructExprClass:
11022   case Expr::CXXDependentScopeMemberExprClass:
11023   case Expr::UnresolvedMemberExprClass:
11024   case Expr::ObjCStringLiteralClass:
11025   case Expr::ObjCBoxedExprClass:
11026   case Expr::ObjCArrayLiteralClass:
11027   case Expr::ObjCDictionaryLiteralClass:
11028   case Expr::ObjCEncodeExprClass:
11029   case Expr::ObjCMessageExprClass:
11030   case Expr::ObjCSelectorExprClass:
11031   case Expr::ObjCProtocolExprClass:
11032   case Expr::ObjCIvarRefExprClass:
11033   case Expr::ObjCPropertyRefExprClass:
11034   case Expr::ObjCSubscriptRefExprClass:
11035   case Expr::ObjCIsaExprClass:
11036   case Expr::ObjCAvailabilityCheckExprClass:
11037   case Expr::ShuffleVectorExprClass:
11038   case Expr::ConvertVectorExprClass:
11039   case Expr::BlockExprClass:
11040   case Expr::NoStmtClass:
11041   case Expr::OpaqueValueExprClass:
11042   case Expr::PackExpansionExprClass:
11043   case Expr::SubstNonTypeTemplateParmPackExprClass:
11044   case Expr::FunctionParmPackExprClass:
11045   case Expr::AsTypeExprClass:
11046   case Expr::ObjCIndirectCopyRestoreExprClass:
11047   case Expr::MaterializeTemporaryExprClass:
11048   case Expr::PseudoObjectExprClass:
11049   case Expr::AtomicExprClass:
11050   case Expr::LambdaExprClass:
11051   case Expr::CXXFoldExprClass:
11052   case Expr::CoawaitExprClass:
11053   case Expr::DependentCoawaitExprClass:
11054   case Expr::CoyieldExprClass:
11055     return ICEDiag(IK_NotICE, E->getBeginLoc());
11056 
11057   case Expr::InitListExprClass: {
11058     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
11059     // form "T x = { a };" is equivalent to "T x = a;".
11060     // Unless we're initializing a reference, T is a scalar as it is known to be
11061     // of integral or enumeration type.
11062     if (E->isRValue())
11063       if (cast<InitListExpr>(E)->getNumInits() == 1)
11064         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
11065     return ICEDiag(IK_NotICE, E->getBeginLoc());
11066   }
11067 
11068   case Expr::SizeOfPackExprClass:
11069   case Expr::GNUNullExprClass:
11070     // GCC considers the GNU __null value to be an integral constant expression.
11071     return NoDiag();
11072 
11073   case Expr::SubstNonTypeTemplateParmExprClass:
11074     return
11075       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
11076 
11077   case Expr::ConstantExprClass:
11078     return CheckICE(cast<ConstantExpr>(E)->getSubExpr(), Ctx);
11079 
11080   case Expr::ParenExprClass:
11081     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
11082   case Expr::GenericSelectionExprClass:
11083     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
11084   case Expr::IntegerLiteralClass:
11085   case Expr::FixedPointLiteralClass:
11086   case Expr::CharacterLiteralClass:
11087   case Expr::ObjCBoolLiteralExprClass:
11088   case Expr::CXXBoolLiteralExprClass:
11089   case Expr::CXXScalarValueInitExprClass:
11090   case Expr::TypeTraitExprClass:
11091   case Expr::ArrayTypeTraitExprClass:
11092   case Expr::ExpressionTraitExprClass:
11093   case Expr::CXXNoexceptExprClass:
11094     return NoDiag();
11095   case Expr::CallExprClass:
11096   case Expr::CXXOperatorCallExprClass: {
11097     // C99 6.6/3 allows function calls within unevaluated subexpressions of
11098     // constant expressions, but they can never be ICEs because an ICE cannot
11099     // contain an operand of (pointer to) function type.
11100     const CallExpr *CE = cast<CallExpr>(E);
11101     if (CE->getBuiltinCallee())
11102       return CheckEvalInICE(E, Ctx);
11103     return ICEDiag(IK_NotICE, E->getBeginLoc());
11104   }
11105   case Expr::DeclRefExprClass: {
11106     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
11107       return NoDiag();
11108     const ValueDecl *D = cast<DeclRefExpr>(E)->getDecl();
11109     if (Ctx.getLangOpts().CPlusPlus &&
11110         D && IsConstNonVolatile(D->getType())) {
11111       // Parameter variables are never constants.  Without this check,
11112       // getAnyInitializer() can find a default argument, which leads
11113       // to chaos.
11114       if (isa<ParmVarDecl>(D))
11115         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11116 
11117       // C++ 7.1.5.1p2
11118       //   A variable of non-volatile const-qualified integral or enumeration
11119       //   type initialized by an ICE can be used in ICEs.
11120       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
11121         if (!Dcl->getType()->isIntegralOrEnumerationType())
11122           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11123 
11124         const VarDecl *VD;
11125         // Look for a declaration of this variable that has an initializer, and
11126         // check whether it is an ICE.
11127         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
11128           return NoDiag();
11129         else
11130           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
11131       }
11132     }
11133     return ICEDiag(IK_NotICE, E->getBeginLoc());
11134   }
11135   case Expr::UnaryOperatorClass: {
11136     const UnaryOperator *Exp = cast<UnaryOperator>(E);
11137     switch (Exp->getOpcode()) {
11138     case UO_PostInc:
11139     case UO_PostDec:
11140     case UO_PreInc:
11141     case UO_PreDec:
11142     case UO_AddrOf:
11143     case UO_Deref:
11144     case UO_Coawait:
11145       // C99 6.6/3 allows increment and decrement within unevaluated
11146       // subexpressions of constant expressions, but they can never be ICEs
11147       // because an ICE cannot contain an lvalue operand.
11148       return ICEDiag(IK_NotICE, E->getBeginLoc());
11149     case UO_Extension:
11150     case UO_LNot:
11151     case UO_Plus:
11152     case UO_Minus:
11153     case UO_Not:
11154     case UO_Real:
11155     case UO_Imag:
11156       return CheckICE(Exp->getSubExpr(), Ctx);
11157     }
11158     llvm_unreachable("invalid unary operator class");
11159   }
11160   case Expr::OffsetOfExprClass: {
11161     // Note that per C99, offsetof must be an ICE. And AFAIK, using
11162     // EvaluateAsRValue matches the proposed gcc behavior for cases like
11163     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
11164     // compliance: we should warn earlier for offsetof expressions with
11165     // array subscripts that aren't ICEs, and if the array subscripts
11166     // are ICEs, the value of the offsetof must be an integer constant.
11167     return CheckEvalInICE(E, Ctx);
11168   }
11169   case Expr::UnaryExprOrTypeTraitExprClass: {
11170     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
11171     if ((Exp->getKind() ==  UETT_SizeOf) &&
11172         Exp->getTypeOfArgument()->isVariableArrayType())
11173       return ICEDiag(IK_NotICE, E->getBeginLoc());
11174     return NoDiag();
11175   }
11176   case Expr::BinaryOperatorClass: {
11177     const BinaryOperator *Exp = cast<BinaryOperator>(E);
11178     switch (Exp->getOpcode()) {
11179     case BO_PtrMemD:
11180     case BO_PtrMemI:
11181     case BO_Assign:
11182     case BO_MulAssign:
11183     case BO_DivAssign:
11184     case BO_RemAssign:
11185     case BO_AddAssign:
11186     case BO_SubAssign:
11187     case BO_ShlAssign:
11188     case BO_ShrAssign:
11189     case BO_AndAssign:
11190     case BO_XorAssign:
11191     case BO_OrAssign:
11192       // C99 6.6/3 allows assignments within unevaluated subexpressions of
11193       // constant expressions, but they can never be ICEs because an ICE cannot
11194       // contain an lvalue operand.
11195       return ICEDiag(IK_NotICE, E->getBeginLoc());
11196 
11197     case BO_Mul:
11198     case BO_Div:
11199     case BO_Rem:
11200     case BO_Add:
11201     case BO_Sub:
11202     case BO_Shl:
11203     case BO_Shr:
11204     case BO_LT:
11205     case BO_GT:
11206     case BO_LE:
11207     case BO_GE:
11208     case BO_EQ:
11209     case BO_NE:
11210     case BO_And:
11211     case BO_Xor:
11212     case BO_Or:
11213     case BO_Comma:
11214     case BO_Cmp: {
11215       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11216       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11217       if (Exp->getOpcode() == BO_Div ||
11218           Exp->getOpcode() == BO_Rem) {
11219         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
11220         // we don't evaluate one.
11221         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
11222           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
11223           if (REval == 0)
11224             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11225           if (REval.isSigned() && REval.isAllOnesValue()) {
11226             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
11227             if (LEval.isMinSignedValue())
11228               return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11229           }
11230         }
11231       }
11232       if (Exp->getOpcode() == BO_Comma) {
11233         if (Ctx.getLangOpts().C99) {
11234           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
11235           // if it isn't evaluated.
11236           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
11237             return ICEDiag(IK_ICEIfUnevaluated, E->getBeginLoc());
11238         } else {
11239           // In both C89 and C++, commas in ICEs are illegal.
11240           return ICEDiag(IK_NotICE, E->getBeginLoc());
11241         }
11242       }
11243       return Worst(LHSResult, RHSResult);
11244     }
11245     case BO_LAnd:
11246     case BO_LOr: {
11247       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
11248       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
11249       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
11250         // Rare case where the RHS has a comma "side-effect"; we need
11251         // to actually check the condition to see whether the side
11252         // with the comma is evaluated.
11253         if ((Exp->getOpcode() == BO_LAnd) !=
11254             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
11255           return RHSResult;
11256         return NoDiag();
11257       }
11258 
11259       return Worst(LHSResult, RHSResult);
11260     }
11261     }
11262     llvm_unreachable("invalid binary operator kind");
11263   }
11264   case Expr::ImplicitCastExprClass:
11265   case Expr::CStyleCastExprClass:
11266   case Expr::CXXFunctionalCastExprClass:
11267   case Expr::CXXStaticCastExprClass:
11268   case Expr::CXXReinterpretCastExprClass:
11269   case Expr::CXXConstCastExprClass:
11270   case Expr::ObjCBridgedCastExprClass: {
11271     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
11272     if (isa<ExplicitCastExpr>(E)) {
11273       if (const FloatingLiteral *FL
11274             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
11275         unsigned DestWidth = Ctx.getIntWidth(E->getType());
11276         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
11277         APSInt IgnoredVal(DestWidth, !DestSigned);
11278         bool Ignored;
11279         // If the value does not fit in the destination type, the behavior is
11280         // undefined, so we are not required to treat it as a constant
11281         // expression.
11282         if (FL->getValue().convertToInteger(IgnoredVal,
11283                                             llvm::APFloat::rmTowardZero,
11284                                             &Ignored) & APFloat::opInvalidOp)
11285           return ICEDiag(IK_NotICE, E->getBeginLoc());
11286         return NoDiag();
11287       }
11288     }
11289     switch (cast<CastExpr>(E)->getCastKind()) {
11290     case CK_LValueToRValue:
11291     case CK_AtomicToNonAtomic:
11292     case CK_NonAtomicToAtomic:
11293     case CK_NoOp:
11294     case CK_IntegralToBoolean:
11295     case CK_IntegralCast:
11296       return CheckICE(SubExpr, Ctx);
11297     default:
11298       return ICEDiag(IK_NotICE, E->getBeginLoc());
11299     }
11300   }
11301   case Expr::BinaryConditionalOperatorClass: {
11302     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
11303     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
11304     if (CommonResult.Kind == IK_NotICE) return CommonResult;
11305     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11306     if (FalseResult.Kind == IK_NotICE) return FalseResult;
11307     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
11308     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
11309         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
11310     return FalseResult;
11311   }
11312   case Expr::ConditionalOperatorClass: {
11313     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
11314     // If the condition (ignoring parens) is a __builtin_constant_p call,
11315     // then only the true side is actually considered in an integer constant
11316     // expression, and it is fully evaluated.  This is an important GNU
11317     // extension.  See GCC PR38377 for discussion.
11318     if (const CallExpr *CallCE
11319         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
11320       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
11321         return CheckEvalInICE(E, Ctx);
11322     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
11323     if (CondResult.Kind == IK_NotICE)
11324       return CondResult;
11325 
11326     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
11327     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
11328 
11329     if (TrueResult.Kind == IK_NotICE)
11330       return TrueResult;
11331     if (FalseResult.Kind == IK_NotICE)
11332       return FalseResult;
11333     if (CondResult.Kind == IK_ICEIfUnevaluated)
11334       return CondResult;
11335     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
11336       return NoDiag();
11337     // Rare case where the diagnostics depend on which side is evaluated
11338     // Note that if we get here, CondResult is 0, and at least one of
11339     // TrueResult and FalseResult is non-zero.
11340     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
11341       return FalseResult;
11342     return TrueResult;
11343   }
11344   case Expr::CXXDefaultArgExprClass:
11345     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
11346   case Expr::CXXDefaultInitExprClass:
11347     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
11348   case Expr::ChooseExprClass: {
11349     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
11350   }
11351   }
11352 
11353   llvm_unreachable("Invalid StmtClass!");
11354 }
11355 
11356 /// Evaluate an expression as a C++11 integral constant expression.
11357 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
11358                                                     const Expr *E,
11359                                                     llvm::APSInt *Value,
11360                                                     SourceLocation *Loc) {
11361   if (!E->getType()->isIntegralOrUnscopedEnumerationType()) {
11362     if (Loc) *Loc = E->getExprLoc();
11363     return false;
11364   }
11365 
11366   APValue Result;
11367   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
11368     return false;
11369 
11370   if (!Result.isInt()) {
11371     if (Loc) *Loc = E->getExprLoc();
11372     return false;
11373   }
11374 
11375   if (Value) *Value = Result.getInt();
11376   return true;
11377 }
11378 
11379 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
11380                                  SourceLocation *Loc) const {
11381   if (Ctx.getLangOpts().CPlusPlus11)
11382     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
11383 
11384   ICEDiag D = CheckICE(this, Ctx);
11385   if (D.Kind != IK_ICE) {
11386     if (Loc) *Loc = D.Loc;
11387     return false;
11388   }
11389   return true;
11390 }
11391 
11392 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
11393                                  SourceLocation *Loc, bool isEvaluated) const {
11394   if (Ctx.getLangOpts().CPlusPlus11)
11395     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
11396 
11397   if (!isIntegerConstantExpr(Ctx, Loc))
11398     return false;
11399   // The only possible side-effects here are due to UB discovered in the
11400   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
11401   // required to treat the expression as an ICE, so we produce the folded
11402   // value.
11403   if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
11404     llvm_unreachable("ICE cannot be evaluated!");
11405   return true;
11406 }
11407 
11408 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
11409   return CheckICE(this, Ctx).Kind == IK_ICE;
11410 }
11411 
11412 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
11413                                SourceLocation *Loc) const {
11414   // We support this checking in C++98 mode in order to diagnose compatibility
11415   // issues.
11416   assert(Ctx.getLangOpts().CPlusPlus);
11417 
11418   // Build evaluation settings.
11419   Expr::EvalStatus Status;
11420   SmallVector<PartialDiagnosticAt, 8> Diags;
11421   Status.Diag = &Diags;
11422   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
11423 
11424   APValue Scratch;
11425   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
11426 
11427   if (!Diags.empty()) {
11428     IsConstExpr = false;
11429     if (Loc) *Loc = Diags[0].first;
11430   } else if (!IsConstExpr) {
11431     // FIXME: This shouldn't happen.
11432     if (Loc) *Loc = getExprLoc();
11433   }
11434 
11435   return IsConstExpr;
11436 }
11437 
11438 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
11439                                     const FunctionDecl *Callee,
11440                                     ArrayRef<const Expr*> Args,
11441                                     const Expr *This) const {
11442   Expr::EvalStatus Status;
11443   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
11444 
11445   LValue ThisVal;
11446   const LValue *ThisPtr = nullptr;
11447   if (This) {
11448 #ifndef NDEBUG
11449     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
11450     assert(MD && "Don't provide `this` for non-methods.");
11451     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
11452 #endif
11453     if (EvaluateObjectArgument(Info, This, ThisVal))
11454       ThisPtr = &ThisVal;
11455     if (Info.EvalStatus.HasSideEffects)
11456       return false;
11457   }
11458 
11459   ArgVector ArgValues(Args.size());
11460   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
11461        I != E; ++I) {
11462     if ((*I)->isValueDependent() ||
11463         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
11464       // If evaluation fails, throw away the argument entirely.
11465       ArgValues[I - Args.begin()] = APValue();
11466     if (Info.EvalStatus.HasSideEffects)
11467       return false;
11468   }
11469 
11470   // Build fake call to Callee.
11471   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
11472                        ArgValues.data());
11473   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
11474 }
11475 
11476 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
11477                                    SmallVectorImpl<
11478                                      PartialDiagnosticAt> &Diags) {
11479   // FIXME: It would be useful to check constexpr function templates, but at the
11480   // moment the constant expression evaluator cannot cope with the non-rigorous
11481   // ASTs which we build for dependent expressions.
11482   if (FD->isDependentContext())
11483     return true;
11484 
11485   Expr::EvalStatus Status;
11486   Status.Diag = &Diags;
11487 
11488   EvalInfo Info(FD->getASTContext(), Status,
11489                 EvalInfo::EM_PotentialConstantExpression);
11490 
11491   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
11492   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
11493 
11494   // Fabricate an arbitrary expression on the stack and pretend that it
11495   // is a temporary being used as the 'this' pointer.
11496   LValue This;
11497   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
11498   This.set({&VIE, Info.CurrentCall->Index});
11499 
11500   ArrayRef<const Expr*> Args;
11501 
11502   APValue Scratch;
11503   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
11504     // Evaluate the call as a constant initializer, to allow the construction
11505     // of objects of non-literal types.
11506     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
11507     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
11508   } else {
11509     SourceLocation Loc = FD->getLocation();
11510     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
11511                        Args, FD->getBody(), Info, Scratch, nullptr);
11512   }
11513 
11514   return Diags.empty();
11515 }
11516 
11517 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
11518                                               const FunctionDecl *FD,
11519                                               SmallVectorImpl<
11520                                                 PartialDiagnosticAt> &Diags) {
11521   Expr::EvalStatus Status;
11522   Status.Diag = &Diags;
11523 
11524   EvalInfo Info(FD->getASTContext(), Status,
11525                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
11526 
11527   // Fabricate a call stack frame to give the arguments a plausible cover story.
11528   ArrayRef<const Expr*> Args;
11529   ArgVector ArgValues(0);
11530   bool Success = EvaluateArgs(Args, ArgValues, Info);
11531   (void)Success;
11532   assert(Success &&
11533          "Failed to set up arguments for potential constant evaluation");
11534   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
11535 
11536   APValue ResultScratch;
11537   Evaluate(ResultScratch, Info, E);
11538   return Diags.empty();
11539 }
11540 
11541 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
11542                                  unsigned Type) const {
11543   if (!getType()->isPointerType())
11544     return false;
11545 
11546   Expr::EvalStatus Status;
11547   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
11548   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
11549 }
11550