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/RecordLayout.h"
43 #include "clang/AST/StmtVisitor.h"
44 #include "clang/AST/TypeLoc.h"
45 #include "clang/Basic/Builtins.h"
46 #include "clang/Basic/TargetInfo.h"
47 #include "llvm/Support/raw_ostream.h"
48 #include <cstring>
49 #include <functional>
50 
51 #define DEBUG_TYPE "exprconstant"
52 
53 using namespace clang;
54 using llvm::APSInt;
55 using llvm::APFloat;
56 
57 static bool IsGlobalLValue(APValue::LValueBase B);
58 
59 namespace {
60   struct LValue;
61   struct CallStackFrame;
62   struct EvalInfo;
63 
64   static QualType getType(APValue::LValueBase B) {
65     if (!B) return QualType();
66     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
67       // FIXME: It's unclear where we're supposed to take the type from, and
68       // this actually matters for arrays of unknown bound. Using the type of
69       // the most recent declaration isn't clearly correct in general. Eg:
70       //
71       // extern int arr[]; void f() { extern int arr[3]; };
72       // constexpr int *p = &arr[1]; // valid?
73       return cast<ValueDecl>(D->getMostRecentDecl())->getType();
74 
75     const Expr *Base = B.get<const Expr*>();
76 
77     // For a materialized temporary, the type of the temporary we materialized
78     // may not be the type of the expression.
79     if (const MaterializeTemporaryExpr *MTE =
80             dyn_cast<MaterializeTemporaryExpr>(Base)) {
81       SmallVector<const Expr *, 2> CommaLHSs;
82       SmallVector<SubobjectAdjustment, 2> Adjustments;
83       const Expr *Temp = MTE->GetTemporaryExpr();
84       const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
85                                                                Adjustments);
86       // Keep any cv-qualifiers from the reference if we generated a temporary
87       // for it directly. Otherwise use the type after adjustment.
88       if (!Adjustments.empty())
89         return Inner->getType();
90     }
91 
92     return Base->getType();
93   }
94 
95   /// Get an LValue path entry, which is known to not be an array index, as a
96   /// field or base class.
97   static
98   APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
99     APValue::BaseOrMemberType Value;
100     Value.setFromOpaqueValue(E.BaseOrMember);
101     return Value;
102   }
103 
104   /// Get an LValue path entry, which is known to not be an array index, as a
105   /// field declaration.
106   static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
107     return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
108   }
109   /// Get an LValue path entry, which is known to not be an array index, as a
110   /// base class declaration.
111   static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
112     return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
113   }
114   /// Determine whether this LValue path entry for a base class names a virtual
115   /// base class.
116   static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
117     return getAsBaseOrMember(E).getInt();
118   }
119 
120   /// Given a CallExpr, try to get the alloc_size attribute. May return null.
121   static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
122     const FunctionDecl *Callee = CE->getDirectCallee();
123     return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
124   }
125 
126   /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
127   /// This will look through a single cast.
128   ///
129   /// Returns null if we couldn't unwrap a function with alloc_size.
130   static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
131     if (!E->getType()->isPointerType())
132       return nullptr;
133 
134     E = E->IgnoreParens();
135     // If we're doing a variable assignment from e.g. malloc(N), there will
136     // probably be a cast of some kind. Ignore it.
137     if (const auto *Cast = dyn_cast<CastExpr>(E))
138       E = Cast->getSubExpr()->IgnoreParens();
139 
140     if (const auto *CE = dyn_cast<CallExpr>(E))
141       return getAllocSizeAttr(CE) ? CE : nullptr;
142     return nullptr;
143   }
144 
145   /// Determines whether or not the given Base contains a call to a function
146   /// with the alloc_size attribute.
147   static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
148     const auto *E = Base.dyn_cast<const Expr *>();
149     return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
150   }
151 
152   /// The bound to claim that an array of unknown bound has.
153   /// The value in MostDerivedArraySize is undefined in this case. So, set it
154   /// to an arbitrary value that's likely to loudly break things if it's used.
155   static const uint64_t AssumedSizeForUnsizedArray =
156       std::numeric_limits<uint64_t>::max() / 2;
157 
158   /// Determines if an LValue with the given LValueBase will have an unsized
159   /// array in its designator.
160   /// Find the path length and type of the most-derived subobject in the given
161   /// path, and find the size of the containing array, if any.
162   static unsigned
163   findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
164                            ArrayRef<APValue::LValuePathEntry> Path,
165                            uint64_t &ArraySize, QualType &Type, bool &IsArray,
166                            bool &FirstEntryIsUnsizedArray) {
167     // This only accepts LValueBases from APValues, and APValues don't support
168     // arrays that lack size info.
169     assert(!isBaseAnAllocSizeCall(Base) &&
170            "Unsized arrays shouldn't appear here");
171     unsigned MostDerivedLength = 0;
172     Type = getType(Base);
173 
174     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
175       if (Type->isArrayType()) {
176         const ArrayType *AT = Ctx.getAsArrayType(Type);
177         Type = AT->getElementType();
178         MostDerivedLength = I + 1;
179         IsArray = true;
180 
181         if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
182           ArraySize = CAT->getSize().getZExtValue();
183         } else {
184           assert(I == 0 && "unexpected unsized array designator");
185           FirstEntryIsUnsizedArray = true;
186           ArraySize = AssumedSizeForUnsizedArray;
187         }
188       } else if (Type->isAnyComplexType()) {
189         const ComplexType *CT = Type->castAs<ComplexType>();
190         Type = CT->getElementType();
191         ArraySize = 2;
192         MostDerivedLength = I + 1;
193         IsArray = true;
194       } else if (const FieldDecl *FD = getAsField(Path[I])) {
195         Type = FD->getType();
196         ArraySize = 0;
197         MostDerivedLength = I + 1;
198         IsArray = false;
199       } else {
200         // Path[I] describes a base class.
201         ArraySize = 0;
202         IsArray = false;
203       }
204     }
205     return MostDerivedLength;
206   }
207 
208   // The order of this enum is important for diagnostics.
209   enum CheckSubobjectKind {
210     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
211     CSK_This, CSK_Real, CSK_Imag
212   };
213 
214   /// A path from a glvalue to a subobject of that glvalue.
215   struct SubobjectDesignator {
216     /// True if the subobject was named in a manner not supported by C++11. Such
217     /// lvalues can still be folded, but they are not core constant expressions
218     /// and we cannot perform lvalue-to-rvalue conversions on them.
219     unsigned Invalid : 1;
220 
221     /// Is this a pointer one past the end of an object?
222     unsigned IsOnePastTheEnd : 1;
223 
224     /// Indicator of whether the first entry is an unsized array.
225     unsigned FirstEntryIsAnUnsizedArray : 1;
226 
227     /// Indicator of whether the most-derived object is an array element.
228     unsigned MostDerivedIsArrayElement : 1;
229 
230     /// The length of the path to the most-derived object of which this is a
231     /// subobject.
232     unsigned MostDerivedPathLength : 28;
233 
234     /// The size of the array of which the most-derived object is an element.
235     /// This will always be 0 if the most-derived object is not an array
236     /// element. 0 is not an indicator of whether or not the most-derived object
237     /// is an array, however, because 0-length arrays are allowed.
238     ///
239     /// If the current array is an unsized array, the value of this is
240     /// undefined.
241     uint64_t MostDerivedArraySize;
242 
243     /// The type of the most derived object referred to by this address.
244     QualType MostDerivedType;
245 
246     typedef APValue::LValuePathEntry PathEntry;
247 
248     /// The entries on the path from the glvalue to the designated subobject.
249     SmallVector<PathEntry, 8> Entries;
250 
251     SubobjectDesignator() : Invalid(true) {}
252 
253     explicit SubobjectDesignator(QualType T)
254         : Invalid(false), IsOnePastTheEnd(false),
255           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
256           MostDerivedPathLength(0), MostDerivedArraySize(0),
257           MostDerivedType(T) {}
258 
259     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
260         : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
261           FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
262           MostDerivedPathLength(0), MostDerivedArraySize(0) {
263       assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
264       if (!Invalid) {
265         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
266         ArrayRef<PathEntry> VEntries = V.getLValuePath();
267         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
268         if (V.getLValueBase()) {
269           bool IsArray = false;
270           bool FirstIsUnsizedArray = false;
271           MostDerivedPathLength = findMostDerivedSubobject(
272               Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
273               MostDerivedType, IsArray, FirstIsUnsizedArray);
274           MostDerivedIsArrayElement = IsArray;
275           FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
276         }
277       }
278     }
279 
280     void setInvalid() {
281       Invalid = true;
282       Entries.clear();
283     }
284 
285     /// Determine whether the most derived subobject is an array without a
286     /// known bound.
287     bool isMostDerivedAnUnsizedArray() const {
288       assert(!Invalid && "Calling this makes no sense on invalid designators");
289       return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
290     }
291 
292     /// Determine what the most derived array's size is. Results in an assertion
293     /// failure if the most derived array lacks a size.
294     uint64_t getMostDerivedArraySize() const {
295       assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
296       return MostDerivedArraySize;
297     }
298 
299     /// Determine whether this is a one-past-the-end pointer.
300     bool isOnePastTheEnd() const {
301       assert(!Invalid);
302       if (IsOnePastTheEnd)
303         return true;
304       if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
305           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
306         return true;
307       return false;
308     }
309 
310     /// Check that this refers to a valid subobject.
311     bool isValidSubobject() const {
312       if (Invalid)
313         return false;
314       return !isOnePastTheEnd();
315     }
316     /// Check that this refers to a valid subobject, and if not, produce a
317     /// relevant diagnostic and set the designator as invalid.
318     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
319 
320     /// Update this designator to refer to the first element within this array.
321     void addArrayUnchecked(const ConstantArrayType *CAT) {
322       PathEntry Entry;
323       Entry.ArrayIndex = 0;
324       Entries.push_back(Entry);
325 
326       // This is a most-derived object.
327       MostDerivedType = CAT->getElementType();
328       MostDerivedIsArrayElement = true;
329       MostDerivedArraySize = CAT->getSize().getZExtValue();
330       MostDerivedPathLength = Entries.size();
331     }
332     /// Update this designator to refer to the first element within the array of
333     /// elements of type T. This is an array of unknown size.
334     void addUnsizedArrayUnchecked(QualType ElemTy) {
335       PathEntry Entry;
336       Entry.ArrayIndex = 0;
337       Entries.push_back(Entry);
338 
339       MostDerivedType = ElemTy;
340       MostDerivedIsArrayElement = true;
341       // The value in MostDerivedArraySize is undefined in this case. So, set it
342       // to an arbitrary value that's likely to loudly break things if it's
343       // used.
344       MostDerivedArraySize = AssumedSizeForUnsizedArray;
345       MostDerivedPathLength = Entries.size();
346     }
347     /// Update this designator to refer to the given base or member of this
348     /// object.
349     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
350       PathEntry Entry;
351       APValue::BaseOrMemberType Value(D, Virtual);
352       Entry.BaseOrMember = Value.getOpaqueValue();
353       Entries.push_back(Entry);
354 
355       // If this isn't a base class, it's a new most-derived object.
356       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
357         MostDerivedType = FD->getType();
358         MostDerivedIsArrayElement = false;
359         MostDerivedArraySize = 0;
360         MostDerivedPathLength = Entries.size();
361       }
362     }
363     /// Update this designator to refer to the given complex component.
364     void addComplexUnchecked(QualType EltTy, bool Imag) {
365       PathEntry Entry;
366       Entry.ArrayIndex = Imag;
367       Entries.push_back(Entry);
368 
369       // This is technically a most-derived object, though in practice this
370       // is unlikely to matter.
371       MostDerivedType = EltTy;
372       MostDerivedIsArrayElement = true;
373       MostDerivedArraySize = 2;
374       MostDerivedPathLength = Entries.size();
375     }
376     void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
377     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
378                                    const APSInt &N);
379     /// Add N to the address of this subobject.
380     void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
381       if (Invalid || !N) return;
382       uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
383       if (isMostDerivedAnUnsizedArray()) {
384         diagnoseUnsizedArrayPointerArithmetic(Info, E);
385         // Can't verify -- trust that the user is doing the right thing (or if
386         // not, trust that the caller will catch the bad behavior).
387         // FIXME: Should we reject if this overflows, at least?
388         Entries.back().ArrayIndex += TruncatedN;
389         return;
390       }
391 
392       // [expr.add]p4: For the purposes of these operators, a pointer to a
393       // nonarray object behaves the same as a pointer to the first element of
394       // an array of length one with the type of the object as its element type.
395       bool IsArray = MostDerivedPathLength == Entries.size() &&
396                      MostDerivedIsArrayElement;
397       uint64_t ArrayIndex =
398           IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
399       uint64_t ArraySize =
400           IsArray ? getMostDerivedArraySize() : (uint64_t)1;
401 
402       if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
403         // Calculate the actual index in a wide enough type, so we can include
404         // it in the note.
405         N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
406         (llvm::APInt&)N += ArrayIndex;
407         assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
408         diagnosePointerArithmetic(Info, E, N);
409         setInvalid();
410         return;
411       }
412 
413       ArrayIndex += TruncatedN;
414       assert(ArrayIndex <= ArraySize &&
415              "bounds check succeeded for out-of-bounds index");
416 
417       if (IsArray)
418         Entries.back().ArrayIndex = ArrayIndex;
419       else
420         IsOnePastTheEnd = (ArrayIndex != 0);
421     }
422   };
423 
424   /// A stack frame in the constexpr call stack.
425   struct CallStackFrame {
426     EvalInfo &Info;
427 
428     /// Parent - The caller of this stack frame.
429     CallStackFrame *Caller;
430 
431     /// Callee - The function which was called.
432     const FunctionDecl *Callee;
433 
434     /// This - The binding for the this pointer in this call, if any.
435     const LValue *This;
436 
437     /// Arguments - Parameter bindings for this function call, indexed by
438     /// parameters' function scope indices.
439     APValue *Arguments;
440 
441     // Note that we intentionally use std::map here so that references to
442     // values are stable.
443     typedef std::map<const void*, APValue> MapTy;
444     typedef MapTy::const_iterator temp_iterator;
445     /// Temporaries - Temporary lvalues materialized within this stack frame.
446     MapTy Temporaries;
447 
448     /// CallLoc - The location of the call expression for this call.
449     SourceLocation CallLoc;
450 
451     /// Index - The call index of this call.
452     unsigned Index;
453 
454     // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
455     // on the overall stack usage of deeply-recursing constexpr evaluataions.
456     // (We should cache this map rather than recomputing it repeatedly.)
457     // But let's try this and see how it goes; we can look into caching the map
458     // as a later change.
459 
460     /// LambdaCaptureFields - Mapping from captured variables/this to
461     /// corresponding data members in the closure class.
462     llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
463     FieldDecl *LambdaThisCaptureField;
464 
465     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
466                    const FunctionDecl *Callee, const LValue *This,
467                    APValue *Arguments);
468     ~CallStackFrame();
469 
470     APValue *getTemporary(const void *Key) {
471       MapTy::iterator I = Temporaries.find(Key);
472       return I == Temporaries.end() ? nullptr : &I->second;
473     }
474     APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
475   };
476 
477   /// Temporarily override 'this'.
478   class ThisOverrideRAII {
479   public:
480     ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
481         : Frame(Frame), OldThis(Frame.This) {
482       if (Enable)
483         Frame.This = NewThis;
484     }
485     ~ThisOverrideRAII() {
486       Frame.This = OldThis;
487     }
488   private:
489     CallStackFrame &Frame;
490     const LValue *OldThis;
491   };
492 
493   /// A partial diagnostic which we might know in advance that we are not going
494   /// to emit.
495   class OptionalDiagnostic {
496     PartialDiagnostic *Diag;
497 
498   public:
499     explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
500       : Diag(Diag) {}
501 
502     template<typename T>
503     OptionalDiagnostic &operator<<(const T &v) {
504       if (Diag)
505         *Diag << v;
506       return *this;
507     }
508 
509     OptionalDiagnostic &operator<<(const APSInt &I) {
510       if (Diag) {
511         SmallVector<char, 32> Buffer;
512         I.toString(Buffer);
513         *Diag << StringRef(Buffer.data(), Buffer.size());
514       }
515       return *this;
516     }
517 
518     OptionalDiagnostic &operator<<(const APFloat &F) {
519       if (Diag) {
520         // FIXME: Force the precision of the source value down so we don't
521         // print digits which are usually useless (we don't really care here if
522         // we truncate a digit by accident in edge cases).  Ideally,
523         // APFloat::toString would automatically print the shortest
524         // representation which rounds to the correct value, but it's a bit
525         // tricky to implement.
526         unsigned precision =
527             llvm::APFloat::semanticsPrecision(F.getSemantics());
528         precision = (precision * 59 + 195) / 196;
529         SmallVector<char, 32> Buffer;
530         F.toString(Buffer, precision);
531         *Diag << StringRef(Buffer.data(), Buffer.size());
532       }
533       return *this;
534     }
535   };
536 
537   /// A cleanup, and a flag indicating whether it is lifetime-extended.
538   class Cleanup {
539     llvm::PointerIntPair<APValue*, 1, bool> Value;
540 
541   public:
542     Cleanup(APValue *Val, bool IsLifetimeExtended)
543         : Value(Val, IsLifetimeExtended) {}
544 
545     bool isLifetimeExtended() const { return Value.getInt(); }
546     void endLifetime() {
547       *Value.getPointer() = APValue();
548     }
549   };
550 
551   /// EvalInfo - This is a private struct used by the evaluator to capture
552   /// information about a subexpression as it is folded.  It retains information
553   /// about the AST context, but also maintains information about the folded
554   /// expression.
555   ///
556   /// If an expression could be evaluated, it is still possible it is not a C
557   /// "integer constant expression" or constant expression.  If not, this struct
558   /// captures information about how and why not.
559   ///
560   /// One bit of information passed *into* the request for constant folding
561   /// indicates whether the subexpression is "evaluated" or not according to C
562   /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
563   /// evaluate the expression regardless of what the RHS is, but C only allows
564   /// certain things in certain situations.
565   struct EvalInfo {
566     ASTContext &Ctx;
567 
568     /// EvalStatus - Contains information about the evaluation.
569     Expr::EvalStatus &EvalStatus;
570 
571     /// CurrentCall - The top of the constexpr call stack.
572     CallStackFrame *CurrentCall;
573 
574     /// CallStackDepth - The number of calls in the call stack right now.
575     unsigned CallStackDepth;
576 
577     /// NextCallIndex - The next call index to assign.
578     unsigned NextCallIndex;
579 
580     /// StepsLeft - The remaining number of evaluation steps we're permitted
581     /// to perform. This is essentially a limit for the number of statements
582     /// we will evaluate.
583     unsigned StepsLeft;
584 
585     /// BottomFrame - The frame in which evaluation started. This must be
586     /// initialized after CurrentCall and CallStackDepth.
587     CallStackFrame BottomFrame;
588 
589     /// A stack of values whose lifetimes end at the end of some surrounding
590     /// evaluation frame.
591     llvm::SmallVector<Cleanup, 16> CleanupStack;
592 
593     /// EvaluatingDecl - This is the declaration whose initializer is being
594     /// evaluated, if any.
595     APValue::LValueBase EvaluatingDecl;
596 
597     /// EvaluatingDeclValue - This is the value being constructed for the
598     /// declaration whose initializer is being evaluated, if any.
599     APValue *EvaluatingDeclValue;
600 
601     /// EvaluatingObject - Pair of the AST node that an lvalue represents and
602     /// the call index that that lvalue was allocated in.
603     typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
604 
605     /// EvaluatingConstructors - Set of objects that are currently being
606     /// constructed.
607     llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
608 
609     struct EvaluatingConstructorRAII {
610       EvalInfo &EI;
611       EvaluatingObject Object;
612       bool DidInsert;
613       EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
614           : EI(EI), Object(Object) {
615         DidInsert = EI.EvaluatingConstructors.insert(Object).second;
616       }
617       ~EvaluatingConstructorRAII() {
618         if (DidInsert) EI.EvaluatingConstructors.erase(Object);
619       }
620     };
621 
622     bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
623       return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
624     }
625 
626     /// The current array initialization index, if we're performing array
627     /// initialization.
628     uint64_t ArrayInitIndex = -1;
629 
630     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
631     /// notes attached to it will also be stored, otherwise they will not be.
632     bool HasActiveDiagnostic;
633 
634     /// \brief Have we emitted a diagnostic explaining why we couldn't constant
635     /// fold (not just why it's not strictly a constant expression)?
636     bool HasFoldFailureDiagnostic;
637 
638     /// \brief Whether or not we're currently speculatively evaluating.
639     bool IsSpeculativelyEvaluating;
640 
641     enum EvaluationMode {
642       /// Evaluate as a constant expression. Stop if we find that the expression
643       /// is not a constant expression.
644       EM_ConstantExpression,
645 
646       /// Evaluate as a potential constant expression. Keep going if we hit a
647       /// construct that we can't evaluate yet (because we don't yet know the
648       /// value of something) but stop if we hit something that could never be
649       /// a constant expression.
650       EM_PotentialConstantExpression,
651 
652       /// Fold the expression to a constant. Stop if we hit a side-effect that
653       /// we can't model.
654       EM_ConstantFold,
655 
656       /// Evaluate the expression looking for integer overflow and similar
657       /// issues. Don't worry about side-effects, and try to visit all
658       /// subexpressions.
659       EM_EvaluateForOverflow,
660 
661       /// Evaluate in any way we know how. Don't worry about side-effects that
662       /// can't be modeled.
663       EM_IgnoreSideEffects,
664 
665       /// Evaluate as a constant expression. Stop if we find that the expression
666       /// is not a constant expression. Some expressions can be retried in the
667       /// optimizer if we don't constant fold them here, but in an unevaluated
668       /// context we try to fold them immediately since the optimizer never
669       /// gets a chance to look at it.
670       EM_ConstantExpressionUnevaluated,
671 
672       /// Evaluate as a potential constant expression. Keep going if we hit a
673       /// construct that we can't evaluate yet (because we don't yet know the
674       /// value of something) but stop if we hit something that could never be
675       /// a constant expression. Some expressions can be retried in the
676       /// optimizer if we don't constant fold them here, but in an unevaluated
677       /// context we try to fold them immediately since the optimizer never
678       /// gets a chance to look at it.
679       EM_PotentialConstantExpressionUnevaluated,
680 
681       /// Evaluate as a constant expression. In certain scenarios, if:
682       /// - we find a MemberExpr with a base that can't be evaluated, or
683       /// - we find a variable initialized with a call to a function that has
684       ///   the alloc_size attribute on it
685       /// then we may consider evaluation to have succeeded.
686       ///
687       /// In either case, the LValue returned shall have an invalid base; in the
688       /// former, the base will be the invalid MemberExpr, in the latter, the
689       /// base will be either the alloc_size CallExpr or a CastExpr wrapping
690       /// said CallExpr.
691       EM_OffsetFold,
692     } EvalMode;
693 
694     /// Are we checking whether the expression is a potential constant
695     /// expression?
696     bool checkingPotentialConstantExpression() const {
697       return EvalMode == EM_PotentialConstantExpression ||
698              EvalMode == EM_PotentialConstantExpressionUnevaluated;
699     }
700 
701     /// Are we checking an expression for overflow?
702     // FIXME: We should check for any kind of undefined or suspicious behavior
703     // in such constructs, not just overflow.
704     bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
705 
706     EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
707       : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
708         CallStackDepth(0), NextCallIndex(1),
709         StepsLeft(getLangOpts().ConstexprStepLimit),
710         BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
711         EvaluatingDecl((const ValueDecl *)nullptr),
712         EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
713         HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
714         EvalMode(Mode) {}
715 
716     void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
717       EvaluatingDecl = Base;
718       EvaluatingDeclValue = &Value;
719       EvaluatingConstructors.insert({Base, 0});
720     }
721 
722     const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
723 
724     bool CheckCallLimit(SourceLocation Loc) {
725       // Don't perform any constexpr calls (other than the call we're checking)
726       // when checking a potential constant expression.
727       if (checkingPotentialConstantExpression() && CallStackDepth > 1)
728         return false;
729       if (NextCallIndex == 0) {
730         // NextCallIndex has wrapped around.
731         FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
732         return false;
733       }
734       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
735         return true;
736       FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
737         << getLangOpts().ConstexprCallDepth;
738       return false;
739     }
740 
741     CallStackFrame *getCallFrame(unsigned CallIndex) {
742       assert(CallIndex && "no call index in getCallFrame");
743       // We will eventually hit BottomFrame, which has Index 1, so Frame can't
744       // be null in this loop.
745       CallStackFrame *Frame = CurrentCall;
746       while (Frame->Index > CallIndex)
747         Frame = Frame->Caller;
748       return (Frame->Index == CallIndex) ? Frame : nullptr;
749     }
750 
751     bool nextStep(const Stmt *S) {
752       if (!StepsLeft) {
753         FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
754         return false;
755       }
756       --StepsLeft;
757       return true;
758     }
759 
760   private:
761     /// Add a diagnostic to the diagnostics list.
762     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
763       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
764       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
765       return EvalStatus.Diag->back().second;
766     }
767 
768     /// Add notes containing a call stack to the current point of evaluation.
769     void addCallStack(unsigned Limit);
770 
771   private:
772     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
773                             unsigned ExtraNotes, bool IsCCEDiag) {
774 
775       if (EvalStatus.Diag) {
776         // If we have a prior diagnostic, it will be noting that the expression
777         // isn't a constant expression. This diagnostic is more important,
778         // unless we require this evaluation to produce a constant expression.
779         //
780         // FIXME: We might want to show both diagnostics to the user in
781         // EM_ConstantFold mode.
782         if (!EvalStatus.Diag->empty()) {
783           switch (EvalMode) {
784           case EM_ConstantFold:
785           case EM_IgnoreSideEffects:
786           case EM_EvaluateForOverflow:
787             if (!HasFoldFailureDiagnostic)
788               break;
789             // We've already failed to fold something. Keep that diagnostic.
790             LLVM_FALLTHROUGH;
791           case EM_ConstantExpression:
792           case EM_PotentialConstantExpression:
793           case EM_ConstantExpressionUnevaluated:
794           case EM_PotentialConstantExpressionUnevaluated:
795           case EM_OffsetFold:
796             HasActiveDiagnostic = false;
797             return OptionalDiagnostic();
798           }
799         }
800 
801         unsigned CallStackNotes = CallStackDepth - 1;
802         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
803         if (Limit)
804           CallStackNotes = std::min(CallStackNotes, Limit + 1);
805         if (checkingPotentialConstantExpression())
806           CallStackNotes = 0;
807 
808         HasActiveDiagnostic = true;
809         HasFoldFailureDiagnostic = !IsCCEDiag;
810         EvalStatus.Diag->clear();
811         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
812         addDiag(Loc, DiagId);
813         if (!checkingPotentialConstantExpression())
814           addCallStack(Limit);
815         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
816       }
817       HasActiveDiagnostic = false;
818       return OptionalDiagnostic();
819     }
820   public:
821     // Diagnose that the evaluation could not be folded (FF => FoldFailure)
822     OptionalDiagnostic
823     FFDiag(SourceLocation Loc,
824           diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
825           unsigned ExtraNotes = 0) {
826       return Diag(Loc, DiagId, ExtraNotes, false);
827     }
828 
829     OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
830                               = diag::note_invalid_subexpr_in_const_expr,
831                             unsigned ExtraNotes = 0) {
832       if (EvalStatus.Diag)
833         return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
834       HasActiveDiagnostic = false;
835       return OptionalDiagnostic();
836     }
837 
838     /// Diagnose that the evaluation does not produce a C++11 core constant
839     /// expression.
840     ///
841     /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
842     /// EM_PotentialConstantExpression mode and we produce one of these.
843     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
844                                  = diag::note_invalid_subexpr_in_const_expr,
845                                unsigned ExtraNotes = 0) {
846       // Don't override a previous diagnostic. Don't bother collecting
847       // diagnostics if we're evaluating for overflow.
848       if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
849         HasActiveDiagnostic = false;
850         return OptionalDiagnostic();
851       }
852       return Diag(Loc, DiagId, ExtraNotes, true);
853     }
854     OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
855                                  = diag::note_invalid_subexpr_in_const_expr,
856                                unsigned ExtraNotes = 0) {
857       return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
858     }
859     /// Add a note to a prior diagnostic.
860     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
861       if (!HasActiveDiagnostic)
862         return OptionalDiagnostic();
863       return OptionalDiagnostic(&addDiag(Loc, DiagId));
864     }
865 
866     /// Add a stack of notes to a prior diagnostic.
867     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
868       if (HasActiveDiagnostic) {
869         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
870                                 Diags.begin(), Diags.end());
871       }
872     }
873 
874     /// Should we continue evaluation after encountering a side-effect that we
875     /// couldn't model?
876     bool keepEvaluatingAfterSideEffect() {
877       switch (EvalMode) {
878       case EM_PotentialConstantExpression:
879       case EM_PotentialConstantExpressionUnevaluated:
880       case EM_EvaluateForOverflow:
881       case EM_IgnoreSideEffects:
882         return true;
883 
884       case EM_ConstantExpression:
885       case EM_ConstantExpressionUnevaluated:
886       case EM_ConstantFold:
887       case EM_OffsetFold:
888         return false;
889       }
890       llvm_unreachable("Missed EvalMode case");
891     }
892 
893     /// Note that we have had a side-effect, and determine whether we should
894     /// keep evaluating.
895     bool noteSideEffect() {
896       EvalStatus.HasSideEffects = true;
897       return keepEvaluatingAfterSideEffect();
898     }
899 
900     /// Should we continue evaluation after encountering undefined behavior?
901     bool keepEvaluatingAfterUndefinedBehavior() {
902       switch (EvalMode) {
903       case EM_EvaluateForOverflow:
904       case EM_IgnoreSideEffects:
905       case EM_ConstantFold:
906       case EM_OffsetFold:
907         return true;
908 
909       case EM_PotentialConstantExpression:
910       case EM_PotentialConstantExpressionUnevaluated:
911       case EM_ConstantExpression:
912       case EM_ConstantExpressionUnevaluated:
913         return false;
914       }
915       llvm_unreachable("Missed EvalMode case");
916     }
917 
918     /// Note that we hit something that was technically undefined behavior, but
919     /// that we can evaluate past it (such as signed overflow or floating-point
920     /// division by zero.)
921     bool noteUndefinedBehavior() {
922       EvalStatus.HasUndefinedBehavior = true;
923       return keepEvaluatingAfterUndefinedBehavior();
924     }
925 
926     /// Should we continue evaluation as much as possible after encountering a
927     /// construct which can't be reduced to a value?
928     bool keepEvaluatingAfterFailure() {
929       if (!StepsLeft)
930         return false;
931 
932       switch (EvalMode) {
933       case EM_PotentialConstantExpression:
934       case EM_PotentialConstantExpressionUnevaluated:
935       case EM_EvaluateForOverflow:
936         return true;
937 
938       case EM_ConstantExpression:
939       case EM_ConstantExpressionUnevaluated:
940       case EM_ConstantFold:
941       case EM_IgnoreSideEffects:
942       case EM_OffsetFold:
943         return false;
944       }
945       llvm_unreachable("Missed EvalMode case");
946     }
947 
948     /// Notes that we failed to evaluate an expression that other expressions
949     /// directly depend on, and determine if we should keep evaluating. This
950     /// should only be called if we actually intend to keep evaluating.
951     ///
952     /// Call noteSideEffect() instead if we may be able to ignore the value that
953     /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
954     ///
955     /// (Foo(), 1)      // use noteSideEffect
956     /// (Foo() || true) // use noteSideEffect
957     /// Foo() + 1       // use noteFailure
958     LLVM_NODISCARD bool noteFailure() {
959       // Failure when evaluating some expression often means there is some
960       // subexpression whose evaluation was skipped. Therefore, (because we
961       // don't track whether we skipped an expression when unwinding after an
962       // evaluation failure) every evaluation failure that bubbles up from a
963       // subexpression implies that a side-effect has potentially happened. We
964       // skip setting the HasSideEffects flag to true until we decide to
965       // continue evaluating after that point, which happens here.
966       bool KeepGoing = keepEvaluatingAfterFailure();
967       EvalStatus.HasSideEffects |= KeepGoing;
968       return KeepGoing;
969     }
970 
971     class ArrayInitLoopIndex {
972       EvalInfo &Info;
973       uint64_t OuterIndex;
974 
975     public:
976       ArrayInitLoopIndex(EvalInfo &Info)
977           : Info(Info), OuterIndex(Info.ArrayInitIndex) {
978         Info.ArrayInitIndex = 0;
979       }
980       ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
981 
982       operator uint64_t&() { return Info.ArrayInitIndex; }
983     };
984   };
985 
986   /// Object used to treat all foldable expressions as constant expressions.
987   struct FoldConstant {
988     EvalInfo &Info;
989     bool Enabled;
990     bool HadNoPriorDiags;
991     EvalInfo::EvaluationMode OldMode;
992 
993     explicit FoldConstant(EvalInfo &Info, bool Enabled)
994       : Info(Info),
995         Enabled(Enabled),
996         HadNoPriorDiags(Info.EvalStatus.Diag &&
997                         Info.EvalStatus.Diag->empty() &&
998                         !Info.EvalStatus.HasSideEffects),
999         OldMode(Info.EvalMode) {
1000       if (Enabled &&
1001           (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1002            Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
1003         Info.EvalMode = EvalInfo::EM_ConstantFold;
1004     }
1005     void keepDiagnostics() { Enabled = false; }
1006     ~FoldConstant() {
1007       if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
1008           !Info.EvalStatus.HasSideEffects)
1009         Info.EvalStatus.Diag->clear();
1010       Info.EvalMode = OldMode;
1011     }
1012   };
1013 
1014   /// RAII object used to treat the current evaluation as the correct pointer
1015   /// offset fold for the current EvalMode
1016   struct FoldOffsetRAII {
1017     EvalInfo &Info;
1018     EvalInfo::EvaluationMode OldMode;
1019     explicit FoldOffsetRAII(EvalInfo &Info)
1020         : Info(Info), OldMode(Info.EvalMode) {
1021       if (!Info.checkingPotentialConstantExpression())
1022         Info.EvalMode = EvalInfo::EM_OffsetFold;
1023     }
1024 
1025     ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1026   };
1027 
1028   /// RAII object used to optionally suppress diagnostics and side-effects from
1029   /// a speculative evaluation.
1030   class SpeculativeEvaluationRAII {
1031     EvalInfo *Info = nullptr;
1032     Expr::EvalStatus OldStatus;
1033     bool OldIsSpeculativelyEvaluating;
1034 
1035     void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
1036       Info = Other.Info;
1037       OldStatus = Other.OldStatus;
1038       OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
1039       Other.Info = nullptr;
1040     }
1041 
1042     void maybeRestoreState() {
1043       if (!Info)
1044         return;
1045 
1046       Info->EvalStatus = OldStatus;
1047       Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
1048     }
1049 
1050   public:
1051     SpeculativeEvaluationRAII() = default;
1052 
1053     SpeculativeEvaluationRAII(
1054         EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
1055         : Info(&Info), OldStatus(Info.EvalStatus),
1056           OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
1057       Info.EvalStatus.Diag = NewDiag;
1058       Info.IsSpeculativelyEvaluating = true;
1059     }
1060 
1061     SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1062     SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1063       moveFromAndCancel(std::move(Other));
1064     }
1065 
1066     SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1067       maybeRestoreState();
1068       moveFromAndCancel(std::move(Other));
1069       return *this;
1070     }
1071 
1072     ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
1073   };
1074 
1075   /// RAII object wrapping a full-expression or block scope, and handling
1076   /// the ending of the lifetime of temporaries created within it.
1077   template<bool IsFullExpression>
1078   class ScopeRAII {
1079     EvalInfo &Info;
1080     unsigned OldStackSize;
1081   public:
1082     ScopeRAII(EvalInfo &Info)
1083         : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1084     ~ScopeRAII() {
1085       // Body moved to a static method to encourage the compiler to inline away
1086       // instances of this class.
1087       cleanup(Info, OldStackSize);
1088     }
1089   private:
1090     static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1091       unsigned NewEnd = OldStackSize;
1092       for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1093            I != N; ++I) {
1094         if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1095           // Full-expression cleanup of a lifetime-extended temporary: nothing
1096           // to do, just move this cleanup to the right place in the stack.
1097           std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1098           ++NewEnd;
1099         } else {
1100           // End the lifetime of the object.
1101           Info.CleanupStack[I].endLifetime();
1102         }
1103       }
1104       Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1105                               Info.CleanupStack.end());
1106     }
1107   };
1108   typedef ScopeRAII<false> BlockScopeRAII;
1109   typedef ScopeRAII<true> FullExpressionRAII;
1110 }
1111 
1112 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1113                                          CheckSubobjectKind CSK) {
1114   if (Invalid)
1115     return false;
1116   if (isOnePastTheEnd()) {
1117     Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
1118       << CSK;
1119     setInvalid();
1120     return false;
1121   }
1122   // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1123   // must actually be at least one array element; even a VLA cannot have a
1124   // bound of zero. And if our index is nonzero, we already had a CCEDiag.
1125   return true;
1126 }
1127 
1128 void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1129                                                                 const Expr *E) {
1130   Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1131   // Do not set the designator as invalid: we can represent this situation,
1132   // and correct handling of __builtin_object_size requires us to do so.
1133 }
1134 
1135 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
1136                                                     const Expr *E,
1137                                                     const APSInt &N) {
1138   // If we're complaining, we must be able to statically determine the size of
1139   // the most derived array.
1140   if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
1141     Info.CCEDiag(E, diag::note_constexpr_array_index)
1142       << N << /*array*/ 0
1143       << static_cast<unsigned>(getMostDerivedArraySize());
1144   else
1145     Info.CCEDiag(E, diag::note_constexpr_array_index)
1146       << N << /*non-array*/ 1;
1147   setInvalid();
1148 }
1149 
1150 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1151                                const FunctionDecl *Callee, const LValue *This,
1152                                APValue *Arguments)
1153     : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1154       Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
1155   Info.CurrentCall = this;
1156   ++Info.CallStackDepth;
1157 }
1158 
1159 CallStackFrame::~CallStackFrame() {
1160   assert(Info.CurrentCall == this && "calls retired out of order");
1161   --Info.CallStackDepth;
1162   Info.CurrentCall = Caller;
1163 }
1164 
1165 APValue &CallStackFrame::createTemporary(const void *Key,
1166                                          bool IsLifetimeExtended) {
1167   APValue &Result = Temporaries[Key];
1168   assert(Result.isUninit() && "temporary created multiple times");
1169   Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1170   return Result;
1171 }
1172 
1173 static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
1174 
1175 void EvalInfo::addCallStack(unsigned Limit) {
1176   // Determine which calls to skip, if any.
1177   unsigned ActiveCalls = CallStackDepth - 1;
1178   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1179   if (Limit && Limit < ActiveCalls) {
1180     SkipStart = Limit / 2 + Limit % 2;
1181     SkipEnd = ActiveCalls - Limit / 2;
1182   }
1183 
1184   // Walk the call stack and add the diagnostics.
1185   unsigned CallIdx = 0;
1186   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1187        Frame = Frame->Caller, ++CallIdx) {
1188     // Skip this call?
1189     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1190       if (CallIdx == SkipStart) {
1191         // Note that we're skipping calls.
1192         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1193           << unsigned(ActiveCalls - Limit);
1194       }
1195       continue;
1196     }
1197 
1198     // Use a different note for an inheriting constructor, because from the
1199     // user's perspective it's not really a function at all.
1200     if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1201       if (CD->isInheritingConstructor()) {
1202         addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1203           << CD->getParent();
1204         continue;
1205       }
1206     }
1207 
1208     SmallVector<char, 128> Buffer;
1209     llvm::raw_svector_ostream Out(Buffer);
1210     describeCall(Frame, Out);
1211     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1212   }
1213 }
1214 
1215 namespace {
1216   struct ComplexValue {
1217   private:
1218     bool IsInt;
1219 
1220   public:
1221     APSInt IntReal, IntImag;
1222     APFloat FloatReal, FloatImag;
1223 
1224     ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
1225 
1226     void makeComplexFloat() { IsInt = false; }
1227     bool isComplexFloat() const { return !IsInt; }
1228     APFloat &getComplexFloatReal() { return FloatReal; }
1229     APFloat &getComplexFloatImag() { return FloatImag; }
1230 
1231     void makeComplexInt() { IsInt = true; }
1232     bool isComplexInt() const { return IsInt; }
1233     APSInt &getComplexIntReal() { return IntReal; }
1234     APSInt &getComplexIntImag() { return IntImag; }
1235 
1236     void moveInto(APValue &v) const {
1237       if (isComplexFloat())
1238         v = APValue(FloatReal, FloatImag);
1239       else
1240         v = APValue(IntReal, IntImag);
1241     }
1242     void setFrom(const APValue &v) {
1243       assert(v.isComplexFloat() || v.isComplexInt());
1244       if (v.isComplexFloat()) {
1245         makeComplexFloat();
1246         FloatReal = v.getComplexFloatReal();
1247         FloatImag = v.getComplexFloatImag();
1248       } else {
1249         makeComplexInt();
1250         IntReal = v.getComplexIntReal();
1251         IntImag = v.getComplexIntImag();
1252       }
1253     }
1254   };
1255 
1256   struct LValue {
1257     APValue::LValueBase Base;
1258     CharUnits Offset;
1259     unsigned InvalidBase : 1;
1260     unsigned CallIndex : 31;
1261     SubobjectDesignator Designator;
1262     bool IsNullPtr;
1263 
1264     const APValue::LValueBase getLValueBase() const { return Base; }
1265     CharUnits &getLValueOffset() { return Offset; }
1266     const CharUnits &getLValueOffset() const { return Offset; }
1267     unsigned getLValueCallIndex() const { return CallIndex; }
1268     SubobjectDesignator &getLValueDesignator() { return Designator; }
1269     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
1270     bool isNullPointer() const { return IsNullPtr;}
1271 
1272     void moveInto(APValue &V) const {
1273       if (Designator.Invalid)
1274         V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1275                     IsNullPtr);
1276       else {
1277         assert(!InvalidBase && "APValues can't handle invalid LValue bases");
1278         V = APValue(Base, Offset, Designator.Entries,
1279                     Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
1280       }
1281     }
1282     void setFrom(ASTContext &Ctx, const APValue &V) {
1283       assert(V.isLValue() && "Setting LValue from a non-LValue?");
1284       Base = V.getLValueBase();
1285       Offset = V.getLValueOffset();
1286       InvalidBase = false;
1287       CallIndex = V.getLValueCallIndex();
1288       Designator = SubobjectDesignator(Ctx, V);
1289       IsNullPtr = V.isNullPointer();
1290     }
1291 
1292     void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
1293 #ifndef NDEBUG
1294       // We only allow a few types of invalid bases. Enforce that here.
1295       if (BInvalid) {
1296         const auto *E = B.get<const Expr *>();
1297         assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1298                "Unexpected type of invalid base");
1299       }
1300 #endif
1301 
1302       Base = B;
1303       Offset = CharUnits::fromQuantity(0);
1304       InvalidBase = BInvalid;
1305       CallIndex = I;
1306       Designator = SubobjectDesignator(getType(B));
1307       IsNullPtr = false;
1308     }
1309 
1310     void setNull(QualType PointerTy, uint64_t TargetVal) {
1311       Base = (Expr *)nullptr;
1312       Offset = CharUnits::fromQuantity(TargetVal);
1313       InvalidBase = false;
1314       CallIndex = 0;
1315       Designator = SubobjectDesignator(PointerTy->getPointeeType());
1316       IsNullPtr = true;
1317     }
1318 
1319     void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1320       set(B, I, true);
1321     }
1322 
1323     // Check that this LValue is not based on a null pointer. If it is, produce
1324     // a diagnostic and mark the designator as invalid.
1325     bool checkNullPointer(EvalInfo &Info, const Expr *E,
1326                           CheckSubobjectKind CSK) {
1327       if (Designator.Invalid)
1328         return false;
1329       if (IsNullPtr) {
1330         Info.CCEDiag(E, diag::note_constexpr_null_subobject)
1331           << CSK;
1332         Designator.setInvalid();
1333         return false;
1334       }
1335       return true;
1336     }
1337 
1338     // Check this LValue refers to an object. If not, set the designator to be
1339     // invalid and emit a diagnostic.
1340     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
1341       return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
1342              Designator.checkSubobject(Info, E, CSK);
1343     }
1344 
1345     void addDecl(EvalInfo &Info, const Expr *E,
1346                  const Decl *D, bool Virtual = false) {
1347       if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1348         Designator.addDeclUnchecked(D, Virtual);
1349     }
1350     void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1351       if (!Designator.Entries.empty()) {
1352         Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1353         Designator.setInvalid();
1354         return;
1355       }
1356       if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1357         assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1358         Designator.FirstEntryIsAnUnsizedArray = true;
1359         Designator.addUnsizedArrayUnchecked(ElemTy);
1360       }
1361     }
1362     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
1363       if (checkSubobject(Info, E, CSK_ArrayToPointer))
1364         Designator.addArrayUnchecked(CAT);
1365     }
1366     void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
1367       if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1368         Designator.addComplexUnchecked(EltTy, Imag);
1369     }
1370     void clearIsNullPointer() {
1371       IsNullPtr = false;
1372     }
1373     void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1374                               const APSInt &Index, CharUnits ElementSize) {
1375       // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1376       // but we're not required to diagnose it and it's valid in C++.)
1377       if (!Index)
1378         return;
1379 
1380       // Compute the new offset in the appropriate width, wrapping at 64 bits.
1381       // FIXME: When compiling for a 32-bit target, we should use 32-bit
1382       // offsets.
1383       uint64_t Offset64 = Offset.getQuantity();
1384       uint64_t ElemSize64 = ElementSize.getQuantity();
1385       uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1386       Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1387 
1388       if (checkNullPointer(Info, E, CSK_ArrayIndex))
1389         Designator.adjustIndex(Info, E, Index);
1390       clearIsNullPointer();
1391     }
1392     void adjustOffset(CharUnits N) {
1393       Offset += N;
1394       if (N.getQuantity())
1395         clearIsNullPointer();
1396     }
1397   };
1398 
1399   struct MemberPtr {
1400     MemberPtr() {}
1401     explicit MemberPtr(const ValueDecl *Decl) :
1402       DeclAndIsDerivedMember(Decl, false), Path() {}
1403 
1404     /// The member or (direct or indirect) field referred to by this member
1405     /// pointer, or 0 if this is a null member pointer.
1406     const ValueDecl *getDecl() const {
1407       return DeclAndIsDerivedMember.getPointer();
1408     }
1409     /// Is this actually a member of some type derived from the relevant class?
1410     bool isDerivedMember() const {
1411       return DeclAndIsDerivedMember.getInt();
1412     }
1413     /// Get the class which the declaration actually lives in.
1414     const CXXRecordDecl *getContainingRecord() const {
1415       return cast<CXXRecordDecl>(
1416           DeclAndIsDerivedMember.getPointer()->getDeclContext());
1417     }
1418 
1419     void moveInto(APValue &V) const {
1420       V = APValue(getDecl(), isDerivedMember(), Path);
1421     }
1422     void setFrom(const APValue &V) {
1423       assert(V.isMemberPointer());
1424       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1425       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1426       Path.clear();
1427       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1428       Path.insert(Path.end(), P.begin(), P.end());
1429     }
1430 
1431     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1432     /// whether the member is a member of some class derived from the class type
1433     /// of the member pointer.
1434     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1435     /// Path - The path of base/derived classes from the member declaration's
1436     /// class (exclusive) to the class type of the member pointer (inclusive).
1437     SmallVector<const CXXRecordDecl*, 4> Path;
1438 
1439     /// Perform a cast towards the class of the Decl (either up or down the
1440     /// hierarchy).
1441     bool castBack(const CXXRecordDecl *Class) {
1442       assert(!Path.empty());
1443       const CXXRecordDecl *Expected;
1444       if (Path.size() >= 2)
1445         Expected = Path[Path.size() - 2];
1446       else
1447         Expected = getContainingRecord();
1448       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1449         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1450         // if B does not contain the original member and is not a base or
1451         // derived class of the class containing the original member, the result
1452         // of the cast is undefined.
1453         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1454         // (D::*). We consider that to be a language defect.
1455         return false;
1456       }
1457       Path.pop_back();
1458       return true;
1459     }
1460     /// Perform a base-to-derived member pointer cast.
1461     bool castToDerived(const CXXRecordDecl *Derived) {
1462       if (!getDecl())
1463         return true;
1464       if (!isDerivedMember()) {
1465         Path.push_back(Derived);
1466         return true;
1467       }
1468       if (!castBack(Derived))
1469         return false;
1470       if (Path.empty())
1471         DeclAndIsDerivedMember.setInt(false);
1472       return true;
1473     }
1474     /// Perform a derived-to-base member pointer cast.
1475     bool castToBase(const CXXRecordDecl *Base) {
1476       if (!getDecl())
1477         return true;
1478       if (Path.empty())
1479         DeclAndIsDerivedMember.setInt(true);
1480       if (isDerivedMember()) {
1481         Path.push_back(Base);
1482         return true;
1483       }
1484       return castBack(Base);
1485     }
1486   };
1487 
1488   /// Compare two member pointers, which are assumed to be of the same type.
1489   static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1490     if (!LHS.getDecl() || !RHS.getDecl())
1491       return !LHS.getDecl() && !RHS.getDecl();
1492     if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1493       return false;
1494     return LHS.Path == RHS.Path;
1495   }
1496 }
1497 
1498 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
1499 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1500                             const LValue &This, const Expr *E,
1501                             bool AllowNonLiteralTypes = false);
1502 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1503                            bool InvalidBaseOK = false);
1504 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1505                             bool InvalidBaseOK = false);
1506 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1507                                   EvalInfo &Info);
1508 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
1509 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
1510 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
1511                                     EvalInfo &Info);
1512 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
1513 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
1514 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1515                            EvalInfo &Info);
1516 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
1517 
1518 //===----------------------------------------------------------------------===//
1519 // Misc utilities
1520 //===----------------------------------------------------------------------===//
1521 
1522 /// Negate an APSInt in place, converting it to a signed form if necessary, and
1523 /// preserving its value (by extending by up to one bit as needed).
1524 static void negateAsSigned(APSInt &Int) {
1525   if (Int.isUnsigned() || Int.isMinSignedValue()) {
1526     Int = Int.extend(Int.getBitWidth() + 1);
1527     Int.setIsSigned(true);
1528   }
1529   Int = -Int;
1530 }
1531 
1532 /// Produce a string describing the given constexpr call.
1533 static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1534   unsigned ArgIndex = 0;
1535   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1536                       !isa<CXXConstructorDecl>(Frame->Callee) &&
1537                       cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1538 
1539   if (!IsMemberCall)
1540     Out << *Frame->Callee << '(';
1541 
1542   if (Frame->This && IsMemberCall) {
1543     APValue Val;
1544     Frame->This->moveInto(Val);
1545     Val.printPretty(Out, Frame->Info.Ctx,
1546                     Frame->This->Designator.MostDerivedType);
1547     // FIXME: Add parens around Val if needed.
1548     Out << "->" << *Frame->Callee << '(';
1549     IsMemberCall = false;
1550   }
1551 
1552   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1553        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1554     if (ArgIndex > (unsigned)IsMemberCall)
1555       Out << ", ";
1556 
1557     const ParmVarDecl *Param = *I;
1558     const APValue &Arg = Frame->Arguments[ArgIndex];
1559     Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1560 
1561     if (ArgIndex == 0 && IsMemberCall)
1562       Out << "->" << *Frame->Callee << '(';
1563   }
1564 
1565   Out << ')';
1566 }
1567 
1568 /// Evaluate an expression to see if it had side-effects, and discard its
1569 /// result.
1570 /// \return \c true if the caller should keep evaluating.
1571 static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
1572   APValue Scratch;
1573   if (!Evaluate(Scratch, Info, E))
1574     // We don't need the value, but we might have skipped a side effect here.
1575     return Info.noteSideEffect();
1576   return true;
1577 }
1578 
1579 /// Should this call expression be treated as a string literal?
1580 static bool IsStringLiteralCall(const CallExpr *E) {
1581   unsigned Builtin = E->getBuiltinCallee();
1582   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1583           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1584 }
1585 
1586 static bool IsGlobalLValue(APValue::LValueBase B) {
1587   // C++11 [expr.const]p3 An address constant expression is a prvalue core
1588   // constant expression of pointer type that evaluates to...
1589 
1590   // ... a null pointer value, or a prvalue core constant expression of type
1591   // std::nullptr_t.
1592   if (!B) return true;
1593 
1594   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1595     // ... the address of an object with static storage duration,
1596     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1597       return VD->hasGlobalStorage();
1598     // ... the address of a function,
1599     return isa<FunctionDecl>(D);
1600   }
1601 
1602   const Expr *E = B.get<const Expr*>();
1603   switch (E->getStmtClass()) {
1604   default:
1605     return false;
1606   case Expr::CompoundLiteralExprClass: {
1607     const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1608     return CLE->isFileScope() && CLE->isLValue();
1609   }
1610   case Expr::MaterializeTemporaryExprClass:
1611     // A materialized temporary might have been lifetime-extended to static
1612     // storage duration.
1613     return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
1614   // A string literal has static storage duration.
1615   case Expr::StringLiteralClass:
1616   case Expr::PredefinedExprClass:
1617   case Expr::ObjCStringLiteralClass:
1618   case Expr::ObjCEncodeExprClass:
1619   case Expr::CXXTypeidExprClass:
1620   case Expr::CXXUuidofExprClass:
1621     return true;
1622   case Expr::CallExprClass:
1623     return IsStringLiteralCall(cast<CallExpr>(E));
1624   // For GCC compatibility, &&label has static storage duration.
1625   case Expr::AddrLabelExprClass:
1626     return true;
1627   // A Block literal expression may be used as the initialization value for
1628   // Block variables at global or local static scope.
1629   case Expr::BlockExprClass:
1630     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
1631   case Expr::ImplicitValueInitExprClass:
1632     // FIXME:
1633     // We can never form an lvalue with an implicit value initialization as its
1634     // base through expression evaluation, so these only appear in one case: the
1635     // implicit variable declaration we invent when checking whether a constexpr
1636     // constructor can produce a constant expression. We must assume that such
1637     // an expression might be a global lvalue.
1638     return true;
1639   }
1640 }
1641 
1642 static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1643   assert(Base && "no location for a null lvalue");
1644   const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1645   if (VD)
1646     Info.Note(VD->getLocation(), diag::note_declared_at);
1647   else
1648     Info.Note(Base.get<const Expr*>()->getExprLoc(),
1649               diag::note_constexpr_temporary_here);
1650 }
1651 
1652 /// Check that this reference or pointer core constant expression is a valid
1653 /// value for an address or reference constant expression. Return true if we
1654 /// can fold this expression, whether or not it's a constant expression.
1655 static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1656                                           QualType Type, const LValue &LVal) {
1657   bool IsReferenceType = Type->isReferenceType();
1658 
1659   APValue::LValueBase Base = LVal.getLValueBase();
1660   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1661 
1662   // Check that the object is a global. Note that the fake 'this' object we
1663   // manufacture when checking potential constant expressions is conservatively
1664   // assumed to be global here.
1665   if (!IsGlobalLValue(Base)) {
1666     if (Info.getLangOpts().CPlusPlus11) {
1667       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1668       Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
1669         << IsReferenceType << !Designator.Entries.empty()
1670         << !!VD << VD;
1671       NoteLValueLocation(Info, Base);
1672     } else {
1673       Info.FFDiag(Loc);
1674     }
1675     // Don't allow references to temporaries to escape.
1676     return false;
1677   }
1678   assert((Info.checkingPotentialConstantExpression() ||
1679           LVal.getLValueCallIndex() == 0) &&
1680          "have call index for global lvalue");
1681 
1682   if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1683     if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1684       // Check if this is a thread-local variable.
1685       if (Var->getTLSKind())
1686         return false;
1687 
1688       // A dllimport variable never acts like a constant.
1689       if (Var->hasAttr<DLLImportAttr>())
1690         return false;
1691     }
1692     if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1693       // __declspec(dllimport) must be handled very carefully:
1694       // We must never initialize an expression with the thunk in C++.
1695       // Doing otherwise would allow the same id-expression to yield
1696       // different addresses for the same function in different translation
1697       // units.  However, this means that we must dynamically initialize the
1698       // expression with the contents of the import address table at runtime.
1699       //
1700       // The C language has no notion of ODR; furthermore, it has no notion of
1701       // dynamic initialization.  This means that we are permitted to
1702       // perform initialization with the address of the thunk.
1703       if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
1704         return false;
1705     }
1706   }
1707 
1708   // Allow address constant expressions to be past-the-end pointers. This is
1709   // an extension: the standard requires them to point to an object.
1710   if (!IsReferenceType)
1711     return true;
1712 
1713   // A reference constant expression must refer to an object.
1714   if (!Base) {
1715     // FIXME: diagnostic
1716     Info.CCEDiag(Loc);
1717     return true;
1718   }
1719 
1720   // Does this refer one past the end of some object?
1721   if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
1722     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1723     Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
1724       << !Designator.Entries.empty() << !!VD << VD;
1725     NoteLValueLocation(Info, Base);
1726   }
1727 
1728   return true;
1729 }
1730 
1731 /// Member pointers are constant expressions unless they point to a
1732 /// non-virtual dllimport member function.
1733 static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1734                                                  SourceLocation Loc,
1735                                                  QualType Type,
1736                                                  const APValue &Value) {
1737   const ValueDecl *Member = Value.getMemberPointerDecl();
1738   const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1739   if (!FD)
1740     return true;
1741   return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1742 }
1743 
1744 /// Check that this core constant expression is of literal type, and if not,
1745 /// produce an appropriate diagnostic.
1746 static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
1747                              const LValue *This = nullptr) {
1748   if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
1749     return true;
1750 
1751   // C++1y: A constant initializer for an object o [...] may also invoke
1752   // constexpr constructors for o and its subobjects even if those objects
1753   // are of non-literal class types.
1754   //
1755   // C++11 missed this detail for aggregates, so classes like this:
1756   //   struct foo_t { union { int i; volatile int j; } u; };
1757   // are not (obviously) initializable like so:
1758   //   __attribute__((__require_constant_initialization__))
1759   //   static const foo_t x = {{0}};
1760   // because "i" is a subobject with non-literal initialization (due to the
1761   // volatile member of the union). See:
1762   //   http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1763   // Therefore, we use the C++1y behavior.
1764   if (This && Info.EvaluatingDecl == This->getLValueBase())
1765     return true;
1766 
1767   // Prvalue constant expressions must be of literal types.
1768   if (Info.getLangOpts().CPlusPlus11)
1769     Info.FFDiag(E, diag::note_constexpr_nonliteral)
1770       << E->getType();
1771   else
1772     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1773   return false;
1774 }
1775 
1776 /// Check that this core constant expression value is a valid value for a
1777 /// constant expression. If not, report an appropriate diagnostic. Does not
1778 /// check that the expression is of literal type.
1779 static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1780                                     QualType Type, const APValue &Value) {
1781   if (Value.isUninit()) {
1782     Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
1783       << true << Type;
1784     return false;
1785   }
1786 
1787   // We allow _Atomic(T) to be initialized from anything that T can be
1788   // initialized from.
1789   if (const AtomicType *AT = Type->getAs<AtomicType>())
1790     Type = AT->getValueType();
1791 
1792   // Core issue 1454: For a literal constant expression of array or class type,
1793   // each subobject of its value shall have been initialized by a constant
1794   // expression.
1795   if (Value.isArray()) {
1796     QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1797     for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1798       if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1799                                    Value.getArrayInitializedElt(I)))
1800         return false;
1801     }
1802     if (!Value.hasArrayFiller())
1803       return true;
1804     return CheckConstantExpression(Info, DiagLoc, EltTy,
1805                                    Value.getArrayFiller());
1806   }
1807   if (Value.isUnion() && Value.getUnionField()) {
1808     return CheckConstantExpression(Info, DiagLoc,
1809                                    Value.getUnionField()->getType(),
1810                                    Value.getUnionValue());
1811   }
1812   if (Value.isStruct()) {
1813     RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1814     if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1815       unsigned BaseIndex = 0;
1816       for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1817              End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1818         if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1819                                      Value.getStructBase(BaseIndex)))
1820           return false;
1821       }
1822     }
1823     for (const auto *I : RD->fields()) {
1824       if (I->isUnnamedBitfield())
1825         continue;
1826 
1827       if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1828                                    Value.getStructField(I->getFieldIndex())))
1829         return false;
1830     }
1831   }
1832 
1833   if (Value.isLValue()) {
1834     LValue LVal;
1835     LVal.setFrom(Info.Ctx, Value);
1836     return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1837   }
1838 
1839   if (Value.isMemberPointer())
1840     return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1841 
1842   // Everything else is fine.
1843   return true;
1844 }
1845 
1846 static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
1847   return LVal.Base.dyn_cast<const ValueDecl*>();
1848 }
1849 
1850 static bool IsLiteralLValue(const LValue &Value) {
1851   if (Value.CallIndex)
1852     return false;
1853   const Expr *E = Value.Base.dyn_cast<const Expr*>();
1854   return E && !isa<MaterializeTemporaryExpr>(E);
1855 }
1856 
1857 static bool IsWeakLValue(const LValue &Value) {
1858   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1859   return Decl && Decl->isWeak();
1860 }
1861 
1862 static bool isZeroSized(const LValue &Value) {
1863   const ValueDecl *Decl = GetLValueBaseDecl(Value);
1864   if (Decl && isa<VarDecl>(Decl)) {
1865     QualType Ty = Decl->getType();
1866     if (Ty->isArrayType())
1867       return Ty->isIncompleteType() ||
1868              Decl->getASTContext().getTypeSize(Ty) == 0;
1869   }
1870   return false;
1871 }
1872 
1873 static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
1874   // A null base expression indicates a null pointer.  These are always
1875   // evaluatable, and they are false unless the offset is zero.
1876   if (!Value.getLValueBase()) {
1877     Result = !Value.getLValueOffset().isZero();
1878     return true;
1879   }
1880 
1881   // We have a non-null base.  These are generally known to be true, but if it's
1882   // a weak declaration it can be null at runtime.
1883   Result = true;
1884   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1885   return !Decl || !Decl->isWeak();
1886 }
1887 
1888 static bool HandleConversionToBool(const APValue &Val, bool &Result) {
1889   switch (Val.getKind()) {
1890   case APValue::Uninitialized:
1891     return false;
1892   case APValue::Int:
1893     Result = Val.getInt().getBoolValue();
1894     return true;
1895   case APValue::Float:
1896     Result = !Val.getFloat().isZero();
1897     return true;
1898   case APValue::ComplexInt:
1899     Result = Val.getComplexIntReal().getBoolValue() ||
1900              Val.getComplexIntImag().getBoolValue();
1901     return true;
1902   case APValue::ComplexFloat:
1903     Result = !Val.getComplexFloatReal().isZero() ||
1904              !Val.getComplexFloatImag().isZero();
1905     return true;
1906   case APValue::LValue:
1907     return EvalPointerValueAsBool(Val, Result);
1908   case APValue::MemberPointer:
1909     Result = Val.getMemberPointerDecl();
1910     return true;
1911   case APValue::Vector:
1912   case APValue::Array:
1913   case APValue::Struct:
1914   case APValue::Union:
1915   case APValue::AddrLabelDiff:
1916     return false;
1917   }
1918 
1919   llvm_unreachable("unknown APValue kind");
1920 }
1921 
1922 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1923                                        EvalInfo &Info) {
1924   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1925   APValue Val;
1926   if (!Evaluate(Val, Info, E))
1927     return false;
1928   return HandleConversionToBool(Val, Result);
1929 }
1930 
1931 template<typename T>
1932 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1933                            const T &SrcValue, QualType DestType) {
1934   Info.CCEDiag(E, diag::note_constexpr_overflow)
1935     << SrcValue << DestType;
1936   return Info.noteUndefinedBehavior();
1937 }
1938 
1939 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1940                                  QualType SrcType, const APFloat &Value,
1941                                  QualType DestType, APSInt &Result) {
1942   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1943   // Determine whether we are converting to unsigned or signed.
1944   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1945 
1946   Result = APSInt(DestWidth, !DestSigned);
1947   bool ignored;
1948   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1949       & APFloat::opInvalidOp)
1950     return HandleOverflow(Info, E, Value, DestType);
1951   return true;
1952 }
1953 
1954 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1955                                    QualType SrcType, QualType DestType,
1956                                    APFloat &Result) {
1957   APFloat Value = Result;
1958   bool ignored;
1959   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1960                      APFloat::rmNearestTiesToEven, &ignored)
1961       & APFloat::opOverflow)
1962     return HandleOverflow(Info, E, Value, DestType);
1963   return true;
1964 }
1965 
1966 static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1967                                  QualType DestType, QualType SrcType,
1968                                  const APSInt &Value) {
1969   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1970   APSInt Result = Value;
1971   // Figure out if this is a truncate, extend or noop cast.
1972   // If the input is signed, do a sign extend, noop, or truncate.
1973   Result = Result.extOrTrunc(DestWidth);
1974   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1975   return Result;
1976 }
1977 
1978 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1979                                  QualType SrcType, const APSInt &Value,
1980                                  QualType DestType, APFloat &Result) {
1981   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1982   if (Result.convertFromAPInt(Value, Value.isSigned(),
1983                               APFloat::rmNearestTiesToEven)
1984       & APFloat::opOverflow)
1985     return HandleOverflow(Info, E, Value, DestType);
1986   return true;
1987 }
1988 
1989 static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1990                                   APValue &Value, const FieldDecl *FD) {
1991   assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1992 
1993   if (!Value.isInt()) {
1994     // Trying to store a pointer-cast-to-integer into a bitfield.
1995     // FIXME: In this case, we should provide the diagnostic for casting
1996     // a pointer to an integer.
1997     assert(Value.isLValue() && "integral value neither int nor lvalue?");
1998     Info.FFDiag(E);
1999     return false;
2000   }
2001 
2002   APSInt &Int = Value.getInt();
2003   unsigned OldBitWidth = Int.getBitWidth();
2004   unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2005   if (NewBitWidth < OldBitWidth)
2006     Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2007   return true;
2008 }
2009 
2010 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2011                                   llvm::APInt &Res) {
2012   APValue SVal;
2013   if (!Evaluate(SVal, Info, E))
2014     return false;
2015   if (SVal.isInt()) {
2016     Res = SVal.getInt();
2017     return true;
2018   }
2019   if (SVal.isFloat()) {
2020     Res = SVal.getFloat().bitcastToAPInt();
2021     return true;
2022   }
2023   if (SVal.isVector()) {
2024     QualType VecTy = E->getType();
2025     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2026     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2027     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2028     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2029     Res = llvm::APInt::getNullValue(VecSize);
2030     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2031       APValue &Elt = SVal.getVectorElt(i);
2032       llvm::APInt EltAsInt;
2033       if (Elt.isInt()) {
2034         EltAsInt = Elt.getInt();
2035       } else if (Elt.isFloat()) {
2036         EltAsInt = Elt.getFloat().bitcastToAPInt();
2037       } else {
2038         // Don't try to handle vectors of anything other than int or float
2039         // (not sure if it's possible to hit this case).
2040         Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2041         return false;
2042       }
2043       unsigned BaseEltSize = EltAsInt.getBitWidth();
2044       if (BigEndian)
2045         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2046       else
2047         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2048     }
2049     return true;
2050   }
2051   // Give up if the input isn't an int, float, or vector.  For example, we
2052   // reject "(v4i16)(intptr_t)&a".
2053   Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2054   return false;
2055 }
2056 
2057 /// Perform the given integer operation, which is known to need at most BitWidth
2058 /// bits, and check for overflow in the original type (if that type was not an
2059 /// unsigned type).
2060 template<typename Operation>
2061 static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2062                                  const APSInt &LHS, const APSInt &RHS,
2063                                  unsigned BitWidth, Operation Op,
2064                                  APSInt &Result) {
2065   if (LHS.isUnsigned()) {
2066     Result = Op(LHS, RHS);
2067     return true;
2068   }
2069 
2070   APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
2071   Result = Value.trunc(LHS.getBitWidth());
2072   if (Result.extend(BitWidth) != Value) {
2073     if (Info.checkingForOverflow())
2074       Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
2075                                        diag::warn_integer_constant_overflow)
2076           << Result.toString(10) << E->getType();
2077     else
2078       return HandleOverflow(Info, E, Value, E->getType());
2079   }
2080   return true;
2081 }
2082 
2083 /// Perform the given binary integer operation.
2084 static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2085                               BinaryOperatorKind Opcode, APSInt RHS,
2086                               APSInt &Result) {
2087   switch (Opcode) {
2088   default:
2089     Info.FFDiag(E);
2090     return false;
2091   case BO_Mul:
2092     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2093                                 std::multiplies<APSInt>(), Result);
2094   case BO_Add:
2095     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2096                                 std::plus<APSInt>(), Result);
2097   case BO_Sub:
2098     return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2099                                 std::minus<APSInt>(), Result);
2100   case BO_And: Result = LHS & RHS; return true;
2101   case BO_Xor: Result = LHS ^ RHS; return true;
2102   case BO_Or:  Result = LHS | RHS; return true;
2103   case BO_Div:
2104   case BO_Rem:
2105     if (RHS == 0) {
2106       Info.FFDiag(E, diag::note_expr_divide_by_zero);
2107       return false;
2108     }
2109     Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2110     // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2111     // this operation and gives the two's complement result.
2112     if (RHS.isNegative() && RHS.isAllOnesValue() &&
2113         LHS.isSigned() && LHS.isMinSignedValue())
2114       return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2115                             E->getType());
2116     return true;
2117   case BO_Shl: {
2118     if (Info.getLangOpts().OpenCL)
2119       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2120       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2121                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2122                     RHS.isUnsigned());
2123     else if (RHS.isSigned() && RHS.isNegative()) {
2124       // During constant-folding, a negative shift is an opposite shift. Such
2125       // a shift is not a constant expression.
2126       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2127       RHS = -RHS;
2128       goto shift_right;
2129     }
2130   shift_left:
2131     // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2132     // the shifted type.
2133     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2134     if (SA != RHS) {
2135       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2136         << RHS << E->getType() << LHS.getBitWidth();
2137     } else if (LHS.isSigned()) {
2138       // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2139       // operand, and must not overflow the corresponding unsigned type.
2140       if (LHS.isNegative())
2141         Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2142       else if (LHS.countLeadingZeros() < SA)
2143         Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2144     }
2145     Result = LHS << SA;
2146     return true;
2147   }
2148   case BO_Shr: {
2149     if (Info.getLangOpts().OpenCL)
2150       // OpenCL 6.3j: shift values are effectively % word size of LHS.
2151       RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2152                     static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2153                     RHS.isUnsigned());
2154     else if (RHS.isSigned() && RHS.isNegative()) {
2155       // During constant-folding, a negative shift is an opposite shift. Such a
2156       // shift is not a constant expression.
2157       Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2158       RHS = -RHS;
2159       goto shift_left;
2160     }
2161   shift_right:
2162     // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2163     // shifted type.
2164     unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2165     if (SA != RHS)
2166       Info.CCEDiag(E, diag::note_constexpr_large_shift)
2167         << RHS << E->getType() << LHS.getBitWidth();
2168     Result = LHS >> SA;
2169     return true;
2170   }
2171 
2172   case BO_LT: Result = LHS < RHS; return true;
2173   case BO_GT: Result = LHS > RHS; return true;
2174   case BO_LE: Result = LHS <= RHS; return true;
2175   case BO_GE: Result = LHS >= RHS; return true;
2176   case BO_EQ: Result = LHS == RHS; return true;
2177   case BO_NE: Result = LHS != RHS; return true;
2178   }
2179 }
2180 
2181 /// Perform the given binary floating-point operation, in-place, on LHS.
2182 static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2183                                   APFloat &LHS, BinaryOperatorKind Opcode,
2184                                   const APFloat &RHS) {
2185   switch (Opcode) {
2186   default:
2187     Info.FFDiag(E);
2188     return false;
2189   case BO_Mul:
2190     LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2191     break;
2192   case BO_Add:
2193     LHS.add(RHS, APFloat::rmNearestTiesToEven);
2194     break;
2195   case BO_Sub:
2196     LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2197     break;
2198   case BO_Div:
2199     LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2200     break;
2201   }
2202 
2203   if (LHS.isInfinity() || LHS.isNaN()) {
2204     Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
2205     return Info.noteUndefinedBehavior();
2206   }
2207   return true;
2208 }
2209 
2210 /// Cast an lvalue referring to a base subobject to a derived class, by
2211 /// truncating the lvalue's path to the given length.
2212 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2213                                const RecordDecl *TruncatedType,
2214                                unsigned TruncatedElements) {
2215   SubobjectDesignator &D = Result.Designator;
2216 
2217   // Check we actually point to a derived class object.
2218   if (TruncatedElements == D.Entries.size())
2219     return true;
2220   assert(TruncatedElements >= D.MostDerivedPathLength &&
2221          "not casting to a derived class");
2222   if (!Result.checkSubobject(Info, E, CSK_Derived))
2223     return false;
2224 
2225   // Truncate the path to the subobject, and remove any derived-to-base offsets.
2226   const RecordDecl *RD = TruncatedType;
2227   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
2228     if (RD->isInvalidDecl()) return false;
2229     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2230     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
2231     if (isVirtualBaseClass(D.Entries[I]))
2232       Result.Offset -= Layout.getVBaseClassOffset(Base);
2233     else
2234       Result.Offset -= Layout.getBaseClassOffset(Base);
2235     RD = Base;
2236   }
2237   D.Entries.resize(TruncatedElements);
2238   return true;
2239 }
2240 
2241 static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2242                                    const CXXRecordDecl *Derived,
2243                                    const CXXRecordDecl *Base,
2244                                    const ASTRecordLayout *RL = nullptr) {
2245   if (!RL) {
2246     if (Derived->isInvalidDecl()) return false;
2247     RL = &Info.Ctx.getASTRecordLayout(Derived);
2248   }
2249 
2250   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
2251   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
2252   return true;
2253 }
2254 
2255 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
2256                              const CXXRecordDecl *DerivedDecl,
2257                              const CXXBaseSpecifier *Base) {
2258   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2259 
2260   if (!Base->isVirtual())
2261     return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
2262 
2263   SubobjectDesignator &D = Obj.Designator;
2264   if (D.Invalid)
2265     return false;
2266 
2267   // Extract most-derived object and corresponding type.
2268   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2269   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2270     return false;
2271 
2272   // Find the virtual base class.
2273   if (DerivedDecl->isInvalidDecl()) return false;
2274   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2275   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
2276   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
2277   return true;
2278 }
2279 
2280 static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2281                                  QualType Type, LValue &Result) {
2282   for (CastExpr::path_const_iterator PathI = E->path_begin(),
2283                                      PathE = E->path_end();
2284        PathI != PathE; ++PathI) {
2285     if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2286                           *PathI))
2287       return false;
2288     Type = (*PathI)->getType();
2289   }
2290   return true;
2291 }
2292 
2293 /// Update LVal to refer to the given field, which must be a member of the type
2294 /// currently described by LVal.
2295 static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
2296                                const FieldDecl *FD,
2297                                const ASTRecordLayout *RL = nullptr) {
2298   if (!RL) {
2299     if (FD->getParent()->isInvalidDecl()) return false;
2300     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
2301   }
2302 
2303   unsigned I = FD->getFieldIndex();
2304   LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
2305   LVal.addDecl(Info, E, FD);
2306   return true;
2307 }
2308 
2309 /// Update LVal to refer to the given indirect field.
2310 static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
2311                                        LValue &LVal,
2312                                        const IndirectFieldDecl *IFD) {
2313   for (const auto *C : IFD->chain())
2314     if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
2315       return false;
2316   return true;
2317 }
2318 
2319 /// Get the size of the given type in char units.
2320 static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2321                          QualType Type, CharUnits &Size) {
2322   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2323   // extension.
2324   if (Type->isVoidType() || Type->isFunctionType()) {
2325     Size = CharUnits::One();
2326     return true;
2327   }
2328 
2329   if (Type->isDependentType()) {
2330     Info.FFDiag(Loc);
2331     return false;
2332   }
2333 
2334   if (!Type->isConstantSizeType()) {
2335     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
2336     // FIXME: Better diagnostic.
2337     Info.FFDiag(Loc);
2338     return false;
2339   }
2340 
2341   Size = Info.Ctx.getTypeSizeInChars(Type);
2342   return true;
2343 }
2344 
2345 /// Update a pointer value to model pointer arithmetic.
2346 /// \param Info - Information about the ongoing evaluation.
2347 /// \param E - The expression being evaluated, for diagnostic purposes.
2348 /// \param LVal - The pointer value to be updated.
2349 /// \param EltTy - The pointee type represented by LVal.
2350 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
2351 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2352                                         LValue &LVal, QualType EltTy,
2353                                         APSInt Adjustment) {
2354   CharUnits SizeOfPointee;
2355   if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
2356     return false;
2357 
2358   LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
2359   return true;
2360 }
2361 
2362 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2363                                         LValue &LVal, QualType EltTy,
2364                                         int64_t Adjustment) {
2365   return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2366                                      APSInt::get(Adjustment));
2367 }
2368 
2369 /// Update an lvalue to refer to a component of a complex number.
2370 /// \param Info - Information about the ongoing evaluation.
2371 /// \param LVal - The lvalue to be updated.
2372 /// \param EltTy - The complex number's component type.
2373 /// \param Imag - False for the real component, true for the imaginary.
2374 static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2375                                        LValue &LVal, QualType EltTy,
2376                                        bool Imag) {
2377   if (Imag) {
2378     CharUnits SizeOfComponent;
2379     if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2380       return false;
2381     LVal.Offset += SizeOfComponent;
2382   }
2383   LVal.addComplex(Info, E, EltTy, Imag);
2384   return true;
2385 }
2386 
2387 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2388                                            QualType Type, const LValue &LVal,
2389                                            APValue &RVal);
2390 
2391 /// Try to evaluate the initializer for a variable declaration.
2392 ///
2393 /// \param Info   Information about the ongoing evaluation.
2394 /// \param E      An expression to be used when printing diagnostics.
2395 /// \param VD     The variable whose initializer should be obtained.
2396 /// \param Frame  The frame in which the variable was created. Must be null
2397 ///               if this variable is not local to the evaluation.
2398 /// \param Result Filled in with a pointer to the value of the variable.
2399 static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2400                                 const VarDecl *VD, CallStackFrame *Frame,
2401                                 APValue *&Result) {
2402 
2403   // If this is a parameter to an active constexpr function call, perform
2404   // argument substitution.
2405   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
2406     // Assume arguments of a potential constant expression are unknown
2407     // constant expressions.
2408     if (Info.checkingPotentialConstantExpression())
2409       return false;
2410     if (!Frame || !Frame->Arguments) {
2411       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2412       return false;
2413     }
2414     Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
2415     return true;
2416   }
2417 
2418   // If this is a local variable, dig out its value.
2419   if (Frame) {
2420     Result = Frame->getTemporary(VD);
2421     if (!Result) {
2422       // Assume variables referenced within a lambda's call operator that were
2423       // not declared within the call operator are captures and during checking
2424       // of a potential constant expression, assume they are unknown constant
2425       // expressions.
2426       assert(isLambdaCallOperator(Frame->Callee) &&
2427              (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2428              "missing value for local variable");
2429       if (Info.checkingPotentialConstantExpression())
2430         return false;
2431       // FIXME: implement capture evaluation during constant expr evaluation.
2432       Info.FFDiag(E->getLocStart(),
2433            diag::note_unimplemented_constexpr_lambda_feature_ast)
2434           << "captures not currently allowed";
2435       return false;
2436     }
2437     return true;
2438   }
2439 
2440   // Dig out the initializer, and use the declaration which it's attached to.
2441   const Expr *Init = VD->getAnyInitializer(VD);
2442   if (!Init || Init->isValueDependent()) {
2443     // If we're checking a potential constant expression, the variable could be
2444     // initialized later.
2445     if (!Info.checkingPotentialConstantExpression())
2446       Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2447     return false;
2448   }
2449 
2450   // If we're currently evaluating the initializer of this declaration, use that
2451   // in-flight value.
2452   if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
2453     Result = Info.EvaluatingDeclValue;
2454     return true;
2455   }
2456 
2457   // Never evaluate the initializer of a weak variable. We can't be sure that
2458   // this is the definition which will be used.
2459   if (VD->isWeak()) {
2460     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2461     return false;
2462   }
2463 
2464   // Check that we can fold the initializer. In C++, we will have already done
2465   // this in the cases where it matters for conformance.
2466   SmallVector<PartialDiagnosticAt, 8> Notes;
2467   if (!VD->evaluateValue(Notes)) {
2468     Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
2469               Notes.size() + 1) << VD;
2470     Info.Note(VD->getLocation(), diag::note_declared_at);
2471     Info.addNotes(Notes);
2472     return false;
2473   } else if (!VD->checkInitIsICE()) {
2474     Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
2475                  Notes.size() + 1) << VD;
2476     Info.Note(VD->getLocation(), diag::note_declared_at);
2477     Info.addNotes(Notes);
2478   }
2479 
2480   Result = VD->getEvaluatedValue();
2481   return true;
2482 }
2483 
2484 static bool IsConstNonVolatile(QualType T) {
2485   Qualifiers Quals = T.getQualifiers();
2486   return Quals.hasConst() && !Quals.hasVolatile();
2487 }
2488 
2489 /// Get the base index of the given base class within an APValue representing
2490 /// the given derived class.
2491 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2492                              const CXXRecordDecl *Base) {
2493   Base = Base->getCanonicalDecl();
2494   unsigned Index = 0;
2495   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2496          E = Derived->bases_end(); I != E; ++I, ++Index) {
2497     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2498       return Index;
2499   }
2500 
2501   llvm_unreachable("base class missing from derived class's bases list");
2502 }
2503 
2504 /// Extract the value of a character from a string literal.
2505 static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2506                                             uint64_t Index) {
2507   // FIXME: Support MakeStringConstant
2508   if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2509     std::string Str;
2510     Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2511     assert(Index <= Str.size() && "Index too large");
2512     return APSInt::getUnsigned(Str.c_str()[Index]);
2513   }
2514 
2515   if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2516     Lit = PE->getFunctionName();
2517   const StringLiteral *S = cast<StringLiteral>(Lit);
2518   const ConstantArrayType *CAT =
2519       Info.Ctx.getAsConstantArrayType(S->getType());
2520   assert(CAT && "string literal isn't an array");
2521   QualType CharType = CAT->getElementType();
2522   assert(CharType->isIntegerType() && "unexpected character type");
2523 
2524   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2525                CharType->isUnsignedIntegerType());
2526   if (Index < S->getLength())
2527     Value = S->getCodeUnit(Index);
2528   return Value;
2529 }
2530 
2531 // Expand a string literal into an array of characters.
2532 static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2533                                 APValue &Result) {
2534   const StringLiteral *S = cast<StringLiteral>(Lit);
2535   const ConstantArrayType *CAT =
2536       Info.Ctx.getAsConstantArrayType(S->getType());
2537   assert(CAT && "string literal isn't an array");
2538   QualType CharType = CAT->getElementType();
2539   assert(CharType->isIntegerType() && "unexpected character type");
2540 
2541   unsigned Elts = CAT->getSize().getZExtValue();
2542   Result = APValue(APValue::UninitArray(),
2543                    std::min(S->getLength(), Elts), Elts);
2544   APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2545                CharType->isUnsignedIntegerType());
2546   if (Result.hasArrayFiller())
2547     Result.getArrayFiller() = APValue(Value);
2548   for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2549     Value = S->getCodeUnit(I);
2550     Result.getArrayInitializedElt(I) = APValue(Value);
2551   }
2552 }
2553 
2554 // Expand an array so that it has more than Index filled elements.
2555 static void expandArray(APValue &Array, unsigned Index) {
2556   unsigned Size = Array.getArraySize();
2557   assert(Index < Size);
2558 
2559   // Always at least double the number of elements for which we store a value.
2560   unsigned OldElts = Array.getArrayInitializedElts();
2561   unsigned NewElts = std::max(Index+1, OldElts * 2);
2562   NewElts = std::min(Size, std::max(NewElts, 8u));
2563 
2564   // Copy the data across.
2565   APValue NewValue(APValue::UninitArray(), NewElts, Size);
2566   for (unsigned I = 0; I != OldElts; ++I)
2567     NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2568   for (unsigned I = OldElts; I != NewElts; ++I)
2569     NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2570   if (NewValue.hasArrayFiller())
2571     NewValue.getArrayFiller() = Array.getArrayFiller();
2572   Array.swap(NewValue);
2573 }
2574 
2575 /// Determine whether a type would actually be read by an lvalue-to-rvalue
2576 /// conversion. If it's of class type, we may assume that the copy operation
2577 /// is trivial. Note that this is never true for a union type with fields
2578 /// (because the copy always "reads" the active member) and always true for
2579 /// a non-class type.
2580 static bool isReadByLvalueToRvalueConversion(QualType T) {
2581   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2582   if (!RD || (RD->isUnion() && !RD->field_empty()))
2583     return true;
2584   if (RD->isEmpty())
2585     return false;
2586 
2587   for (auto *Field : RD->fields())
2588     if (isReadByLvalueToRvalueConversion(Field->getType()))
2589       return true;
2590 
2591   for (auto &BaseSpec : RD->bases())
2592     if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2593       return true;
2594 
2595   return false;
2596 }
2597 
2598 /// Diagnose an attempt to read from any unreadable field within the specified
2599 /// type, which might be a class type.
2600 static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2601                                      QualType T) {
2602   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2603   if (!RD)
2604     return false;
2605 
2606   if (!RD->hasMutableFields())
2607     return false;
2608 
2609   for (auto *Field : RD->fields()) {
2610     // If we're actually going to read this field in some way, then it can't
2611     // be mutable. If we're in a union, then assigning to a mutable field
2612     // (even an empty one) can change the active member, so that's not OK.
2613     // FIXME: Add core issue number for the union case.
2614     if (Field->isMutable() &&
2615         (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2616       Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2617       Info.Note(Field->getLocation(), diag::note_declared_at);
2618       return true;
2619     }
2620 
2621     if (diagnoseUnreadableFields(Info, E, Field->getType()))
2622       return true;
2623   }
2624 
2625   for (auto &BaseSpec : RD->bases())
2626     if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2627       return true;
2628 
2629   // All mutable fields were empty, and thus not actually read.
2630   return false;
2631 }
2632 
2633 /// Kinds of access we can perform on an object, for diagnostics.
2634 enum AccessKinds {
2635   AK_Read,
2636   AK_Assign,
2637   AK_Increment,
2638   AK_Decrement
2639 };
2640 
2641 namespace {
2642 /// A handle to a complete object (an object that is not a subobject of
2643 /// another object).
2644 struct CompleteObject {
2645   /// The value of the complete object.
2646   APValue *Value;
2647   /// The type of the complete object.
2648   QualType Type;
2649   bool LifetimeStartedInEvaluation;
2650 
2651   CompleteObject() : Value(nullptr) {}
2652   CompleteObject(APValue *Value, QualType Type,
2653                  bool LifetimeStartedInEvaluation)
2654       : Value(Value), Type(Type),
2655         LifetimeStartedInEvaluation(LifetimeStartedInEvaluation) {
2656     assert(Value && "missing value for complete object");
2657   }
2658 
2659   explicit operator bool() const { return Value; }
2660 };
2661 } // end anonymous namespace
2662 
2663 /// Find the designated sub-object of an rvalue.
2664 template<typename SubobjectHandler>
2665 typename SubobjectHandler::result_type
2666 findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
2667               const SubobjectDesignator &Sub, SubobjectHandler &handler) {
2668   if (Sub.Invalid)
2669     // A diagnostic will have already been produced.
2670     return handler.failed();
2671   if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
2672     if (Info.getLangOpts().CPlusPlus11)
2673       Info.FFDiag(E, Sub.isOnePastTheEnd()
2674                          ? diag::note_constexpr_access_past_end
2675                          : diag::note_constexpr_access_unsized_array)
2676           << handler.AccessKind;
2677     else
2678       Info.FFDiag(E);
2679     return handler.failed();
2680   }
2681 
2682   APValue *O = Obj.Value;
2683   QualType ObjType = Obj.Type;
2684   const FieldDecl *LastField = nullptr;
2685   const bool MayReadMutableMembers =
2686       Obj.LifetimeStartedInEvaluation && Info.getLangOpts().CPlusPlus14;
2687 
2688   // Walk the designator's path to find the subobject.
2689   for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2690     if (O->isUninit()) {
2691       if (!Info.checkingPotentialConstantExpression())
2692         Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2693       return handler.failed();
2694     }
2695 
2696     if (I == N) {
2697       // If we are reading an object of class type, there may still be more
2698       // things we need to check: if there are any mutable subobjects, we
2699       // cannot perform this read. (This only happens when performing a trivial
2700       // copy or assignment.)
2701       if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2702           !MayReadMutableMembers && diagnoseUnreadableFields(Info, E, ObjType))
2703         return handler.failed();
2704 
2705       if (!handler.found(*O, ObjType))
2706         return false;
2707 
2708       // If we modified a bit-field, truncate it to the right width.
2709       if (handler.AccessKind != AK_Read &&
2710           LastField && LastField->isBitField() &&
2711           !truncateBitfieldValue(Info, E, *O, LastField))
2712         return false;
2713 
2714       return true;
2715     }
2716 
2717     LastField = nullptr;
2718     if (ObjType->isArrayType()) {
2719       // Next subobject is an array element.
2720       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
2721       assert(CAT && "vla in literal type?");
2722       uint64_t Index = Sub.Entries[I].ArrayIndex;
2723       if (CAT->getSize().ule(Index)) {
2724         // Note, it should not be possible to form a pointer with a valid
2725         // designator which points more than one past the end of the array.
2726         if (Info.getLangOpts().CPlusPlus11)
2727           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2728             << handler.AccessKind;
2729         else
2730           Info.FFDiag(E);
2731         return handler.failed();
2732       }
2733 
2734       ObjType = CAT->getElementType();
2735 
2736       // An array object is represented as either an Array APValue or as an
2737       // LValue which refers to a string literal.
2738       if (O->isLValue()) {
2739         assert(I == N - 1 && "extracting subobject of character?");
2740         assert(!O->hasLValuePath() || O->getLValuePath().empty());
2741         if (handler.AccessKind != AK_Read)
2742           expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2743                               *O);
2744         else
2745           return handler.foundString(*O, ObjType, Index);
2746       }
2747 
2748       if (O->getArrayInitializedElts() > Index)
2749         O = &O->getArrayInitializedElt(Index);
2750       else if (handler.AccessKind != AK_Read) {
2751         expandArray(*O, Index);
2752         O = &O->getArrayInitializedElt(Index);
2753       } else
2754         O = &O->getArrayFiller();
2755     } else if (ObjType->isAnyComplexType()) {
2756       // Next subobject is a complex number.
2757       uint64_t Index = Sub.Entries[I].ArrayIndex;
2758       if (Index > 1) {
2759         if (Info.getLangOpts().CPlusPlus11)
2760           Info.FFDiag(E, diag::note_constexpr_access_past_end)
2761             << handler.AccessKind;
2762         else
2763           Info.FFDiag(E);
2764         return handler.failed();
2765       }
2766 
2767       bool WasConstQualified = ObjType.isConstQualified();
2768       ObjType = ObjType->castAs<ComplexType>()->getElementType();
2769       if (WasConstQualified)
2770         ObjType.addConst();
2771 
2772       assert(I == N - 1 && "extracting subobject of scalar?");
2773       if (O->isComplexInt()) {
2774         return handler.found(Index ? O->getComplexIntImag()
2775                                    : O->getComplexIntReal(), ObjType);
2776       } else {
2777         assert(O->isComplexFloat());
2778         return handler.found(Index ? O->getComplexFloatImag()
2779                                    : O->getComplexFloatReal(), ObjType);
2780       }
2781     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
2782       // In C++14 onwards, it is permitted to read a mutable member whose
2783       // lifetime began within the evaluation.
2784       // FIXME: Should we also allow this in C++11?
2785       if (Field->isMutable() && handler.AccessKind == AK_Read &&
2786           !MayReadMutableMembers) {
2787         Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
2788           << Field;
2789         Info.Note(Field->getLocation(), diag::note_declared_at);
2790         return handler.failed();
2791       }
2792 
2793       // Next subobject is a class, struct or union field.
2794       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2795       if (RD->isUnion()) {
2796         const FieldDecl *UnionField = O->getUnionField();
2797         if (!UnionField ||
2798             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
2799           Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
2800             << handler.AccessKind << Field << !UnionField << UnionField;
2801           return handler.failed();
2802         }
2803         O = &O->getUnionValue();
2804       } else
2805         O = &O->getStructField(Field->getFieldIndex());
2806 
2807       bool WasConstQualified = ObjType.isConstQualified();
2808       ObjType = Field->getType();
2809       if (WasConstQualified && !Field->isMutable())
2810         ObjType.addConst();
2811 
2812       if (ObjType.isVolatileQualified()) {
2813         if (Info.getLangOpts().CPlusPlus) {
2814           // FIXME: Include a description of the path to the volatile subobject.
2815           Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
2816             << handler.AccessKind << 2 << Field;
2817           Info.Note(Field->getLocation(), diag::note_declared_at);
2818         } else {
2819           Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
2820         }
2821         return handler.failed();
2822       }
2823 
2824       LastField = Field;
2825     } else {
2826       // Next subobject is a base class.
2827       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2828       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2829       O = &O->getStructBase(getBaseIndex(Derived, Base));
2830 
2831       bool WasConstQualified = ObjType.isConstQualified();
2832       ObjType = Info.Ctx.getRecordType(Base);
2833       if (WasConstQualified)
2834         ObjType.addConst();
2835     }
2836   }
2837 }
2838 
2839 namespace {
2840 struct ExtractSubobjectHandler {
2841   EvalInfo &Info;
2842   APValue &Result;
2843 
2844   static const AccessKinds AccessKind = AK_Read;
2845 
2846   typedef bool result_type;
2847   bool failed() { return false; }
2848   bool found(APValue &Subobj, QualType SubobjType) {
2849     Result = Subobj;
2850     return true;
2851   }
2852   bool found(APSInt &Value, QualType SubobjType) {
2853     Result = APValue(Value);
2854     return true;
2855   }
2856   bool found(APFloat &Value, QualType SubobjType) {
2857     Result = APValue(Value);
2858     return true;
2859   }
2860   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2861     Result = APValue(extractStringLiteralCharacter(
2862         Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2863     return true;
2864   }
2865 };
2866 } // end anonymous namespace
2867 
2868 const AccessKinds ExtractSubobjectHandler::AccessKind;
2869 
2870 /// Extract the designated sub-object of an rvalue.
2871 static bool extractSubobject(EvalInfo &Info, const Expr *E,
2872                              const CompleteObject &Obj,
2873                              const SubobjectDesignator &Sub,
2874                              APValue &Result) {
2875   ExtractSubobjectHandler Handler = { Info, Result };
2876   return findSubobject(Info, E, Obj, Sub, Handler);
2877 }
2878 
2879 namespace {
2880 struct ModifySubobjectHandler {
2881   EvalInfo &Info;
2882   APValue &NewVal;
2883   const Expr *E;
2884 
2885   typedef bool result_type;
2886   static const AccessKinds AccessKind = AK_Assign;
2887 
2888   bool checkConst(QualType QT) {
2889     // Assigning to a const object has undefined behavior.
2890     if (QT.isConstQualified()) {
2891       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
2892       return false;
2893     }
2894     return true;
2895   }
2896 
2897   bool failed() { return false; }
2898   bool found(APValue &Subobj, QualType SubobjType) {
2899     if (!checkConst(SubobjType))
2900       return false;
2901     // We've been given ownership of NewVal, so just swap it in.
2902     Subobj.swap(NewVal);
2903     return true;
2904   }
2905   bool found(APSInt &Value, QualType SubobjType) {
2906     if (!checkConst(SubobjType))
2907       return false;
2908     if (!NewVal.isInt()) {
2909       // Maybe trying to write a cast pointer value into a complex?
2910       Info.FFDiag(E);
2911       return false;
2912     }
2913     Value = NewVal.getInt();
2914     return true;
2915   }
2916   bool found(APFloat &Value, QualType SubobjType) {
2917     if (!checkConst(SubobjType))
2918       return false;
2919     Value = NewVal.getFloat();
2920     return true;
2921   }
2922   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2923     llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2924   }
2925 };
2926 } // end anonymous namespace
2927 
2928 const AccessKinds ModifySubobjectHandler::AccessKind;
2929 
2930 /// Update the designated sub-object of an rvalue to the given value.
2931 static bool modifySubobject(EvalInfo &Info, const Expr *E,
2932                             const CompleteObject &Obj,
2933                             const SubobjectDesignator &Sub,
2934                             APValue &NewVal) {
2935   ModifySubobjectHandler Handler = { Info, NewVal, E };
2936   return findSubobject(Info, E, Obj, Sub, Handler);
2937 }
2938 
2939 /// Find the position where two subobject designators diverge, or equivalently
2940 /// the length of the common initial subsequence.
2941 static unsigned FindDesignatorMismatch(QualType ObjType,
2942                                        const SubobjectDesignator &A,
2943                                        const SubobjectDesignator &B,
2944                                        bool &WasArrayIndex) {
2945   unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2946   for (/**/; I != N; ++I) {
2947     if (!ObjType.isNull() &&
2948         (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
2949       // Next subobject is an array element.
2950       if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2951         WasArrayIndex = true;
2952         return I;
2953       }
2954       if (ObjType->isAnyComplexType())
2955         ObjType = ObjType->castAs<ComplexType>()->getElementType();
2956       else
2957         ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
2958     } else {
2959       if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2960         WasArrayIndex = false;
2961         return I;
2962       }
2963       if (const FieldDecl *FD = getAsField(A.Entries[I]))
2964         // Next subobject is a field.
2965         ObjType = FD->getType();
2966       else
2967         // Next subobject is a base class.
2968         ObjType = QualType();
2969     }
2970   }
2971   WasArrayIndex = false;
2972   return I;
2973 }
2974 
2975 /// Determine whether the given subobject designators refer to elements of the
2976 /// same array object.
2977 static bool AreElementsOfSameArray(QualType ObjType,
2978                                    const SubobjectDesignator &A,
2979                                    const SubobjectDesignator &B) {
2980   if (A.Entries.size() != B.Entries.size())
2981     return false;
2982 
2983   bool IsArray = A.MostDerivedIsArrayElement;
2984   if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2985     // A is a subobject of the array element.
2986     return false;
2987 
2988   // If A (and B) designates an array element, the last entry will be the array
2989   // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2990   // of length 1' case, and the entire path must match.
2991   bool WasArrayIndex;
2992   unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2993   return CommonLength >= A.Entries.size() - IsArray;
2994 }
2995 
2996 /// Find the complete object to which an LValue refers.
2997 static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2998                                          AccessKinds AK, const LValue &LVal,
2999                                          QualType LValType) {
3000   if (!LVal.Base) {
3001     Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
3002     return CompleteObject();
3003   }
3004 
3005   CallStackFrame *Frame = nullptr;
3006   if (LVal.CallIndex) {
3007     Frame = Info.getCallFrame(LVal.CallIndex);
3008     if (!Frame) {
3009       Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
3010         << AK << LVal.Base.is<const ValueDecl*>();
3011       NoteLValueLocation(Info, LVal.Base);
3012       return CompleteObject();
3013     }
3014   }
3015 
3016   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3017   // is not a constant expression (even if the object is non-volatile). We also
3018   // apply this rule to C++98, in order to conform to the expected 'volatile'
3019   // semantics.
3020   if (LValType.isVolatileQualified()) {
3021     if (Info.getLangOpts().CPlusPlus)
3022       Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
3023         << AK << LValType;
3024     else
3025       Info.FFDiag(E);
3026     return CompleteObject();
3027   }
3028 
3029   // Compute value storage location and type of base object.
3030   APValue *BaseVal = nullptr;
3031   QualType BaseType = getType(LVal.Base);
3032   bool LifetimeStartedInEvaluation = Frame;
3033 
3034   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3035     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3036     // In C++11, constexpr, non-volatile variables initialized with constant
3037     // expressions are constant expressions too. Inside constexpr functions,
3038     // parameters are constant expressions even if they're non-const.
3039     // In C++1y, objects local to a constant expression (those with a Frame) are
3040     // both readable and writable inside constant expressions.
3041     // In C, such things can also be folded, although they are not ICEs.
3042     const VarDecl *VD = dyn_cast<VarDecl>(D);
3043     if (VD) {
3044       if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3045         VD = VDef;
3046     }
3047     if (!VD || VD->isInvalidDecl()) {
3048       Info.FFDiag(E);
3049       return CompleteObject();
3050     }
3051 
3052     // Accesses of volatile-qualified objects are not allowed.
3053     if (BaseType.isVolatileQualified()) {
3054       if (Info.getLangOpts().CPlusPlus) {
3055         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3056           << AK << 1 << VD;
3057         Info.Note(VD->getLocation(), diag::note_declared_at);
3058       } else {
3059         Info.FFDiag(E);
3060       }
3061       return CompleteObject();
3062     }
3063 
3064     // Unless we're looking at a local variable or argument in a constexpr call,
3065     // the variable we're reading must be const.
3066     if (!Frame) {
3067       if (Info.getLangOpts().CPlusPlus14 &&
3068           VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3069         // OK, we can read and modify an object if we're in the process of
3070         // evaluating its initializer, because its lifetime began in this
3071         // evaluation.
3072       } else if (AK != AK_Read) {
3073         // All the remaining cases only permit reading.
3074         Info.FFDiag(E, diag::note_constexpr_modify_global);
3075         return CompleteObject();
3076       } else if (VD->isConstexpr()) {
3077         // OK, we can read this variable.
3078       } else if (BaseType->isIntegralOrEnumerationType()) {
3079         // In OpenCL if a variable is in constant address space it is a const value.
3080         if (!(BaseType.isConstQualified() ||
3081               (Info.getLangOpts().OpenCL &&
3082                BaseType.getAddressSpace() == LangAS::opencl_constant))) {
3083           if (Info.getLangOpts().CPlusPlus) {
3084             Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
3085             Info.Note(VD->getLocation(), diag::note_declared_at);
3086           } else {
3087             Info.FFDiag(E);
3088           }
3089           return CompleteObject();
3090         }
3091       } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3092         // We support folding of const floating-point types, in order to make
3093         // static const data members of such types (supported as an extension)
3094         // more useful.
3095         if (Info.getLangOpts().CPlusPlus11) {
3096           Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3097           Info.Note(VD->getLocation(), diag::note_declared_at);
3098         } else {
3099           Info.CCEDiag(E);
3100         }
3101       } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3102         Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3103         // Keep evaluating to see what we can do.
3104       } else {
3105         // FIXME: Allow folding of values of any literal type in all languages.
3106         if (Info.checkingPotentialConstantExpression() &&
3107             VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3108           // The definition of this variable could be constexpr. We can't
3109           // access it right now, but may be able to in future.
3110         } else if (Info.getLangOpts().CPlusPlus11) {
3111           Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3112           Info.Note(VD->getLocation(), diag::note_declared_at);
3113         } else {
3114           Info.FFDiag(E);
3115         }
3116         return CompleteObject();
3117       }
3118     }
3119 
3120     if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3121       return CompleteObject();
3122   } else {
3123     const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3124 
3125     if (!Frame) {
3126       if (const MaterializeTemporaryExpr *MTE =
3127               dyn_cast<MaterializeTemporaryExpr>(Base)) {
3128         assert(MTE->getStorageDuration() == SD_Static &&
3129                "should have a frame for a non-global materialized temporary");
3130 
3131         // Per C++1y [expr.const]p2:
3132         //  an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3133         //   - a [...] glvalue of integral or enumeration type that refers to
3134         //     a non-volatile const object [...]
3135         //   [...]
3136         //   - a [...] glvalue of literal type that refers to a non-volatile
3137         //     object whose lifetime began within the evaluation of e.
3138         //
3139         // C++11 misses the 'began within the evaluation of e' check and
3140         // instead allows all temporaries, including things like:
3141         //   int &&r = 1;
3142         //   int x = ++r;
3143         //   constexpr int k = r;
3144         // Therefore we use the C++14 rules in C++11 too.
3145         const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3146         const ValueDecl *ED = MTE->getExtendingDecl();
3147         if (!(BaseType.isConstQualified() &&
3148               BaseType->isIntegralOrEnumerationType()) &&
3149             !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
3150           Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
3151           Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3152           return CompleteObject();
3153         }
3154 
3155         BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3156         assert(BaseVal && "got reference to unevaluated temporary");
3157         LifetimeStartedInEvaluation = true;
3158       } else {
3159         Info.FFDiag(E);
3160         return CompleteObject();
3161       }
3162     } else {
3163       BaseVal = Frame->getTemporary(Base);
3164       assert(BaseVal && "missing value for temporary");
3165     }
3166 
3167     // Volatile temporary objects cannot be accessed in constant expressions.
3168     if (BaseType.isVolatileQualified()) {
3169       if (Info.getLangOpts().CPlusPlus) {
3170         Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
3171           << AK << 0;
3172         Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3173       } else {
3174         Info.FFDiag(E);
3175       }
3176       return CompleteObject();
3177     }
3178   }
3179 
3180   // During the construction of an object, it is not yet 'const'.
3181   // FIXME: This doesn't do quite the right thing for const subobjects of the
3182   // object under construction.
3183   if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
3184     BaseType = Info.Ctx.getCanonicalType(BaseType);
3185     BaseType.removeLocalConst();
3186     LifetimeStartedInEvaluation = true;
3187   }
3188 
3189   // In C++14, we can't safely access any mutable state when we might be
3190   // evaluating after an unmodeled side effect.
3191   //
3192   // FIXME: Not all local state is mutable. Allow local constant subobjects
3193   // to be read here (but take care with 'mutable' fields).
3194   if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3195        Info.EvalStatus.HasSideEffects) ||
3196       (AK != AK_Read && Info.IsSpeculativelyEvaluating))
3197     return CompleteObject();
3198 
3199   return CompleteObject(BaseVal, BaseType, LifetimeStartedInEvaluation);
3200 }
3201 
3202 /// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3203 /// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3204 /// glvalue referred to by an entity of reference type.
3205 ///
3206 /// \param Info - Information about the ongoing evaluation.
3207 /// \param Conv - The expression for which we are performing the conversion.
3208 ///               Used for diagnostics.
3209 /// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3210 ///               case of a non-class type).
3211 /// \param LVal - The glvalue on which we are attempting to perform this action.
3212 /// \param RVal - The produced value will be placed here.
3213 static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
3214                                            QualType Type,
3215                                            const LValue &LVal, APValue &RVal) {
3216   if (LVal.Designator.Invalid)
3217     return false;
3218 
3219   // Check for special cases where there is no existing APValue to look at.
3220   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3221   if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
3222     if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3223       // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3224       // initializer until now for such expressions. Such an expression can't be
3225       // an ICE in C, so this only matters for fold.
3226       if (Type.isVolatileQualified()) {
3227         Info.FFDiag(Conv);
3228         return false;
3229       }
3230       APValue Lit;
3231       if (!Evaluate(Lit, Info, CLE->getInitializer()))
3232         return false;
3233       CompleteObject LitObj(&Lit, Base->getType(), false);
3234       return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
3235     } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
3236       // We represent a string literal array as an lvalue pointing at the
3237       // corresponding expression, rather than building an array of chars.
3238       // FIXME: Support ObjCEncodeExpr, MakeStringConstant
3239       APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3240       CompleteObject StrObj(&Str, Base->getType(), false);
3241       return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
3242     }
3243   }
3244 
3245   CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3246   return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
3247 }
3248 
3249 /// Perform an assignment of Val to LVal. Takes ownership of Val.
3250 static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
3251                              QualType LValType, APValue &Val) {
3252   if (LVal.Designator.Invalid)
3253     return false;
3254 
3255   if (!Info.getLangOpts().CPlusPlus14) {
3256     Info.FFDiag(E);
3257     return false;
3258   }
3259 
3260   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3261   return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
3262 }
3263 
3264 namespace {
3265 struct CompoundAssignSubobjectHandler {
3266   EvalInfo &Info;
3267   const Expr *E;
3268   QualType PromotedLHSType;
3269   BinaryOperatorKind Opcode;
3270   const APValue &RHS;
3271 
3272   static const AccessKinds AccessKind = AK_Assign;
3273 
3274   typedef bool result_type;
3275 
3276   bool checkConst(QualType QT) {
3277     // Assigning to a const object has undefined behavior.
3278     if (QT.isConstQualified()) {
3279       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3280       return false;
3281     }
3282     return true;
3283   }
3284 
3285   bool failed() { return false; }
3286   bool found(APValue &Subobj, QualType SubobjType) {
3287     switch (Subobj.getKind()) {
3288     case APValue::Int:
3289       return found(Subobj.getInt(), SubobjType);
3290     case APValue::Float:
3291       return found(Subobj.getFloat(), SubobjType);
3292     case APValue::ComplexInt:
3293     case APValue::ComplexFloat:
3294       // FIXME: Implement complex compound assignment.
3295       Info.FFDiag(E);
3296       return false;
3297     case APValue::LValue:
3298       return foundPointer(Subobj, SubobjType);
3299     default:
3300       // FIXME: can this happen?
3301       Info.FFDiag(E);
3302       return false;
3303     }
3304   }
3305   bool found(APSInt &Value, QualType SubobjType) {
3306     if (!checkConst(SubobjType))
3307       return false;
3308 
3309     if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3310       // We don't support compound assignment on integer-cast-to-pointer
3311       // values.
3312       Info.FFDiag(E);
3313       return false;
3314     }
3315 
3316     APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3317                                     SubobjType, Value);
3318     if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3319       return false;
3320     Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3321     return true;
3322   }
3323   bool found(APFloat &Value, QualType SubobjType) {
3324     return checkConst(SubobjType) &&
3325            HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3326                                   Value) &&
3327            handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3328            HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
3329   }
3330   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3331     if (!checkConst(SubobjType))
3332       return false;
3333 
3334     QualType PointeeType;
3335     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3336       PointeeType = PT->getPointeeType();
3337 
3338     if (PointeeType.isNull() || !RHS.isInt() ||
3339         (Opcode != BO_Add && Opcode != BO_Sub)) {
3340       Info.FFDiag(E);
3341       return false;
3342     }
3343 
3344     APSInt Offset = RHS.getInt();
3345     if (Opcode == BO_Sub)
3346       negateAsSigned(Offset);
3347 
3348     LValue LVal;
3349     LVal.setFrom(Info.Ctx, Subobj);
3350     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3351       return false;
3352     LVal.moveInto(Subobj);
3353     return true;
3354   }
3355   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3356     llvm_unreachable("shouldn't encounter string elements here");
3357   }
3358 };
3359 } // end anonymous namespace
3360 
3361 const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3362 
3363 /// Perform a compound assignment of LVal <op>= RVal.
3364 static bool handleCompoundAssignment(
3365     EvalInfo &Info, const Expr *E,
3366     const LValue &LVal, QualType LValType, QualType PromotedLValType,
3367     BinaryOperatorKind Opcode, const APValue &RVal) {
3368   if (LVal.Designator.Invalid)
3369     return false;
3370 
3371   if (!Info.getLangOpts().CPlusPlus14) {
3372     Info.FFDiag(E);
3373     return false;
3374   }
3375 
3376   CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3377   CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3378                                              RVal };
3379   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3380 }
3381 
3382 namespace {
3383 struct IncDecSubobjectHandler {
3384   EvalInfo &Info;
3385   const UnaryOperator *E;
3386   AccessKinds AccessKind;
3387   APValue *Old;
3388 
3389   typedef bool result_type;
3390 
3391   bool checkConst(QualType QT) {
3392     // Assigning to a const object has undefined behavior.
3393     if (QT.isConstQualified()) {
3394       Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
3395       return false;
3396     }
3397     return true;
3398   }
3399 
3400   bool failed() { return false; }
3401   bool found(APValue &Subobj, QualType SubobjType) {
3402     // Stash the old value. Also clear Old, so we don't clobber it later
3403     // if we're post-incrementing a complex.
3404     if (Old) {
3405       *Old = Subobj;
3406       Old = nullptr;
3407     }
3408 
3409     switch (Subobj.getKind()) {
3410     case APValue::Int:
3411       return found(Subobj.getInt(), SubobjType);
3412     case APValue::Float:
3413       return found(Subobj.getFloat(), SubobjType);
3414     case APValue::ComplexInt:
3415       return found(Subobj.getComplexIntReal(),
3416                    SubobjType->castAs<ComplexType>()->getElementType()
3417                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3418     case APValue::ComplexFloat:
3419       return found(Subobj.getComplexFloatReal(),
3420                    SubobjType->castAs<ComplexType>()->getElementType()
3421                      .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3422     case APValue::LValue:
3423       return foundPointer(Subobj, SubobjType);
3424     default:
3425       // FIXME: can this happen?
3426       Info.FFDiag(E);
3427       return false;
3428     }
3429   }
3430   bool found(APSInt &Value, QualType SubobjType) {
3431     if (!checkConst(SubobjType))
3432       return false;
3433 
3434     if (!SubobjType->isIntegerType()) {
3435       // We don't support increment / decrement on integer-cast-to-pointer
3436       // values.
3437       Info.FFDiag(E);
3438       return false;
3439     }
3440 
3441     if (Old) *Old = APValue(Value);
3442 
3443     // bool arithmetic promotes to int, and the conversion back to bool
3444     // doesn't reduce mod 2^n, so special-case it.
3445     if (SubobjType->isBooleanType()) {
3446       if (AccessKind == AK_Increment)
3447         Value = 1;
3448       else
3449         Value = !Value;
3450       return true;
3451     }
3452 
3453     bool WasNegative = Value.isNegative();
3454     if (AccessKind == AK_Increment) {
3455       ++Value;
3456 
3457       if (!WasNegative && Value.isNegative() && E->canOverflow()) {
3458         APSInt ActualValue(Value, /*IsUnsigned*/true);
3459         return HandleOverflow(Info, E, ActualValue, SubobjType);
3460       }
3461     } else {
3462       --Value;
3463 
3464       if (WasNegative && !Value.isNegative() && E->canOverflow()) {
3465         unsigned BitWidth = Value.getBitWidth();
3466         APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3467         ActualValue.setBit(BitWidth);
3468         return HandleOverflow(Info, E, ActualValue, SubobjType);
3469       }
3470     }
3471     return true;
3472   }
3473   bool found(APFloat &Value, QualType SubobjType) {
3474     if (!checkConst(SubobjType))
3475       return false;
3476 
3477     if (Old) *Old = APValue(Value);
3478 
3479     APFloat One(Value.getSemantics(), 1);
3480     if (AccessKind == AK_Increment)
3481       Value.add(One, APFloat::rmNearestTiesToEven);
3482     else
3483       Value.subtract(One, APFloat::rmNearestTiesToEven);
3484     return true;
3485   }
3486   bool foundPointer(APValue &Subobj, QualType SubobjType) {
3487     if (!checkConst(SubobjType))
3488       return false;
3489 
3490     QualType PointeeType;
3491     if (const PointerType *PT = SubobjType->getAs<PointerType>())
3492       PointeeType = PT->getPointeeType();
3493     else {
3494       Info.FFDiag(E);
3495       return false;
3496     }
3497 
3498     LValue LVal;
3499     LVal.setFrom(Info.Ctx, Subobj);
3500     if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3501                                      AccessKind == AK_Increment ? 1 : -1))
3502       return false;
3503     LVal.moveInto(Subobj);
3504     return true;
3505   }
3506   bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3507     llvm_unreachable("shouldn't encounter string elements here");
3508   }
3509 };
3510 } // end anonymous namespace
3511 
3512 /// Perform an increment or decrement on LVal.
3513 static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3514                          QualType LValType, bool IsIncrement, APValue *Old) {
3515   if (LVal.Designator.Invalid)
3516     return false;
3517 
3518   if (!Info.getLangOpts().CPlusPlus14) {
3519     Info.FFDiag(E);
3520     return false;
3521   }
3522 
3523   AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3524   CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3525   IncDecSubobjectHandler Handler = {Info, cast<UnaryOperator>(E), AK, Old};
3526   return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3527 }
3528 
3529 /// Build an lvalue for the object argument of a member function call.
3530 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3531                                    LValue &This) {
3532   if (Object->getType()->isPointerType())
3533     return EvaluatePointer(Object, This, Info);
3534 
3535   if (Object->isGLValue())
3536     return EvaluateLValue(Object, This, Info);
3537 
3538   if (Object->getType()->isLiteralType(Info.Ctx))
3539     return EvaluateTemporary(Object, This, Info);
3540 
3541   Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
3542   return false;
3543 }
3544 
3545 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
3546 /// lvalue referring to the result.
3547 ///
3548 /// \param Info - Information about the ongoing evaluation.
3549 /// \param LV - An lvalue referring to the base of the member pointer.
3550 /// \param RHS - The member pointer expression.
3551 /// \param IncludeMember - Specifies whether the member itself is included in
3552 ///        the resulting LValue subobject designator. This is not possible when
3553 ///        creating a bound member function.
3554 /// \return The field or method declaration to which the member pointer refers,
3555 ///         or 0 if evaluation fails.
3556 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3557                                                   QualType LVType,
3558                                                   LValue &LV,
3559                                                   const Expr *RHS,
3560                                                   bool IncludeMember = true) {
3561   MemberPtr MemPtr;
3562   if (!EvaluateMemberPointer(RHS, MemPtr, Info))
3563     return nullptr;
3564 
3565   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3566   // member value, the behavior is undefined.
3567   if (!MemPtr.getDecl()) {
3568     // FIXME: Specific diagnostic.
3569     Info.FFDiag(RHS);
3570     return nullptr;
3571   }
3572 
3573   if (MemPtr.isDerivedMember()) {
3574     // This is a member of some derived class. Truncate LV appropriately.
3575     // The end of the derived-to-base path for the base object must match the
3576     // derived-to-base path for the member pointer.
3577     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
3578         LV.Designator.Entries.size()) {
3579       Info.FFDiag(RHS);
3580       return nullptr;
3581     }
3582     unsigned PathLengthToMember =
3583         LV.Designator.Entries.size() - MemPtr.Path.size();
3584     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3585       const CXXRecordDecl *LVDecl = getAsBaseClass(
3586           LV.Designator.Entries[PathLengthToMember + I]);
3587       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
3588       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3589         Info.FFDiag(RHS);
3590         return nullptr;
3591       }
3592     }
3593 
3594     // Truncate the lvalue to the appropriate derived class.
3595     if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
3596                             PathLengthToMember))
3597       return nullptr;
3598   } else if (!MemPtr.Path.empty()) {
3599     // Extend the LValue path with the member pointer's path.
3600     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3601                                   MemPtr.Path.size() + IncludeMember);
3602 
3603     // Walk down to the appropriate base class.
3604     if (const PointerType *PT = LVType->getAs<PointerType>())
3605       LVType = PT->getPointeeType();
3606     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3607     assert(RD && "member pointer access on non-class-type expression");
3608     // The first class in the path is that of the lvalue.
3609     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3610       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
3611       if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
3612         return nullptr;
3613       RD = Base;
3614     }
3615     // Finally cast to the class containing the member.
3616     if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3617                                 MemPtr.getContainingRecord()))
3618       return nullptr;
3619   }
3620 
3621   // Add the member. Note that we cannot build bound member functions here.
3622   if (IncludeMember) {
3623     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
3624       if (!HandleLValueMember(Info, RHS, LV, FD))
3625         return nullptr;
3626     } else if (const IndirectFieldDecl *IFD =
3627                  dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
3628       if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
3629         return nullptr;
3630     } else {
3631       llvm_unreachable("can't construct reference to bound member function");
3632     }
3633   }
3634 
3635   return MemPtr.getDecl();
3636 }
3637 
3638 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3639                                                   const BinaryOperator *BO,
3640                                                   LValue &LV,
3641                                                   bool IncludeMember = true) {
3642   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3643 
3644   if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3645     if (Info.noteFailure()) {
3646       MemberPtr MemPtr;
3647       EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3648     }
3649     return nullptr;
3650   }
3651 
3652   return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3653                                    BO->getRHS(), IncludeMember);
3654 }
3655 
3656 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3657 /// the provided lvalue, which currently refers to the base object.
3658 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3659                                     LValue &Result) {
3660   SubobjectDesignator &D = Result.Designator;
3661   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
3662     return false;
3663 
3664   QualType TargetQT = E->getType();
3665   if (const PointerType *PT = TargetQT->getAs<PointerType>())
3666     TargetQT = PT->getPointeeType();
3667 
3668   // Check this cast lands within the final derived-to-base subobject path.
3669   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
3670     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3671       << D.MostDerivedType << TargetQT;
3672     return false;
3673   }
3674 
3675   // Check the type of the final cast. We don't need to check the path,
3676   // since a cast can only be formed if the path is unique.
3677   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
3678   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3679   const CXXRecordDecl *FinalType;
3680   if (NewEntriesSize == D.MostDerivedPathLength)
3681     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3682   else
3683     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
3684   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
3685     Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
3686       << D.MostDerivedType << TargetQT;
3687     return false;
3688   }
3689 
3690   // Truncate the lvalue to the appropriate derived class.
3691   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
3692 }
3693 
3694 namespace {
3695 enum EvalStmtResult {
3696   /// Evaluation failed.
3697   ESR_Failed,
3698   /// Hit a 'return' statement.
3699   ESR_Returned,
3700   /// Evaluation succeeded.
3701   ESR_Succeeded,
3702   /// Hit a 'continue' statement.
3703   ESR_Continue,
3704   /// Hit a 'break' statement.
3705   ESR_Break,
3706   /// Still scanning for 'case' or 'default' statement.
3707   ESR_CaseNotFound
3708 };
3709 }
3710 
3711 static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3712   // We don't need to evaluate the initializer for a static local.
3713   if (!VD->hasLocalStorage())
3714     return true;
3715 
3716   LValue Result;
3717   Result.set(VD, Info.CurrentCall->Index);
3718   APValue &Val = Info.CurrentCall->createTemporary(VD, true);
3719 
3720   const Expr *InitE = VD->getInit();
3721   if (!InitE) {
3722     Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3723       << false << VD->getType();
3724     Val = APValue();
3725     return false;
3726   }
3727 
3728   if (InitE->isValueDependent())
3729     return false;
3730 
3731   if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3732     // Wipe out any partially-computed value, to allow tracking that this
3733     // evaluation failed.
3734     Val = APValue();
3735     return false;
3736   }
3737 
3738   return true;
3739 }
3740 
3741 static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3742   bool OK = true;
3743 
3744   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3745     OK &= EvaluateVarDecl(Info, VD);
3746 
3747   if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3748     for (auto *BD : DD->bindings())
3749       if (auto *VD = BD->getHoldingVar())
3750         OK &= EvaluateDecl(Info, VD);
3751 
3752   return OK;
3753 }
3754 
3755 
3756 /// Evaluate a condition (either a variable declaration or an expression).
3757 static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3758                          const Expr *Cond, bool &Result) {
3759   FullExpressionRAII Scope(Info);
3760   if (CondDecl && !EvaluateDecl(Info, CondDecl))
3761     return false;
3762   return EvaluateAsBooleanCondition(Cond, Result, Info);
3763 }
3764 
3765 namespace {
3766 /// \brief A location where the result (returned value) of evaluating a
3767 /// statement should be stored.
3768 struct StmtResult {
3769   /// The APValue that should be filled in with the returned value.
3770   APValue &Value;
3771   /// The location containing the result, if any (used to support RVO).
3772   const LValue *Slot;
3773 };
3774 }
3775 
3776 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3777                                    const Stmt *S,
3778                                    const SwitchCase *SC = nullptr);
3779 
3780 /// Evaluate the body of a loop, and translate the result as appropriate.
3781 static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
3782                                        const Stmt *Body,
3783                                        const SwitchCase *Case = nullptr) {
3784   BlockScopeRAII Scope(Info);
3785   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
3786   case ESR_Break:
3787     return ESR_Succeeded;
3788   case ESR_Succeeded:
3789   case ESR_Continue:
3790     return ESR_Continue;
3791   case ESR_Failed:
3792   case ESR_Returned:
3793   case ESR_CaseNotFound:
3794     return ESR;
3795   }
3796   llvm_unreachable("Invalid EvalStmtResult!");
3797 }
3798 
3799 /// Evaluate a switch statement.
3800 static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
3801                                      const SwitchStmt *SS) {
3802   BlockScopeRAII Scope(Info);
3803 
3804   // Evaluate the switch condition.
3805   APSInt Value;
3806   {
3807     FullExpressionRAII Scope(Info);
3808     if (const Stmt *Init = SS->getInit()) {
3809       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3810       if (ESR != ESR_Succeeded)
3811         return ESR;
3812     }
3813     if (SS->getConditionVariable() &&
3814         !EvaluateDecl(Info, SS->getConditionVariable()))
3815       return ESR_Failed;
3816     if (!EvaluateInteger(SS->getCond(), Value, Info))
3817       return ESR_Failed;
3818   }
3819 
3820   // Find the switch case corresponding to the value of the condition.
3821   // FIXME: Cache this lookup.
3822   const SwitchCase *Found = nullptr;
3823   for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3824        SC = SC->getNextSwitchCase()) {
3825     if (isa<DefaultStmt>(SC)) {
3826       Found = SC;
3827       continue;
3828     }
3829 
3830     const CaseStmt *CS = cast<CaseStmt>(SC);
3831     APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3832     APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3833                               : LHS;
3834     if (LHS <= Value && Value <= RHS) {
3835       Found = SC;
3836       break;
3837     }
3838   }
3839 
3840   if (!Found)
3841     return ESR_Succeeded;
3842 
3843   // Search the switch body for the switch case and evaluate it from there.
3844   switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3845   case ESR_Break:
3846     return ESR_Succeeded;
3847   case ESR_Succeeded:
3848   case ESR_Continue:
3849   case ESR_Failed:
3850   case ESR_Returned:
3851     return ESR;
3852   case ESR_CaseNotFound:
3853     // This can only happen if the switch case is nested within a statement
3854     // expression. We have no intention of supporting that.
3855     Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3856     return ESR_Failed;
3857   }
3858   llvm_unreachable("Invalid EvalStmtResult!");
3859 }
3860 
3861 // Evaluate a statement.
3862 static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
3863                                    const Stmt *S, const SwitchCase *Case) {
3864   if (!Info.nextStep(S))
3865     return ESR_Failed;
3866 
3867   // If we're hunting down a 'case' or 'default' label, recurse through
3868   // substatements until we hit the label.
3869   if (Case) {
3870     // FIXME: We don't start the lifetime of objects whose initialization we
3871     // jump over. However, such objects must be of class type with a trivial
3872     // default constructor that initialize all subobjects, so must be empty,
3873     // so this almost never matters.
3874     switch (S->getStmtClass()) {
3875     case Stmt::CompoundStmtClass:
3876       // FIXME: Precompute which substatement of a compound statement we
3877       // would jump to, and go straight there rather than performing a
3878       // linear scan each time.
3879     case Stmt::LabelStmtClass:
3880     case Stmt::AttributedStmtClass:
3881     case Stmt::DoStmtClass:
3882       break;
3883 
3884     case Stmt::CaseStmtClass:
3885     case Stmt::DefaultStmtClass:
3886       if (Case == S)
3887         Case = nullptr;
3888       break;
3889 
3890     case Stmt::IfStmtClass: {
3891       // FIXME: Precompute which side of an 'if' we would jump to, and go
3892       // straight there rather than scanning both sides.
3893       const IfStmt *IS = cast<IfStmt>(S);
3894 
3895       // Wrap the evaluation in a block scope, in case it's a DeclStmt
3896       // preceded by our switch label.
3897       BlockScopeRAII Scope(Info);
3898 
3899       EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3900       if (ESR != ESR_CaseNotFound || !IS->getElse())
3901         return ESR;
3902       return EvaluateStmt(Result, Info, IS->getElse(), Case);
3903     }
3904 
3905     case Stmt::WhileStmtClass: {
3906       EvalStmtResult ESR =
3907           EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3908       if (ESR != ESR_Continue)
3909         return ESR;
3910       break;
3911     }
3912 
3913     case Stmt::ForStmtClass: {
3914       const ForStmt *FS = cast<ForStmt>(S);
3915       EvalStmtResult ESR =
3916           EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3917       if (ESR != ESR_Continue)
3918         return ESR;
3919       if (FS->getInc()) {
3920         FullExpressionRAII IncScope(Info);
3921         if (!EvaluateIgnoredValue(Info, FS->getInc()))
3922           return ESR_Failed;
3923       }
3924       break;
3925     }
3926 
3927     case Stmt::DeclStmtClass:
3928       // FIXME: If the variable has initialization that can't be jumped over,
3929       // bail out of any immediately-surrounding compound-statement too.
3930     default:
3931       return ESR_CaseNotFound;
3932     }
3933   }
3934 
3935   switch (S->getStmtClass()) {
3936   default:
3937     if (const Expr *E = dyn_cast<Expr>(S)) {
3938       // Don't bother evaluating beyond an expression-statement which couldn't
3939       // be evaluated.
3940       FullExpressionRAII Scope(Info);
3941       if (!EvaluateIgnoredValue(Info, E))
3942         return ESR_Failed;
3943       return ESR_Succeeded;
3944     }
3945 
3946     Info.FFDiag(S->getLocStart());
3947     return ESR_Failed;
3948 
3949   case Stmt::NullStmtClass:
3950     return ESR_Succeeded;
3951 
3952   case Stmt::DeclStmtClass: {
3953     const DeclStmt *DS = cast<DeclStmt>(S);
3954     for (const auto *DclIt : DS->decls()) {
3955       // Each declaration initialization is its own full-expression.
3956       // FIXME: This isn't quite right; if we're performing aggregate
3957       // initialization, each braced subexpression is its own full-expression.
3958       FullExpressionRAII Scope(Info);
3959       if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
3960         return ESR_Failed;
3961     }
3962     return ESR_Succeeded;
3963   }
3964 
3965   case Stmt::ReturnStmtClass: {
3966     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
3967     FullExpressionRAII Scope(Info);
3968     if (RetExpr &&
3969         !(Result.Slot
3970               ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3971               : Evaluate(Result.Value, Info, RetExpr)))
3972       return ESR_Failed;
3973     return ESR_Returned;
3974   }
3975 
3976   case Stmt::CompoundStmtClass: {
3977     BlockScopeRAII Scope(Info);
3978 
3979     const CompoundStmt *CS = cast<CompoundStmt>(S);
3980     for (const auto *BI : CS->body()) {
3981       EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
3982       if (ESR == ESR_Succeeded)
3983         Case = nullptr;
3984       else if (ESR != ESR_CaseNotFound)
3985         return ESR;
3986     }
3987     return Case ? ESR_CaseNotFound : ESR_Succeeded;
3988   }
3989 
3990   case Stmt::IfStmtClass: {
3991     const IfStmt *IS = cast<IfStmt>(S);
3992 
3993     // Evaluate the condition, as either a var decl or as an expression.
3994     BlockScopeRAII Scope(Info);
3995     if (const Stmt *Init = IS->getInit()) {
3996       EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3997       if (ESR != ESR_Succeeded)
3998         return ESR;
3999     }
4000     bool Cond;
4001     if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
4002       return ESR_Failed;
4003 
4004     if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
4005       EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
4006       if (ESR != ESR_Succeeded)
4007         return ESR;
4008     }
4009     return ESR_Succeeded;
4010   }
4011 
4012   case Stmt::WhileStmtClass: {
4013     const WhileStmt *WS = cast<WhileStmt>(S);
4014     while (true) {
4015       BlockScopeRAII Scope(Info);
4016       bool Continue;
4017       if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4018                         Continue))
4019         return ESR_Failed;
4020       if (!Continue)
4021         break;
4022 
4023       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4024       if (ESR != ESR_Continue)
4025         return ESR;
4026     }
4027     return ESR_Succeeded;
4028   }
4029 
4030   case Stmt::DoStmtClass: {
4031     const DoStmt *DS = cast<DoStmt>(S);
4032     bool Continue;
4033     do {
4034       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
4035       if (ESR != ESR_Continue)
4036         return ESR;
4037       Case = nullptr;
4038 
4039       FullExpressionRAII CondScope(Info);
4040       if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4041         return ESR_Failed;
4042     } while (Continue);
4043     return ESR_Succeeded;
4044   }
4045 
4046   case Stmt::ForStmtClass: {
4047     const ForStmt *FS = cast<ForStmt>(S);
4048     BlockScopeRAII Scope(Info);
4049     if (FS->getInit()) {
4050       EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4051       if (ESR != ESR_Succeeded)
4052         return ESR;
4053     }
4054     while (true) {
4055       BlockScopeRAII Scope(Info);
4056       bool Continue = true;
4057       if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4058                                          FS->getCond(), Continue))
4059         return ESR_Failed;
4060       if (!Continue)
4061         break;
4062 
4063       EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4064       if (ESR != ESR_Continue)
4065         return ESR;
4066 
4067       if (FS->getInc()) {
4068         FullExpressionRAII IncScope(Info);
4069         if (!EvaluateIgnoredValue(Info, FS->getInc()))
4070           return ESR_Failed;
4071       }
4072     }
4073     return ESR_Succeeded;
4074   }
4075 
4076   case Stmt::CXXForRangeStmtClass: {
4077     const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
4078     BlockScopeRAII Scope(Info);
4079 
4080     // Initialize the __range variable.
4081     EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4082     if (ESR != ESR_Succeeded)
4083       return ESR;
4084 
4085     // Create the __begin and __end iterators.
4086     ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4087     if (ESR != ESR_Succeeded)
4088       return ESR;
4089     ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
4090     if (ESR != ESR_Succeeded)
4091       return ESR;
4092 
4093     while (true) {
4094       // Condition: __begin != __end.
4095       {
4096         bool Continue = true;
4097         FullExpressionRAII CondExpr(Info);
4098         if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4099           return ESR_Failed;
4100         if (!Continue)
4101           break;
4102       }
4103 
4104       // User's variable declaration, initialized by *__begin.
4105       BlockScopeRAII InnerScope(Info);
4106       ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4107       if (ESR != ESR_Succeeded)
4108         return ESR;
4109 
4110       // Loop body.
4111       ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4112       if (ESR != ESR_Continue)
4113         return ESR;
4114 
4115       // Increment: ++__begin
4116       if (!EvaluateIgnoredValue(Info, FS->getInc()))
4117         return ESR_Failed;
4118     }
4119 
4120     return ESR_Succeeded;
4121   }
4122 
4123   case Stmt::SwitchStmtClass:
4124     return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4125 
4126   case Stmt::ContinueStmtClass:
4127     return ESR_Continue;
4128 
4129   case Stmt::BreakStmtClass:
4130     return ESR_Break;
4131 
4132   case Stmt::LabelStmtClass:
4133     return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4134 
4135   case Stmt::AttributedStmtClass:
4136     // As a general principle, C++11 attributes can be ignored without
4137     // any semantic impact.
4138     return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4139                         Case);
4140 
4141   case Stmt::CaseStmtClass:
4142   case Stmt::DefaultStmtClass:
4143     return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
4144   }
4145 }
4146 
4147 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4148 /// default constructor. If so, we'll fold it whether or not it's marked as
4149 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
4150 /// so we need special handling.
4151 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
4152                                            const CXXConstructorDecl *CD,
4153                                            bool IsValueInitialization) {
4154   if (!CD->isTrivial() || !CD->isDefaultConstructor())
4155     return false;
4156 
4157   // Value-initialization does not call a trivial default constructor, so such a
4158   // call is a core constant expression whether or not the constructor is
4159   // constexpr.
4160   if (!CD->isConstexpr() && !IsValueInitialization) {
4161     if (Info.getLangOpts().CPlusPlus11) {
4162       // FIXME: If DiagDecl is an implicitly-declared special member function,
4163       // we should be much more explicit about why it's not constexpr.
4164       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4165         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4166       Info.Note(CD->getLocation(), diag::note_declared_at);
4167     } else {
4168       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4169     }
4170   }
4171   return true;
4172 }
4173 
4174 /// CheckConstexprFunction - Check that a function can be called in a constant
4175 /// expression.
4176 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4177                                    const FunctionDecl *Declaration,
4178                                    const FunctionDecl *Definition,
4179                                    const Stmt *Body) {
4180   // Potential constant expressions can contain calls to declared, but not yet
4181   // defined, constexpr functions.
4182   if (Info.checkingPotentialConstantExpression() && !Definition &&
4183       Declaration->isConstexpr())
4184     return false;
4185 
4186   // Bail out with no diagnostic if the function declaration itself is invalid.
4187   // We will have produced a relevant diagnostic while parsing it.
4188   if (Declaration->isInvalidDecl())
4189     return false;
4190 
4191   // Can we evaluate this function call?
4192   if (Definition && Definition->isConstexpr() &&
4193       !Definition->isInvalidDecl() && Body)
4194     return true;
4195 
4196   if (Info.getLangOpts().CPlusPlus11) {
4197     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
4198 
4199     // If this function is not constexpr because it is an inherited
4200     // non-constexpr constructor, diagnose that directly.
4201     auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4202     if (CD && CD->isInheritingConstructor()) {
4203       auto *Inherited = CD->getInheritedConstructor().getConstructor();
4204       if (!Inherited->isConstexpr())
4205         DiagDecl = CD = Inherited;
4206     }
4207 
4208     // FIXME: If DiagDecl is an implicitly-declared special member function
4209     // or an inheriting constructor, we should be much more explicit about why
4210     // it's not constexpr.
4211     if (CD && CD->isInheritingConstructor())
4212       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
4213         << CD->getInheritedConstructor().getConstructor()->getParent();
4214     else
4215       Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
4216         << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
4217     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4218   } else {
4219     Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
4220   }
4221   return false;
4222 }
4223 
4224 /// Determine if a class has any fields that might need to be copied by a
4225 /// trivial copy or move operation.
4226 static bool hasFields(const CXXRecordDecl *RD) {
4227   if (!RD || RD->isEmpty())
4228     return false;
4229   for (auto *FD : RD->fields()) {
4230     if (FD->isUnnamedBitfield())
4231       continue;
4232     return true;
4233   }
4234   for (auto &Base : RD->bases())
4235     if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4236       return true;
4237   return false;
4238 }
4239 
4240 namespace {
4241 typedef SmallVector<APValue, 8> ArgVector;
4242 }
4243 
4244 /// EvaluateArgs - Evaluate the arguments to a function call.
4245 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4246                          EvalInfo &Info) {
4247   bool Success = true;
4248   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
4249        I != E; ++I) {
4250     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4251       // If we're checking for a potential constant expression, evaluate all
4252       // initializers even if some of them fail.
4253       if (!Info.noteFailure())
4254         return false;
4255       Success = false;
4256     }
4257   }
4258   return Success;
4259 }
4260 
4261 /// Evaluate a function call.
4262 static bool HandleFunctionCall(SourceLocation CallLoc,
4263                                const FunctionDecl *Callee, const LValue *This,
4264                                ArrayRef<const Expr*> Args, const Stmt *Body,
4265                                EvalInfo &Info, APValue &Result,
4266                                const LValue *ResultSlot) {
4267   ArgVector ArgValues(Args.size());
4268   if (!EvaluateArgs(Args, ArgValues, Info))
4269     return false;
4270 
4271   if (!Info.CheckCallLimit(CallLoc))
4272     return false;
4273 
4274   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
4275 
4276   // For a trivial copy or move assignment, perform an APValue copy. This is
4277   // essential for unions, where the operations performed by the assignment
4278   // operator cannot be represented as statements.
4279   //
4280   // Skip this for non-union classes with no fields; in that case, the defaulted
4281   // copy/move does not actually read the object.
4282   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
4283   if (MD && MD->isDefaulted() &&
4284       (MD->getParent()->isUnion() ||
4285        (MD->isTrivial() && hasFields(MD->getParent())))) {
4286     assert(This &&
4287            (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4288     LValue RHS;
4289     RHS.setFrom(Info.Ctx, ArgValues[0]);
4290     APValue RHSValue;
4291     if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4292                                         RHS, RHSValue))
4293       return false;
4294     if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4295                           RHSValue))
4296       return false;
4297     This->moveInto(Result);
4298     return true;
4299   } else if (MD && isLambdaCallOperator(MD)) {
4300     // We're in a lambda; determine the lambda capture field maps.
4301     MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4302                                       Frame.LambdaThisCaptureField);
4303   }
4304 
4305   StmtResult Ret = {Result, ResultSlot};
4306   EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
4307   if (ESR == ESR_Succeeded) {
4308     if (Callee->getReturnType()->isVoidType())
4309       return true;
4310     Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
4311   }
4312   return ESR == ESR_Returned;
4313 }
4314 
4315 /// Evaluate a constructor call.
4316 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4317                                   APValue *ArgValues,
4318                                   const CXXConstructorDecl *Definition,
4319                                   EvalInfo &Info, APValue &Result) {
4320   SourceLocation CallLoc = E->getExprLoc();
4321   if (!Info.CheckCallLimit(CallLoc))
4322     return false;
4323 
4324   const CXXRecordDecl *RD = Definition->getParent();
4325   if (RD->getNumVBases()) {
4326     Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
4327     return false;
4328   }
4329 
4330   EvalInfo::EvaluatingConstructorRAII EvalObj(
4331       Info, {This.getLValueBase(), This.CallIndex});
4332   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
4333 
4334   // FIXME: Creating an APValue just to hold a nonexistent return value is
4335   // wasteful.
4336   APValue RetVal;
4337   StmtResult Ret = {RetVal, nullptr};
4338 
4339   // If it's a delegating constructor, delegate.
4340   if (Definition->isDelegatingConstructor()) {
4341     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
4342     {
4343       FullExpressionRAII InitScope(Info);
4344       if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4345         return false;
4346     }
4347     return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4348   }
4349 
4350   // For a trivial copy or move constructor, perform an APValue copy. This is
4351   // essential for unions (or classes with anonymous union members), where the
4352   // operations performed by the constructor cannot be represented by
4353   // ctor-initializers.
4354   //
4355   // Skip this for empty non-union classes; we should not perform an
4356   // lvalue-to-rvalue conversion on them because their copy constructor does not
4357   // actually read them.
4358   if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
4359       (Definition->getParent()->isUnion() ||
4360        (Definition->isTrivial() && hasFields(Definition->getParent())))) {
4361     LValue RHS;
4362     RHS.setFrom(Info.Ctx, ArgValues[0]);
4363     return handleLValueToRValueConversion(
4364         Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4365         RHS, Result);
4366   }
4367 
4368   // Reserve space for the struct members.
4369   if (!RD->isUnion() && Result.isUninit())
4370     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
4371                      std::distance(RD->field_begin(), RD->field_end()));
4372 
4373   if (RD->isInvalidDecl()) return false;
4374   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4375 
4376   // A scope for temporaries lifetime-extended by reference members.
4377   BlockScopeRAII LifetimeExtendedScope(Info);
4378 
4379   bool Success = true;
4380   unsigned BasesSeen = 0;
4381 #ifndef NDEBUG
4382   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4383 #endif
4384   for (const auto *I : Definition->inits()) {
4385     LValue Subobject = This;
4386     LValue SubobjectParent = This;
4387     APValue *Value = &Result;
4388 
4389     // Determine the subobject to initialize.
4390     FieldDecl *FD = nullptr;
4391     if (I->isBaseInitializer()) {
4392       QualType BaseType(I->getBaseClass(), 0);
4393 #ifndef NDEBUG
4394       // Non-virtual base classes are initialized in the order in the class
4395       // definition. We have already checked for virtual base classes.
4396       assert(!BaseIt->isVirtual() && "virtual base for literal type");
4397       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4398              "base class initializers not in expected order");
4399       ++BaseIt;
4400 #endif
4401       if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
4402                                   BaseType->getAsCXXRecordDecl(), &Layout))
4403         return false;
4404       Value = &Result.getStructBase(BasesSeen++);
4405     } else if ((FD = I->getMember())) {
4406       if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
4407         return false;
4408       if (RD->isUnion()) {
4409         Result = APValue(FD);
4410         Value = &Result.getUnionValue();
4411       } else {
4412         Value = &Result.getStructField(FD->getFieldIndex());
4413       }
4414     } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
4415       // Walk the indirect field decl's chain to find the object to initialize,
4416       // and make sure we've initialized every step along it.
4417       auto IndirectFieldChain = IFD->chain();
4418       for (auto *C : IndirectFieldChain) {
4419         FD = cast<FieldDecl>(C);
4420         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4421         // Switch the union field if it differs. This happens if we had
4422         // preceding zero-initialization, and we're now initializing a union
4423         // subobject other than the first.
4424         // FIXME: In this case, the values of the other subobjects are
4425         // specified, since zero-initialization sets all padding bits to zero.
4426         if (Value->isUninit() ||
4427             (Value->isUnion() && Value->getUnionField() != FD)) {
4428           if (CD->isUnion())
4429             *Value = APValue(FD);
4430           else
4431             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
4432                              std::distance(CD->field_begin(), CD->field_end()));
4433         }
4434         // Store Subobject as its parent before updating it for the last element
4435         // in the chain.
4436         if (C == IndirectFieldChain.back())
4437           SubobjectParent = Subobject;
4438         if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
4439           return false;
4440         if (CD->isUnion())
4441           Value = &Value->getUnionValue();
4442         else
4443           Value = &Value->getStructField(FD->getFieldIndex());
4444       }
4445     } else {
4446       llvm_unreachable("unknown base initializer kind");
4447     }
4448 
4449     // Need to override This for implicit field initializers as in this case
4450     // This refers to innermost anonymous struct/union containing initializer,
4451     // not to currently constructed class.
4452     const Expr *Init = I->getInit();
4453     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &SubobjectParent,
4454                                   isa<CXXDefaultInitExpr>(Init));
4455     FullExpressionRAII InitScope(Info);
4456     if (!EvaluateInPlace(*Value, Info, Subobject, Init) ||
4457         (FD && FD->isBitField() &&
4458          !truncateBitfieldValue(Info, Init, *Value, FD))) {
4459       // If we're checking for a potential constant expression, evaluate all
4460       // initializers even if some of them fail.
4461       if (!Info.noteFailure())
4462         return false;
4463       Success = false;
4464     }
4465   }
4466 
4467   return Success &&
4468          EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
4469 }
4470 
4471 static bool HandleConstructorCall(const Expr *E, const LValue &This,
4472                                   ArrayRef<const Expr*> Args,
4473                                   const CXXConstructorDecl *Definition,
4474                                   EvalInfo &Info, APValue &Result) {
4475   ArgVector ArgValues(Args.size());
4476   if (!EvaluateArgs(Args, ArgValues, Info))
4477     return false;
4478 
4479   return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4480                                Info, Result);
4481 }
4482 
4483 //===----------------------------------------------------------------------===//
4484 // Generic Evaluation
4485 //===----------------------------------------------------------------------===//
4486 namespace {
4487 
4488 template <class Derived>
4489 class ExprEvaluatorBase
4490   : public ConstStmtVisitor<Derived, bool> {
4491 private:
4492   Derived &getDerived() { return static_cast<Derived&>(*this); }
4493   bool DerivedSuccess(const APValue &V, const Expr *E) {
4494     return getDerived().Success(V, E);
4495   }
4496   bool DerivedZeroInitialization(const Expr *E) {
4497     return getDerived().ZeroInitialization(E);
4498   }
4499 
4500   // Check whether a conditional operator with a non-constant condition is a
4501   // potential constant expression. If neither arm is a potential constant
4502   // expression, then the conditional operator is not either.
4503   template<typename ConditionalOperator>
4504   void CheckPotentialConstantConditional(const ConditionalOperator *E) {
4505     assert(Info.checkingPotentialConstantExpression());
4506 
4507     // Speculatively evaluate both arms.
4508     SmallVector<PartialDiagnosticAt, 8> Diag;
4509     {
4510       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4511       StmtVisitorTy::Visit(E->getFalseExpr());
4512       if (Diag.empty())
4513         return;
4514     }
4515 
4516     {
4517       SpeculativeEvaluationRAII Speculate(Info, &Diag);
4518       Diag.clear();
4519       StmtVisitorTy::Visit(E->getTrueExpr());
4520       if (Diag.empty())
4521         return;
4522     }
4523 
4524     Error(E, diag::note_constexpr_conditional_never_const);
4525   }
4526 
4527 
4528   template<typename ConditionalOperator>
4529   bool HandleConditionalOperator(const ConditionalOperator *E) {
4530     bool BoolResult;
4531     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
4532       if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
4533         CheckPotentialConstantConditional(E);
4534         return false;
4535       }
4536       if (Info.noteFailure()) {
4537         StmtVisitorTy::Visit(E->getTrueExpr());
4538         StmtVisitorTy::Visit(E->getFalseExpr());
4539       }
4540       return false;
4541     }
4542 
4543     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4544     return StmtVisitorTy::Visit(EvalExpr);
4545   }
4546 
4547 protected:
4548   EvalInfo &Info;
4549   typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
4550   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4551 
4552   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4553     return Info.CCEDiag(E, D);
4554   }
4555 
4556   bool ZeroInitialization(const Expr *E) { return Error(E); }
4557 
4558 public:
4559   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4560 
4561   EvalInfo &getEvalInfo() { return Info; }
4562 
4563   /// Report an evaluation error. This should only be called when an error is
4564   /// first discovered. When propagating an error, just return false.
4565   bool Error(const Expr *E, diag::kind D) {
4566     Info.FFDiag(E, D);
4567     return false;
4568   }
4569   bool Error(const Expr *E) {
4570     return Error(E, diag::note_invalid_subexpr_in_const_expr);
4571   }
4572 
4573   bool VisitStmt(const Stmt *) {
4574     llvm_unreachable("Expression evaluator should not be called on stmts");
4575   }
4576   bool VisitExpr(const Expr *E) {
4577     return Error(E);
4578   }
4579 
4580   bool VisitParenExpr(const ParenExpr *E)
4581     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4582   bool VisitUnaryExtension(const UnaryOperator *E)
4583     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4584   bool VisitUnaryPlus(const UnaryOperator *E)
4585     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4586   bool VisitChooseExpr(const ChooseExpr *E)
4587     { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
4588   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
4589     { return StmtVisitorTy::Visit(E->getResultExpr()); }
4590   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
4591     { return StmtVisitorTy::Visit(E->getReplacement()); }
4592   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
4593     { return StmtVisitorTy::Visit(E->getExpr()); }
4594   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4595     // The initializer may not have been parsed yet, or might be erroneous.
4596     if (!E->getExpr())
4597       return Error(E);
4598     return StmtVisitorTy::Visit(E->getExpr());
4599   }
4600   // We cannot create any objects for which cleanups are required, so there is
4601   // nothing to do here; all cleanups must come from unevaluated subexpressions.
4602   bool VisitExprWithCleanups(const ExprWithCleanups *E)
4603     { return StmtVisitorTy::Visit(E->getSubExpr()); }
4604 
4605   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
4606     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4607     return static_cast<Derived*>(this)->VisitCastExpr(E);
4608   }
4609   bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
4610     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4611     return static_cast<Derived*>(this)->VisitCastExpr(E);
4612   }
4613 
4614   bool VisitBinaryOperator(const BinaryOperator *E) {
4615     switch (E->getOpcode()) {
4616     default:
4617       return Error(E);
4618 
4619     case BO_Comma:
4620       VisitIgnoredValue(E->getLHS());
4621       return StmtVisitorTy::Visit(E->getRHS());
4622 
4623     case BO_PtrMemD:
4624     case BO_PtrMemI: {
4625       LValue Obj;
4626       if (!HandleMemberPointerAccess(Info, E, Obj))
4627         return false;
4628       APValue Result;
4629       if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
4630         return false;
4631       return DerivedSuccess(Result, E);
4632     }
4633     }
4634   }
4635 
4636   bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
4637     // Evaluate and cache the common expression. We treat it as a temporary,
4638     // even though it's not quite the same thing.
4639     if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
4640                   Info, E->getCommon()))
4641       return false;
4642 
4643     return HandleConditionalOperator(E);
4644   }
4645 
4646   bool VisitConditionalOperator(const ConditionalOperator *E) {
4647     bool IsBcpCall = false;
4648     // If the condition (ignoring parens) is a __builtin_constant_p call,
4649     // the result is a constant expression if it can be folded without
4650     // side-effects. This is an important GNU extension. See GCC PR38377
4651     // for discussion.
4652     if (const CallExpr *CallCE =
4653           dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
4654       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
4655         IsBcpCall = true;
4656 
4657     // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4658     // constant expression; we can't check whether it's potentially foldable.
4659     if (Info.checkingPotentialConstantExpression() && IsBcpCall)
4660       return false;
4661 
4662     FoldConstant Fold(Info, IsBcpCall);
4663     if (!HandleConditionalOperator(E)) {
4664       Fold.keepDiagnostics();
4665       return false;
4666     }
4667 
4668     return true;
4669   }
4670 
4671   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
4672     if (APValue *Value = Info.CurrentCall->getTemporary(E))
4673       return DerivedSuccess(*Value, E);
4674 
4675     const Expr *Source = E->getSourceExpr();
4676     if (!Source)
4677       return Error(E);
4678     if (Source == E) { // sanity checking.
4679       assert(0 && "OpaqueValueExpr recursively refers to itself");
4680       return Error(E);
4681     }
4682     return StmtVisitorTy::Visit(Source);
4683   }
4684 
4685   bool VisitCallExpr(const CallExpr *E) {
4686     APValue Result;
4687     if (!handleCallExpr(E, Result, nullptr))
4688       return false;
4689     return DerivedSuccess(Result, E);
4690   }
4691 
4692   bool handleCallExpr(const CallExpr *E, APValue &Result,
4693                      const LValue *ResultSlot) {
4694     const Expr *Callee = E->getCallee()->IgnoreParens();
4695     QualType CalleeType = Callee->getType();
4696 
4697     const FunctionDecl *FD = nullptr;
4698     LValue *This = nullptr, ThisVal;
4699     auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
4700     bool HasQualifier = false;
4701 
4702     // Extract function decl and 'this' pointer from the callee.
4703     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
4704       const ValueDecl *Member = nullptr;
4705       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4706         // Explicit bound member calls, such as x.f() or p->g();
4707         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
4708           return false;
4709         Member = ME->getMemberDecl();
4710         This = &ThisVal;
4711         HasQualifier = ME->hasQualifier();
4712       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4713         // Indirect bound member calls ('.*' or '->*').
4714         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4715         if (!Member) return false;
4716         This = &ThisVal;
4717       } else
4718         return Error(Callee);
4719 
4720       FD = dyn_cast<FunctionDecl>(Member);
4721       if (!FD)
4722         return Error(Callee);
4723     } else if (CalleeType->isFunctionPointerType()) {
4724       LValue Call;
4725       if (!EvaluatePointer(Callee, Call, Info))
4726         return false;
4727 
4728       if (!Call.getLValueOffset().isZero())
4729         return Error(Callee);
4730       FD = dyn_cast_or_null<FunctionDecl>(
4731                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
4732       if (!FD)
4733         return Error(Callee);
4734       // Don't call function pointers which have been cast to some other type.
4735       // Per DR (no number yet), the caller and callee can differ in noexcept.
4736       if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4737         CalleeType->getPointeeType(), FD->getType())) {
4738         return Error(E);
4739       }
4740 
4741       // Overloaded operator calls to member functions are represented as normal
4742       // calls with '*this' as the first argument.
4743       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4744       if (MD && !MD->isStatic()) {
4745         // FIXME: When selecting an implicit conversion for an overloaded
4746         // operator delete, we sometimes try to evaluate calls to conversion
4747         // operators without a 'this' parameter!
4748         if (Args.empty())
4749           return Error(E);
4750 
4751         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4752           return false;
4753         This = &ThisVal;
4754         Args = Args.slice(1);
4755       } else if (MD && MD->isLambdaStaticInvoker()) {
4756         // Map the static invoker for the lambda back to the call operator.
4757         // Conveniently, we don't have to slice out the 'this' argument (as is
4758         // being done for the non-static case), since a static member function
4759         // doesn't have an implicit argument passed in.
4760         const CXXRecordDecl *ClosureClass = MD->getParent();
4761         assert(
4762             ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4763             "Number of captures must be zero for conversion to function-ptr");
4764 
4765         const CXXMethodDecl *LambdaCallOp =
4766             ClosureClass->getLambdaCallOperator();
4767 
4768         // Set 'FD', the function that will be called below, to the call
4769         // operator.  If the closure object represents a generic lambda, find
4770         // the corresponding specialization of the call operator.
4771 
4772         if (ClosureClass->isGenericLambda()) {
4773           assert(MD->isFunctionTemplateSpecialization() &&
4774                  "A generic lambda's static-invoker function must be a "
4775                  "template specialization");
4776           const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4777           FunctionTemplateDecl *CallOpTemplate =
4778               LambdaCallOp->getDescribedFunctionTemplate();
4779           void *InsertPos = nullptr;
4780           FunctionDecl *CorrespondingCallOpSpecialization =
4781               CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4782           assert(CorrespondingCallOpSpecialization &&
4783                  "We must always have a function call operator specialization "
4784                  "that corresponds to our static invoker specialization");
4785           FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4786         } else
4787           FD = LambdaCallOp;
4788       }
4789 
4790 
4791     } else
4792       return Error(E);
4793 
4794     if (This && !This->checkSubobject(Info, E, CSK_This))
4795       return false;
4796 
4797     // DR1358 allows virtual constexpr functions in some cases. Don't allow
4798     // calls to such functions in constant expressions.
4799     if (This && !HasQualifier &&
4800         isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4801       return Error(E, diag::note_constexpr_virtual_call);
4802 
4803     const FunctionDecl *Definition = nullptr;
4804     Stmt *Body = FD->getBody(Definition);
4805 
4806     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4807         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4808                             Result, ResultSlot))
4809       return false;
4810 
4811     return true;
4812   }
4813 
4814   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
4815     return StmtVisitorTy::Visit(E->getInitializer());
4816   }
4817   bool VisitInitListExpr(const InitListExpr *E) {
4818     if (E->getNumInits() == 0)
4819       return DerivedZeroInitialization(E);
4820     if (E->getNumInits() == 1)
4821       return StmtVisitorTy::Visit(E->getInit(0));
4822     return Error(E);
4823   }
4824   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
4825     return DerivedZeroInitialization(E);
4826   }
4827   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
4828     return DerivedZeroInitialization(E);
4829   }
4830   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
4831     return DerivedZeroInitialization(E);
4832   }
4833 
4834   /// A member expression where the object is a prvalue is itself a prvalue.
4835   bool VisitMemberExpr(const MemberExpr *E) {
4836     assert(!E->isArrow() && "missing call to bound member function?");
4837 
4838     APValue Val;
4839     if (!Evaluate(Val, Info, E->getBase()))
4840       return false;
4841 
4842     QualType BaseTy = E->getBase()->getType();
4843 
4844     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
4845     if (!FD) return Error(E);
4846     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
4847     assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4848            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4849 
4850     CompleteObject Obj(&Val, BaseTy, true);
4851     SubobjectDesignator Designator(BaseTy);
4852     Designator.addDeclUnchecked(FD);
4853 
4854     APValue Result;
4855     return extractSubobject(Info, E, Obj, Designator, Result) &&
4856            DerivedSuccess(Result, E);
4857   }
4858 
4859   bool VisitCastExpr(const CastExpr *E) {
4860     switch (E->getCastKind()) {
4861     default:
4862       break;
4863 
4864     case CK_AtomicToNonAtomic: {
4865       APValue AtomicVal;
4866       // This does not need to be done in place even for class/array types:
4867       // atomic-to-non-atomic conversion implies copying the object
4868       // representation.
4869       if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
4870         return false;
4871       return DerivedSuccess(AtomicVal, E);
4872     }
4873 
4874     case CK_NoOp:
4875     case CK_UserDefinedConversion:
4876       return StmtVisitorTy::Visit(E->getSubExpr());
4877 
4878     case CK_LValueToRValue: {
4879       LValue LVal;
4880       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4881         return false;
4882       APValue RVal;
4883       // Note, we use the subexpression's type in order to retain cv-qualifiers.
4884       if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
4885                                           LVal, RVal))
4886         return false;
4887       return DerivedSuccess(RVal, E);
4888     }
4889     }
4890 
4891     return Error(E);
4892   }
4893 
4894   bool VisitUnaryPostInc(const UnaryOperator *UO) {
4895     return VisitUnaryPostIncDec(UO);
4896   }
4897   bool VisitUnaryPostDec(const UnaryOperator *UO) {
4898     return VisitUnaryPostIncDec(UO);
4899   }
4900   bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
4901     if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
4902       return Error(UO);
4903 
4904     LValue LVal;
4905     if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4906       return false;
4907     APValue RVal;
4908     if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4909                       UO->isIncrementOp(), &RVal))
4910       return false;
4911     return DerivedSuccess(RVal, UO);
4912   }
4913 
4914   bool VisitStmtExpr(const StmtExpr *E) {
4915     // We will have checked the full-expressions inside the statement expression
4916     // when they were completed, and don't need to check them again now.
4917     if (Info.checkingForOverflow())
4918       return Error(E);
4919 
4920     BlockScopeRAII Scope(Info);
4921     const CompoundStmt *CS = E->getSubStmt();
4922     if (CS->body_empty())
4923       return true;
4924 
4925     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4926                                            BE = CS->body_end();
4927          /**/; ++BI) {
4928       if (BI + 1 == BE) {
4929         const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4930         if (!FinalExpr) {
4931           Info.FFDiag((*BI)->getLocStart(),
4932                     diag::note_constexpr_stmt_expr_unsupported);
4933           return false;
4934         }
4935         return this->Visit(FinalExpr);
4936       }
4937 
4938       APValue ReturnValue;
4939       StmtResult Result = { ReturnValue, nullptr };
4940       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
4941       if (ESR != ESR_Succeeded) {
4942         // FIXME: If the statement-expression terminated due to 'return',
4943         // 'break', or 'continue', it would be nice to propagate that to
4944         // the outer statement evaluation rather than bailing out.
4945         if (ESR != ESR_Failed)
4946           Info.FFDiag((*BI)->getLocStart(),
4947                     diag::note_constexpr_stmt_expr_unsupported);
4948         return false;
4949       }
4950     }
4951 
4952     llvm_unreachable("Return from function from the loop above.");
4953   }
4954 
4955   /// Visit a value which is evaluated, but whose value is ignored.
4956   void VisitIgnoredValue(const Expr *E) {
4957     EvaluateIgnoredValue(Info, E);
4958   }
4959 
4960   /// Potentially visit a MemberExpr's base expression.
4961   void VisitIgnoredBaseExpression(const Expr *E) {
4962     // While MSVC doesn't evaluate the base expression, it does diagnose the
4963     // presence of side-effecting behavior.
4964     if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4965       return;
4966     VisitIgnoredValue(E);
4967   }
4968 };
4969 
4970 }
4971 
4972 //===----------------------------------------------------------------------===//
4973 // Common base class for lvalue and temporary evaluation.
4974 //===----------------------------------------------------------------------===//
4975 namespace {
4976 template<class Derived>
4977 class LValueExprEvaluatorBase
4978   : public ExprEvaluatorBase<Derived> {
4979 protected:
4980   LValue &Result;
4981   bool InvalidBaseOK;
4982   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
4983   typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
4984 
4985   bool Success(APValue::LValueBase B) {
4986     Result.set(B);
4987     return true;
4988   }
4989 
4990   bool evaluatePointer(const Expr *E, LValue &Result) {
4991     return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4992   }
4993 
4994 public:
4995   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4996       : ExprEvaluatorBaseTy(Info), Result(Result),
4997         InvalidBaseOK(InvalidBaseOK) {}
4998 
4999   bool Success(const APValue &V, const Expr *E) {
5000     Result.setFrom(this->Info.Ctx, V);
5001     return true;
5002   }
5003 
5004   bool VisitMemberExpr(const MemberExpr *E) {
5005     // Handle non-static data members.
5006     QualType BaseTy;
5007     bool EvalOK;
5008     if (E->isArrow()) {
5009       EvalOK = evaluatePointer(E->getBase(), Result);
5010       BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
5011     } else if (E->getBase()->isRValue()) {
5012       assert(E->getBase()->getType()->isRecordType());
5013       EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
5014       BaseTy = E->getBase()->getType();
5015     } else {
5016       EvalOK = this->Visit(E->getBase());
5017       BaseTy = E->getBase()->getType();
5018     }
5019     if (!EvalOK) {
5020       if (!InvalidBaseOK)
5021         return false;
5022       Result.setInvalid(E);
5023       return true;
5024     }
5025 
5026     const ValueDecl *MD = E->getMemberDecl();
5027     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5028       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5029              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5030       (void)BaseTy;
5031       if (!HandleLValueMember(this->Info, E, Result, FD))
5032         return false;
5033     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
5034       if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5035         return false;
5036     } else
5037       return this->Error(E);
5038 
5039     if (MD->getType()->isReferenceType()) {
5040       APValue RefValue;
5041       if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
5042                                           RefValue))
5043         return false;
5044       return Success(RefValue, E);
5045     }
5046     return true;
5047   }
5048 
5049   bool VisitBinaryOperator(const BinaryOperator *E) {
5050     switch (E->getOpcode()) {
5051     default:
5052       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5053 
5054     case BO_PtrMemD:
5055     case BO_PtrMemI:
5056       return HandleMemberPointerAccess(this->Info, E, Result);
5057     }
5058   }
5059 
5060   bool VisitCastExpr(const CastExpr *E) {
5061     switch (E->getCastKind()) {
5062     default:
5063       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5064 
5065     case CK_DerivedToBase:
5066     case CK_UncheckedDerivedToBase:
5067       if (!this->Visit(E->getSubExpr()))
5068         return false;
5069 
5070       // Now figure out the necessary offset to add to the base LV to get from
5071       // the derived class to the base class.
5072       return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5073                                   Result);
5074     }
5075   }
5076 };
5077 }
5078 
5079 //===----------------------------------------------------------------------===//
5080 // LValue Evaluation
5081 //
5082 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5083 // function designators (in C), decl references to void objects (in C), and
5084 // temporaries (if building with -Wno-address-of-temporary).
5085 //
5086 // LValue evaluation produces values comprising a base expression of one of the
5087 // following types:
5088 // - Declarations
5089 //  * VarDecl
5090 //  * FunctionDecl
5091 // - Literals
5092 //  * CompoundLiteralExpr in C (and in global scope in C++)
5093 //  * StringLiteral
5094 //  * CXXTypeidExpr
5095 //  * PredefinedExpr
5096 //  * ObjCStringLiteralExpr
5097 //  * ObjCEncodeExpr
5098 //  * AddrLabelExpr
5099 //  * BlockExpr
5100 //  * CallExpr for a MakeStringConstant builtin
5101 // - Locals and temporaries
5102 //  * MaterializeTemporaryExpr
5103 //  * Any Expr, with a CallIndex indicating the function in which the temporary
5104 //    was evaluated, for cases where the MaterializeTemporaryExpr is missing
5105 //    from the AST (FIXME).
5106 //  * A MaterializeTemporaryExpr that has static storage duration, with no
5107 //    CallIndex, for a lifetime-extended temporary.
5108 // plus an offset in bytes.
5109 //===----------------------------------------------------------------------===//
5110 namespace {
5111 class LValueExprEvaluator
5112   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
5113 public:
5114   LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5115     LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
5116 
5117   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
5118   bool VisitUnaryPreIncDec(const UnaryOperator *UO);
5119 
5120   bool VisitDeclRefExpr(const DeclRefExpr *E);
5121   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
5122   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
5123   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5124   bool VisitMemberExpr(const MemberExpr *E);
5125   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5126   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
5127   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
5128   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
5129   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5130   bool VisitUnaryDeref(const UnaryOperator *E);
5131   bool VisitUnaryReal(const UnaryOperator *E);
5132   bool VisitUnaryImag(const UnaryOperator *E);
5133   bool VisitUnaryPreInc(const UnaryOperator *UO) {
5134     return VisitUnaryPreIncDec(UO);
5135   }
5136   bool VisitUnaryPreDec(const UnaryOperator *UO) {
5137     return VisitUnaryPreIncDec(UO);
5138   }
5139   bool VisitBinAssign(const BinaryOperator *BO);
5140   bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
5141 
5142   bool VisitCastExpr(const CastExpr *E) {
5143     switch (E->getCastKind()) {
5144     default:
5145       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5146 
5147     case CK_LValueBitCast:
5148       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5149       if (!Visit(E->getSubExpr()))
5150         return false;
5151       Result.Designator.setInvalid();
5152       return true;
5153 
5154     case CK_BaseToDerived:
5155       if (!Visit(E->getSubExpr()))
5156         return false;
5157       return HandleBaseToDerivedCast(Info, E, Result);
5158     }
5159   }
5160 };
5161 } // end anonymous namespace
5162 
5163 /// Evaluate an expression as an lvalue. This can be legitimately called on
5164 /// expressions which are not glvalues, in three cases:
5165 ///  * function designators in C, and
5166 ///  * "extern void" objects
5167 ///  * @selector() expressions in Objective-C
5168 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5169                            bool InvalidBaseOK) {
5170   assert(E->isGLValue() || E->getType()->isFunctionType() ||
5171          E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
5172   return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5173 }
5174 
5175 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
5176   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
5177     return Success(FD);
5178   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
5179     return VisitVarDecl(E, VD);
5180   if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
5181     return Visit(BD->getBinding());
5182   return Error(E);
5183 }
5184 
5185 
5186 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
5187 
5188   // If we are within a lambda's call operator, check whether the 'VD' referred
5189   // to within 'E' actually represents a lambda-capture that maps to a
5190   // data-member/field within the closure object, and if so, evaluate to the
5191   // field or what the field refers to.
5192   if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5193     if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5194       if (Info.checkingPotentialConstantExpression())
5195         return false;
5196       // Start with 'Result' referring to the complete closure object...
5197       Result = *Info.CurrentCall->This;
5198       // ... then update it to refer to the field of the closure object
5199       // that represents the capture.
5200       if (!HandleLValueMember(Info, E, Result, FD))
5201         return false;
5202       // And if the field is of reference type, update 'Result' to refer to what
5203       // the field refers to.
5204       if (FD->getType()->isReferenceType()) {
5205         APValue RVal;
5206         if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5207                                             RVal))
5208           return false;
5209         Result.setFrom(Info.Ctx, RVal);
5210       }
5211       return true;
5212     }
5213   }
5214   CallStackFrame *Frame = nullptr;
5215   if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5216     // Only if a local variable was declared in the function currently being
5217     // evaluated, do we expect to be able to find its value in the current
5218     // frame. (Otherwise it was likely declared in an enclosing context and
5219     // could either have a valid evaluatable value (for e.g. a constexpr
5220     // variable) or be ill-formed (and trigger an appropriate evaluation
5221     // diagnostic)).
5222     if (Info.CurrentCall->Callee &&
5223         Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5224       Frame = Info.CurrentCall;
5225     }
5226   }
5227 
5228   if (!VD->getType()->isReferenceType()) {
5229     if (Frame) {
5230       Result.set(VD, Frame->Index);
5231       return true;
5232     }
5233     return Success(VD);
5234   }
5235 
5236   APValue *V;
5237   if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
5238     return false;
5239   if (V->isUninit()) {
5240     if (!Info.checkingPotentialConstantExpression())
5241       Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
5242     return false;
5243   }
5244   return Success(*V, E);
5245 }
5246 
5247 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5248     const MaterializeTemporaryExpr *E) {
5249   // Walk through the expression to find the materialized temporary itself.
5250   SmallVector<const Expr *, 2> CommaLHSs;
5251   SmallVector<SubobjectAdjustment, 2> Adjustments;
5252   const Expr *Inner = E->GetTemporaryExpr()->
5253       skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
5254 
5255   // If we passed any comma operators, evaluate their LHSs.
5256   for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5257     if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5258       return false;
5259 
5260   // A materialized temporary with static storage duration can appear within the
5261   // result of a constant expression evaluation, so we need to preserve its
5262   // value for use outside this evaluation.
5263   APValue *Value;
5264   if (E->getStorageDuration() == SD_Static) {
5265     Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
5266     *Value = APValue();
5267     Result.set(E);
5268   } else {
5269     Value = &Info.CurrentCall->
5270         createTemporary(E, E->getStorageDuration() == SD_Automatic);
5271     Result.set(E, Info.CurrentCall->Index);
5272   }
5273 
5274   QualType Type = Inner->getType();
5275 
5276   // Materialize the temporary itself.
5277   if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5278       (E->getStorageDuration() == SD_Static &&
5279        !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5280     *Value = APValue();
5281     return false;
5282   }
5283 
5284   // Adjust our lvalue to refer to the desired subobject.
5285   for (unsigned I = Adjustments.size(); I != 0; /**/) {
5286     --I;
5287     switch (Adjustments[I].Kind) {
5288     case SubobjectAdjustment::DerivedToBaseAdjustment:
5289       if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5290                                 Type, Result))
5291         return false;
5292       Type = Adjustments[I].DerivedToBase.BasePath->getType();
5293       break;
5294 
5295     case SubobjectAdjustment::FieldAdjustment:
5296       if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5297         return false;
5298       Type = Adjustments[I].Field->getType();
5299       break;
5300 
5301     case SubobjectAdjustment::MemberPointerAdjustment:
5302       if (!HandleMemberPointerAccess(this->Info, Type, Result,
5303                                      Adjustments[I].Ptr.RHS))
5304         return false;
5305       Type = Adjustments[I].Ptr.MPT->getPointeeType();
5306       break;
5307     }
5308   }
5309 
5310   return true;
5311 }
5312 
5313 bool
5314 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
5315   assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5316          "lvalue compound literal in c++?");
5317   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5318   // only see this when folding in C, so there's no standard to follow here.
5319   return Success(E);
5320 }
5321 
5322 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
5323   if (!E->isPotentiallyEvaluated())
5324     return Success(E);
5325 
5326   Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
5327     << E->getExprOperand()->getType()
5328     << E->getExprOperand()->getSourceRange();
5329   return false;
5330 }
5331 
5332 bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5333   return Success(E);
5334 }
5335 
5336 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
5337   // Handle static data members.
5338   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
5339     VisitIgnoredBaseExpression(E->getBase());
5340     return VisitVarDecl(E, VD);
5341   }
5342 
5343   // Handle static member functions.
5344   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5345     if (MD->isStatic()) {
5346       VisitIgnoredBaseExpression(E->getBase());
5347       return Success(MD);
5348     }
5349   }
5350 
5351   // Handle non-static data members.
5352   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
5353 }
5354 
5355 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
5356   // FIXME: Deal with vectors as array subscript bases.
5357   if (E->getBase()->getType()->isVectorType())
5358     return Error(E);
5359 
5360   bool Success = true;
5361   if (!evaluatePointer(E->getBase(), Result)) {
5362     if (!Info.noteFailure())
5363       return false;
5364     Success = false;
5365   }
5366 
5367   APSInt Index;
5368   if (!EvaluateInteger(E->getIdx(), Index, Info))
5369     return false;
5370 
5371   return Success &&
5372          HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
5373 }
5374 
5375 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
5376   return evaluatePointer(E->getSubExpr(), Result);
5377 }
5378 
5379 bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5380   if (!Visit(E->getSubExpr()))
5381     return false;
5382   // __real is a no-op on scalar lvalues.
5383   if (E->getSubExpr()->getType()->isAnyComplexType())
5384     HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5385   return true;
5386 }
5387 
5388 bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5389   assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5390          "lvalue __imag__ on scalar?");
5391   if (!Visit(E->getSubExpr()))
5392     return false;
5393   HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5394   return true;
5395 }
5396 
5397 bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
5398   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5399     return Error(UO);
5400 
5401   if (!this->Visit(UO->getSubExpr()))
5402     return false;
5403 
5404   return handleIncDec(
5405       this->Info, UO, Result, UO->getSubExpr()->getType(),
5406       UO->isIncrementOp(), nullptr);
5407 }
5408 
5409 bool LValueExprEvaluator::VisitCompoundAssignOperator(
5410     const CompoundAssignOperator *CAO) {
5411   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5412     return Error(CAO);
5413 
5414   APValue RHS;
5415 
5416   // The overall lvalue result is the result of evaluating the LHS.
5417   if (!this->Visit(CAO->getLHS())) {
5418     if (Info.noteFailure())
5419       Evaluate(RHS, this->Info, CAO->getRHS());
5420     return false;
5421   }
5422 
5423   if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5424     return false;
5425 
5426   return handleCompoundAssignment(
5427       this->Info, CAO,
5428       Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5429       CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
5430 }
5431 
5432 bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
5433   if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
5434     return Error(E);
5435 
5436   APValue NewVal;
5437 
5438   if (!this->Visit(E->getLHS())) {
5439     if (Info.noteFailure())
5440       Evaluate(NewVal, this->Info, E->getRHS());
5441     return false;
5442   }
5443 
5444   if (!Evaluate(NewVal, this->Info, E->getRHS()))
5445     return false;
5446 
5447   return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
5448                           NewVal);
5449 }
5450 
5451 //===----------------------------------------------------------------------===//
5452 // Pointer Evaluation
5453 //===----------------------------------------------------------------------===//
5454 
5455 /// \brief Attempts to compute the number of bytes available at the pointer
5456 /// returned by a function with the alloc_size attribute. Returns true if we
5457 /// were successful. Places an unsigned number into `Result`.
5458 ///
5459 /// This expects the given CallExpr to be a call to a function with an
5460 /// alloc_size attribute.
5461 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5462                                             const CallExpr *Call,
5463                                             llvm::APInt &Result) {
5464   const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5465 
5466   // alloc_size args are 1-indexed, 0 means not present.
5467   assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5468   unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5469   unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5470   if (Call->getNumArgs() <= SizeArgNo)
5471     return false;
5472 
5473   auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5474     if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5475       return false;
5476     if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5477       return false;
5478     Into = Into.zextOrSelf(BitsInSizeT);
5479     return true;
5480   };
5481 
5482   APSInt SizeOfElem;
5483   if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5484     return false;
5485 
5486   if (!AllocSize->getNumElemsParam()) {
5487     Result = std::move(SizeOfElem);
5488     return true;
5489   }
5490 
5491   APSInt NumberOfElems;
5492   // Argument numbers start at 1
5493   unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5494   if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5495     return false;
5496 
5497   bool Overflow;
5498   llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5499   if (Overflow)
5500     return false;
5501 
5502   Result = std::move(BytesAvailable);
5503   return true;
5504 }
5505 
5506 /// \brief Convenience function. LVal's base must be a call to an alloc_size
5507 /// function.
5508 static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5509                                             const LValue &LVal,
5510                                             llvm::APInt &Result) {
5511   assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5512          "Can't get the size of a non alloc_size function");
5513   const auto *Base = LVal.getLValueBase().get<const Expr *>();
5514   const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5515   return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5516 }
5517 
5518 /// \brief Attempts to evaluate the given LValueBase as the result of a call to
5519 /// a function with the alloc_size attribute. If it was possible to do so, this
5520 /// function will return true, make Result's Base point to said function call,
5521 /// and mark Result's Base as invalid.
5522 static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5523                                       LValue &Result) {
5524   if (Base.isNull())
5525     return false;
5526 
5527   // Because we do no form of static analysis, we only support const variables.
5528   //
5529   // Additionally, we can't support parameters, nor can we support static
5530   // variables (in the latter case, use-before-assign isn't UB; in the former,
5531   // we have no clue what they'll be assigned to).
5532   const auto *VD =
5533       dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5534   if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5535     return false;
5536 
5537   const Expr *Init = VD->getAnyInitializer();
5538   if (!Init)
5539     return false;
5540 
5541   const Expr *E = Init->IgnoreParens();
5542   if (!tryUnwrapAllocSizeCall(E))
5543     return false;
5544 
5545   // Store E instead of E unwrapped so that the type of the LValue's base is
5546   // what the user wanted.
5547   Result.setInvalid(E);
5548 
5549   QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
5550   Result.addUnsizedArray(Info, E, Pointee);
5551   return true;
5552 }
5553 
5554 namespace {
5555 class PointerExprEvaluator
5556   : public ExprEvaluatorBase<PointerExprEvaluator> {
5557   LValue &Result;
5558   bool InvalidBaseOK;
5559 
5560   bool Success(const Expr *E) {
5561     Result.set(E);
5562     return true;
5563   }
5564 
5565   bool evaluateLValue(const Expr *E, LValue &Result) {
5566     return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5567   }
5568 
5569   bool evaluatePointer(const Expr *E, LValue &Result) {
5570     return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5571   }
5572 
5573   bool visitNonBuiltinCallExpr(const CallExpr *E);
5574 public:
5575 
5576   PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5577       : ExprEvaluatorBaseTy(info), Result(Result),
5578         InvalidBaseOK(InvalidBaseOK) {}
5579 
5580   bool Success(const APValue &V, const Expr *E) {
5581     Result.setFrom(Info.Ctx, V);
5582     return true;
5583   }
5584   bool ZeroInitialization(const Expr *E) {
5585     auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5586     Result.setNull(E->getType(), TargetVal);
5587     return true;
5588   }
5589 
5590   bool VisitBinaryOperator(const BinaryOperator *E);
5591   bool VisitCastExpr(const CastExpr* E);
5592   bool VisitUnaryAddrOf(const UnaryOperator *E);
5593   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
5594       { return Success(E); }
5595   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5596     if (Info.noteFailure())
5597       EvaluateIgnoredValue(Info, E->getSubExpr());
5598     return Error(E);
5599   }
5600   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
5601       { return Success(E); }
5602   bool VisitCallExpr(const CallExpr *E);
5603   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
5604   bool VisitBlockExpr(const BlockExpr *E) {
5605     if (!E->getBlockDecl()->hasCaptures())
5606       return Success(E);
5607     return Error(E);
5608   }
5609   bool VisitCXXThisExpr(const CXXThisExpr *E) {
5610     // Can't look at 'this' when checking a potential constant expression.
5611     if (Info.checkingPotentialConstantExpression())
5612       return false;
5613     if (!Info.CurrentCall->This) {
5614       if (Info.getLangOpts().CPlusPlus11)
5615         Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
5616       else
5617         Info.FFDiag(E);
5618       return false;
5619     }
5620     Result = *Info.CurrentCall->This;
5621     // If we are inside a lambda's call operator, the 'this' expression refers
5622     // to the enclosing '*this' object (either by value or reference) which is
5623     // either copied into the closure object's field that represents the '*this'
5624     // or refers to '*this'.
5625     if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5626       // Update 'Result' to refer to the data member/field of the closure object
5627       // that represents the '*this' capture.
5628       if (!HandleLValueMember(Info, E, Result,
5629                              Info.CurrentCall->LambdaThisCaptureField))
5630         return false;
5631       // If we captured '*this' by reference, replace the field with its referent.
5632       if (Info.CurrentCall->LambdaThisCaptureField->getType()
5633               ->isPointerType()) {
5634         APValue RVal;
5635         if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5636                                             RVal))
5637           return false;
5638 
5639         Result.setFrom(Info.Ctx, RVal);
5640       }
5641     }
5642     return true;
5643   }
5644 
5645   // FIXME: Missing: @protocol, @selector
5646 };
5647 } // end anonymous namespace
5648 
5649 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5650                             bool InvalidBaseOK) {
5651   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
5652   return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
5653 }
5654 
5655 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5656   if (E->getOpcode() != BO_Add &&
5657       E->getOpcode() != BO_Sub)
5658     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5659 
5660   const Expr *PExp = E->getLHS();
5661   const Expr *IExp = E->getRHS();
5662   if (IExp->getType()->isPointerType())
5663     std::swap(PExp, IExp);
5664 
5665   bool EvalPtrOK = evaluatePointer(PExp, Result);
5666   if (!EvalPtrOK && !Info.noteFailure())
5667     return false;
5668 
5669   llvm::APSInt Offset;
5670   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
5671     return false;
5672 
5673   if (E->getOpcode() == BO_Sub)
5674     negateAsSigned(Offset);
5675 
5676   QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
5677   return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
5678 }
5679 
5680 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5681   return evaluateLValue(E->getSubExpr(), Result);
5682 }
5683 
5684 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5685   const Expr* SubExpr = E->getSubExpr();
5686 
5687   switch (E->getCastKind()) {
5688   default:
5689     break;
5690 
5691   case CK_BitCast:
5692   case CK_CPointerToObjCPointerCast:
5693   case CK_BlockPointerToObjCPointerCast:
5694   case CK_AnyPointerToBlockPointerCast:
5695   case CK_AddressSpaceConversion:
5696     if (!Visit(SubExpr))
5697       return false;
5698     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5699     // permitted in constant expressions in C++11. Bitcasts from cv void* are
5700     // also static_casts, but we disallow them as a resolution to DR1312.
5701     if (!E->getType()->isVoidPointerType()) {
5702       Result.Designator.setInvalid();
5703       if (SubExpr->getType()->isVoidPointerType())
5704         CCEDiag(E, diag::note_constexpr_invalid_cast)
5705           << 3 << SubExpr->getType();
5706       else
5707         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5708     }
5709     if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5710       ZeroInitialization(E);
5711     return true;
5712 
5713   case CK_DerivedToBase:
5714   case CK_UncheckedDerivedToBase:
5715     if (!evaluatePointer(E->getSubExpr(), Result))
5716       return false;
5717     if (!Result.Base && Result.Offset.isZero())
5718       return true;
5719 
5720     // Now figure out the necessary offset to add to the base LV to get from
5721     // the derived class to the base class.
5722     return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5723                                   castAs<PointerType>()->getPointeeType(),
5724                                 Result);
5725 
5726   case CK_BaseToDerived:
5727     if (!Visit(E->getSubExpr()))
5728       return false;
5729     if (!Result.Base && Result.Offset.isZero())
5730       return true;
5731     return HandleBaseToDerivedCast(Info, E, Result);
5732 
5733   case CK_NullToPointer:
5734     VisitIgnoredValue(E->getSubExpr());
5735     return ZeroInitialization(E);
5736 
5737   case CK_IntegralToPointer: {
5738     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5739 
5740     APValue Value;
5741     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
5742       break;
5743 
5744     if (Value.isInt()) {
5745       unsigned Size = Info.Ctx.getTypeSize(E->getType());
5746       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
5747       Result.Base = (Expr*)nullptr;
5748       Result.InvalidBase = false;
5749       Result.Offset = CharUnits::fromQuantity(N);
5750       Result.CallIndex = 0;
5751       Result.Designator.setInvalid();
5752       Result.IsNullPtr = false;
5753       return true;
5754     } else {
5755       // Cast is of an lvalue, no need to change value.
5756       Result.setFrom(Info.Ctx, Value);
5757       return true;
5758     }
5759   }
5760 
5761   case CK_ArrayToPointerDecay: {
5762     if (SubExpr->isGLValue()) {
5763       if (!evaluateLValue(SubExpr, Result))
5764         return false;
5765     } else {
5766       Result.set(SubExpr, Info.CurrentCall->Index);
5767       if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
5768                            Info, Result, SubExpr))
5769         return false;
5770     }
5771     // The result is a pointer to the first element of the array.
5772     auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5773     if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
5774       Result.addArray(Info, E, CAT);
5775     else
5776       Result.addUnsizedArray(Info, E, AT->getElementType());
5777     return true;
5778   }
5779 
5780   case CK_FunctionToPointerDecay:
5781     return evaluateLValue(SubExpr, Result);
5782 
5783   case CK_LValueToRValue: {
5784     LValue LVal;
5785     if (!evaluateLValue(E->getSubExpr(), LVal))
5786       return false;
5787 
5788     APValue RVal;
5789     // Note, we use the subexpression's type in order to retain cv-qualifiers.
5790     if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5791                                         LVal, RVal))
5792       return InvalidBaseOK &&
5793              evaluateLValueAsAllocSize(Info, LVal.Base, Result);
5794     return Success(RVal, E);
5795   }
5796   }
5797 
5798   return ExprEvaluatorBaseTy::VisitCastExpr(E);
5799 }
5800 
5801 static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5802   // C++ [expr.alignof]p3:
5803   //     When alignof is applied to a reference type, the result is the
5804   //     alignment of the referenced type.
5805   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5806     T = Ref->getPointeeType();
5807 
5808   // __alignof is defined to return the preferred alignment.
5809   if (T.getQualifiers().hasUnaligned())
5810     return CharUnits::One();
5811   return Info.Ctx.toCharUnitsFromBits(
5812     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5813 }
5814 
5815 static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5816   E = E->IgnoreParens();
5817 
5818   // The kinds of expressions that we have special-case logic here for
5819   // should be kept up to date with the special checks for those
5820   // expressions in Sema.
5821 
5822   // alignof decl is always accepted, even if it doesn't make sense: we default
5823   // to 1 in those cases.
5824   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5825     return Info.Ctx.getDeclAlign(DRE->getDecl(),
5826                                  /*RefAsPointee*/true);
5827 
5828   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5829     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5830                                  /*RefAsPointee*/true);
5831 
5832   return GetAlignOfType(Info, E->getType());
5833 }
5834 
5835 // To be clear: this happily visits unsupported builtins. Better name welcomed.
5836 bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5837   if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5838     return true;
5839 
5840   if (!(InvalidBaseOK && getAllocSizeAttr(E)))
5841     return false;
5842 
5843   Result.setInvalid(E);
5844   QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
5845   Result.addUnsizedArray(Info, E, PointeeTy);
5846   return true;
5847 }
5848 
5849 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
5850   if (IsStringLiteralCall(E))
5851     return Success(E);
5852 
5853   if (unsigned BuiltinOp = E->getBuiltinCallee())
5854     return VisitBuiltinCallExpr(E, BuiltinOp);
5855 
5856   return visitNonBuiltinCallExpr(E);
5857 }
5858 
5859 bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5860                                                 unsigned BuiltinOp) {
5861   switch (BuiltinOp) {
5862   case Builtin::BI__builtin_addressof:
5863     return evaluateLValue(E->getArg(0), Result);
5864   case Builtin::BI__builtin_assume_aligned: {
5865     // We need to be very careful here because: if the pointer does not have the
5866     // asserted alignment, then the behavior is undefined, and undefined
5867     // behavior is non-constant.
5868     if (!evaluatePointer(E->getArg(0), Result))
5869       return false;
5870 
5871     LValue OffsetResult(Result);
5872     APSInt Alignment;
5873     if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5874       return false;
5875     CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
5876 
5877     if (E->getNumArgs() > 2) {
5878       APSInt Offset;
5879       if (!EvaluateInteger(E->getArg(2), Offset, Info))
5880         return false;
5881 
5882       int64_t AdditionalOffset = -Offset.getZExtValue();
5883       OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5884     }
5885 
5886     // If there is a base object, then it must have the correct alignment.
5887     if (OffsetResult.Base) {
5888       CharUnits BaseAlignment;
5889       if (const ValueDecl *VD =
5890           OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5891         BaseAlignment = Info.Ctx.getDeclAlign(VD);
5892       } else {
5893         BaseAlignment =
5894           GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5895       }
5896 
5897       if (BaseAlignment < Align) {
5898         Result.Designator.setInvalid();
5899         // FIXME: Add support to Diagnostic for long / long long.
5900         CCEDiag(E->getArg(0),
5901                 diag::note_constexpr_baa_insufficient_alignment) << 0
5902           << (unsigned)BaseAlignment.getQuantity()
5903           << (unsigned)Align.getQuantity();
5904         return false;
5905       }
5906     }
5907 
5908     // The offset must also have the correct alignment.
5909     if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
5910       Result.Designator.setInvalid();
5911 
5912       (OffsetResult.Base
5913            ? CCEDiag(E->getArg(0),
5914                      diag::note_constexpr_baa_insufficient_alignment) << 1
5915            : CCEDiag(E->getArg(0),
5916                      diag::note_constexpr_baa_value_insufficient_alignment))
5917         << (int)OffsetResult.Offset.getQuantity()
5918         << (unsigned)Align.getQuantity();
5919       return false;
5920     }
5921 
5922     return true;
5923   }
5924 
5925   case Builtin::BIstrchr:
5926   case Builtin::BIwcschr:
5927   case Builtin::BImemchr:
5928   case Builtin::BIwmemchr:
5929     if (Info.getLangOpts().CPlusPlus11)
5930       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5931         << /*isConstexpr*/0 << /*isConstructor*/0
5932         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
5933     else
5934       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5935     LLVM_FALLTHROUGH;
5936   case Builtin::BI__builtin_strchr:
5937   case Builtin::BI__builtin_wcschr:
5938   case Builtin::BI__builtin_memchr:
5939   case Builtin::BI__builtin_char_memchr:
5940   case Builtin::BI__builtin_wmemchr: {
5941     if (!Visit(E->getArg(0)))
5942       return false;
5943     APSInt Desired;
5944     if (!EvaluateInteger(E->getArg(1), Desired, Info))
5945       return false;
5946     uint64_t MaxLength = uint64_t(-1);
5947     if (BuiltinOp != Builtin::BIstrchr &&
5948         BuiltinOp != Builtin::BIwcschr &&
5949         BuiltinOp != Builtin::BI__builtin_strchr &&
5950         BuiltinOp != Builtin::BI__builtin_wcschr) {
5951       APSInt N;
5952       if (!EvaluateInteger(E->getArg(2), N, Info))
5953         return false;
5954       MaxLength = N.getExtValue();
5955     }
5956 
5957     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
5958 
5959     // Figure out what value we're actually looking for (after converting to
5960     // the corresponding unsigned type if necessary).
5961     uint64_t DesiredVal;
5962     bool StopAtNull = false;
5963     switch (BuiltinOp) {
5964     case Builtin::BIstrchr:
5965     case Builtin::BI__builtin_strchr:
5966       // strchr compares directly to the passed integer, and therefore
5967       // always fails if given an int that is not a char.
5968       if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5969                                                   E->getArg(1)->getType(),
5970                                                   Desired),
5971                                Desired))
5972         return ZeroInitialization(E);
5973       StopAtNull = true;
5974       LLVM_FALLTHROUGH;
5975     case Builtin::BImemchr:
5976     case Builtin::BI__builtin_memchr:
5977     case Builtin::BI__builtin_char_memchr:
5978       // memchr compares by converting both sides to unsigned char. That's also
5979       // correct for strchr if we get this far (to cope with plain char being
5980       // unsigned in the strchr case).
5981       DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5982       break;
5983 
5984     case Builtin::BIwcschr:
5985     case Builtin::BI__builtin_wcschr:
5986       StopAtNull = true;
5987       LLVM_FALLTHROUGH;
5988     case Builtin::BIwmemchr:
5989     case Builtin::BI__builtin_wmemchr:
5990       // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5991       DesiredVal = Desired.getZExtValue();
5992       break;
5993     }
5994 
5995     for (; MaxLength; --MaxLength) {
5996       APValue Char;
5997       if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5998           !Char.isInt())
5999         return false;
6000       if (Char.getInt().getZExtValue() == DesiredVal)
6001         return true;
6002       if (StopAtNull && !Char.getInt())
6003         break;
6004       if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
6005         return false;
6006     }
6007     // Not found: return nullptr.
6008     return ZeroInitialization(E);
6009   }
6010 
6011   default:
6012     return visitNonBuiltinCallExpr(E);
6013   }
6014 }
6015 
6016 //===----------------------------------------------------------------------===//
6017 // Member Pointer Evaluation
6018 //===----------------------------------------------------------------------===//
6019 
6020 namespace {
6021 class MemberPointerExprEvaluator
6022   : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
6023   MemberPtr &Result;
6024 
6025   bool Success(const ValueDecl *D) {
6026     Result = MemberPtr(D);
6027     return true;
6028   }
6029 public:
6030 
6031   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6032     : ExprEvaluatorBaseTy(Info), Result(Result) {}
6033 
6034   bool Success(const APValue &V, const Expr *E) {
6035     Result.setFrom(V);
6036     return true;
6037   }
6038   bool ZeroInitialization(const Expr *E) {
6039     return Success((const ValueDecl*)nullptr);
6040   }
6041 
6042   bool VisitCastExpr(const CastExpr *E);
6043   bool VisitUnaryAddrOf(const UnaryOperator *E);
6044 };
6045 } // end anonymous namespace
6046 
6047 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6048                                   EvalInfo &Info) {
6049   assert(E->isRValue() && E->getType()->isMemberPointerType());
6050   return MemberPointerExprEvaluator(Info, Result).Visit(E);
6051 }
6052 
6053 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6054   switch (E->getCastKind()) {
6055   default:
6056     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6057 
6058   case CK_NullToMemberPointer:
6059     VisitIgnoredValue(E->getSubExpr());
6060     return ZeroInitialization(E);
6061 
6062   case CK_BaseToDerivedMemberPointer: {
6063     if (!Visit(E->getSubExpr()))
6064       return false;
6065     if (E->path_empty())
6066       return true;
6067     // Base-to-derived member pointer casts store the path in derived-to-base
6068     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6069     // the wrong end of the derived->base arc, so stagger the path by one class.
6070     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6071     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6072          PathI != PathE; ++PathI) {
6073       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6074       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6075       if (!Result.castToDerived(Derived))
6076         return Error(E);
6077     }
6078     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6079     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
6080       return Error(E);
6081     return true;
6082   }
6083 
6084   case CK_DerivedToBaseMemberPointer:
6085     if (!Visit(E->getSubExpr()))
6086       return false;
6087     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6088          PathE = E->path_end(); PathI != PathE; ++PathI) {
6089       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6090       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6091       if (!Result.castToBase(Base))
6092         return Error(E);
6093     }
6094     return true;
6095   }
6096 }
6097 
6098 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6099   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6100   // member can be formed.
6101   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6102 }
6103 
6104 //===----------------------------------------------------------------------===//
6105 // Record Evaluation
6106 //===----------------------------------------------------------------------===//
6107 
6108 namespace {
6109   class RecordExprEvaluator
6110   : public ExprEvaluatorBase<RecordExprEvaluator> {
6111     const LValue &This;
6112     APValue &Result;
6113   public:
6114 
6115     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6116       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6117 
6118     bool Success(const APValue &V, const Expr *E) {
6119       Result = V;
6120       return true;
6121     }
6122     bool ZeroInitialization(const Expr *E) {
6123       return ZeroInitialization(E, E->getType());
6124     }
6125     bool ZeroInitialization(const Expr *E, QualType T);
6126 
6127     bool VisitCallExpr(const CallExpr *E) {
6128       return handleCallExpr(E, Result, &This);
6129     }
6130     bool VisitCastExpr(const CastExpr *E);
6131     bool VisitInitListExpr(const InitListExpr *E);
6132     bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6133       return VisitCXXConstructExpr(E, E->getType());
6134     }
6135     bool VisitLambdaExpr(const LambdaExpr *E);
6136     bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
6137     bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
6138     bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
6139   };
6140 }
6141 
6142 /// Perform zero-initialization on an object of non-union class type.
6143 /// C++11 [dcl.init]p5:
6144 ///  To zero-initialize an object or reference of type T means:
6145 ///    [...]
6146 ///    -- if T is a (possibly cv-qualified) non-union class type,
6147 ///       each non-static data member and each base-class subobject is
6148 ///       zero-initialized
6149 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6150                                           const RecordDecl *RD,
6151                                           const LValue &This, APValue &Result) {
6152   assert(!RD->isUnion() && "Expected non-union class type");
6153   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6154   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
6155                    std::distance(RD->field_begin(), RD->field_end()));
6156 
6157   if (RD->isInvalidDecl()) return false;
6158   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6159 
6160   if (CD) {
6161     unsigned Index = 0;
6162     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
6163            End = CD->bases_end(); I != End; ++I, ++Index) {
6164       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6165       LValue Subobject = This;
6166       if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6167         return false;
6168       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
6169                                          Result.getStructBase(Index)))
6170         return false;
6171     }
6172   }
6173 
6174   for (const auto *I : RD->fields()) {
6175     // -- if T is a reference type, no initialization is performed.
6176     if (I->getType()->isReferenceType())
6177       continue;
6178 
6179     LValue Subobject = This;
6180     if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
6181       return false;
6182 
6183     ImplicitValueInitExpr VIE(I->getType());
6184     if (!EvaluateInPlace(
6185           Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
6186       return false;
6187   }
6188 
6189   return true;
6190 }
6191 
6192 bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6193   const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
6194   if (RD->isInvalidDecl()) return false;
6195   if (RD->isUnion()) {
6196     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6197     // object's first non-static named data member is zero-initialized
6198     RecordDecl::field_iterator I = RD->field_begin();
6199     if (I == RD->field_end()) {
6200       Result = APValue((const FieldDecl*)nullptr);
6201       return true;
6202     }
6203 
6204     LValue Subobject = This;
6205     if (!HandleLValueMember(Info, E, Subobject, *I))
6206       return false;
6207     Result = APValue(*I);
6208     ImplicitValueInitExpr VIE(I->getType());
6209     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
6210   }
6211 
6212   if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
6213     Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
6214     return false;
6215   }
6216 
6217   return HandleClassZeroInitialization(Info, E, RD, This, Result);
6218 }
6219 
6220 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6221   switch (E->getCastKind()) {
6222   default:
6223     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6224 
6225   case CK_ConstructorConversion:
6226     return Visit(E->getSubExpr());
6227 
6228   case CK_DerivedToBase:
6229   case CK_UncheckedDerivedToBase: {
6230     APValue DerivedObject;
6231     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
6232       return false;
6233     if (!DerivedObject.isStruct())
6234       return Error(E->getSubExpr());
6235 
6236     // Derived-to-base rvalue conversion: just slice off the derived part.
6237     APValue *Value = &DerivedObject;
6238     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6239     for (CastExpr::path_const_iterator PathI = E->path_begin(),
6240          PathE = E->path_end(); PathI != PathE; ++PathI) {
6241       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6242       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6243       Value = &Value->getStructBase(getBaseIndex(RD, Base));
6244       RD = Base;
6245     }
6246     Result = *Value;
6247     return true;
6248   }
6249   }
6250 }
6251 
6252 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6253   if (E->isTransparent())
6254     return Visit(E->getInit(0));
6255 
6256   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
6257   if (RD->isInvalidDecl()) return false;
6258   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6259 
6260   if (RD->isUnion()) {
6261     const FieldDecl *Field = E->getInitializedFieldInUnion();
6262     Result = APValue(Field);
6263     if (!Field)
6264       return true;
6265 
6266     // If the initializer list for a union does not contain any elements, the
6267     // first element of the union is value-initialized.
6268     // FIXME: The element should be initialized from an initializer list.
6269     //        Is this difference ever observable for initializer lists which
6270     //        we don't build?
6271     ImplicitValueInitExpr VIE(Field->getType());
6272     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6273 
6274     LValue Subobject = This;
6275     if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6276       return false;
6277 
6278     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6279     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6280                                   isa<CXXDefaultInitExpr>(InitExpr));
6281 
6282     return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
6283   }
6284 
6285   auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
6286   if (Result.isUninit())
6287     Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6288                      std::distance(RD->field_begin(), RD->field_end()));
6289   unsigned ElementNo = 0;
6290   bool Success = true;
6291 
6292   // Initialize base classes.
6293   if (CXXRD) {
6294     for (const auto &Base : CXXRD->bases()) {
6295       assert(ElementNo < E->getNumInits() && "missing init for base class");
6296       const Expr *Init = E->getInit(ElementNo);
6297 
6298       LValue Subobject = This;
6299       if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6300         return false;
6301 
6302       APValue &FieldVal = Result.getStructBase(ElementNo);
6303       if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
6304         if (!Info.noteFailure())
6305           return false;
6306         Success = false;
6307       }
6308       ++ElementNo;
6309     }
6310   }
6311 
6312   // Initialize members.
6313   for (const auto *Field : RD->fields()) {
6314     // Anonymous bit-fields are not considered members of the class for
6315     // purposes of aggregate initialization.
6316     if (Field->isUnnamedBitfield())
6317       continue;
6318 
6319     LValue Subobject = This;
6320 
6321     bool HaveInit = ElementNo < E->getNumInits();
6322 
6323     // FIXME: Diagnostics here should point to the end of the initializer
6324     // list, not the start.
6325     if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
6326                             Subobject, Field, &Layout))
6327       return false;
6328 
6329     // Perform an implicit value-initialization for members beyond the end of
6330     // the initializer list.
6331     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
6332     const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
6333 
6334     // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6335     ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6336                                   isa<CXXDefaultInitExpr>(Init));
6337 
6338     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6339     if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6340         (Field->isBitField() && !truncateBitfieldValue(Info, Init,
6341                                                        FieldVal, Field))) {
6342       if (!Info.noteFailure())
6343         return false;
6344       Success = false;
6345     }
6346   }
6347 
6348   return Success;
6349 }
6350 
6351 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6352                                                 QualType T) {
6353   // Note that E's type is not necessarily the type of our class here; we might
6354   // be initializing an array element instead.
6355   const CXXConstructorDecl *FD = E->getConstructor();
6356   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6357 
6358   bool ZeroInit = E->requiresZeroInitialization();
6359   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
6360     // If we've already performed zero-initialization, we're already done.
6361     if (!Result.isUninit())
6362       return true;
6363 
6364     // We can get here in two different ways:
6365     //  1) We're performing value-initialization, and should zero-initialize
6366     //     the object, or
6367     //  2) We're performing default-initialization of an object with a trivial
6368     //     constexpr default constructor, in which case we should start the
6369     //     lifetimes of all the base subobjects (there can be no data member
6370     //     subobjects in this case) per [basic.life]p1.
6371     // Either way, ZeroInitialization is appropriate.
6372     return ZeroInitialization(E, T);
6373   }
6374 
6375   const FunctionDecl *Definition = nullptr;
6376   auto Body = FD->getBody(Definition);
6377 
6378   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6379     return false;
6380 
6381   // Avoid materializing a temporary for an elidable copy/move constructor.
6382   if (E->isElidable() && !ZeroInit)
6383     if (const MaterializeTemporaryExpr *ME
6384           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6385       return Visit(ME->GetTemporaryExpr());
6386 
6387   if (ZeroInit && !ZeroInitialization(E, T))
6388     return false;
6389 
6390   auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
6391   return HandleConstructorCall(E, This, Args,
6392                                cast<CXXConstructorDecl>(Definition), Info,
6393                                Result);
6394 }
6395 
6396 bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6397     const CXXInheritedCtorInitExpr *E) {
6398   if (!Info.CurrentCall) {
6399     assert(Info.checkingPotentialConstantExpression());
6400     return false;
6401   }
6402 
6403   const CXXConstructorDecl *FD = E->getConstructor();
6404   if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6405     return false;
6406 
6407   const FunctionDecl *Definition = nullptr;
6408   auto Body = FD->getBody(Definition);
6409 
6410   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6411     return false;
6412 
6413   return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
6414                                cast<CXXConstructorDecl>(Definition), Info,
6415                                Result);
6416 }
6417 
6418 bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6419     const CXXStdInitializerListExpr *E) {
6420   const ConstantArrayType *ArrayType =
6421       Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6422 
6423   LValue Array;
6424   if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6425     return false;
6426 
6427   // Get a pointer to the first element of the array.
6428   Array.addArray(Info, E, ArrayType);
6429 
6430   // FIXME: Perform the checks on the field types in SemaInit.
6431   RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6432   RecordDecl::field_iterator Field = Record->field_begin();
6433   if (Field == Record->field_end())
6434     return Error(E);
6435 
6436   // Start pointer.
6437   if (!Field->getType()->isPointerType() ||
6438       !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6439                             ArrayType->getElementType()))
6440     return Error(E);
6441 
6442   // FIXME: What if the initializer_list type has base classes, etc?
6443   Result = APValue(APValue::UninitStruct(), 0, 2);
6444   Array.moveInto(Result.getStructField(0));
6445 
6446   if (++Field == Record->field_end())
6447     return Error(E);
6448 
6449   if (Field->getType()->isPointerType() &&
6450       Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6451                            ArrayType->getElementType())) {
6452     // End pointer.
6453     if (!HandleLValueArrayAdjustment(Info, E, Array,
6454                                      ArrayType->getElementType(),
6455                                      ArrayType->getSize().getZExtValue()))
6456       return false;
6457     Array.moveInto(Result.getStructField(1));
6458   } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6459     // Length.
6460     Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6461   else
6462     return Error(E);
6463 
6464   if (++Field != Record->field_end())
6465     return Error(E);
6466 
6467   return true;
6468 }
6469 
6470 bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6471   const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6472   if (ClosureClass->isInvalidDecl()) return false;
6473 
6474   if (Info.checkingPotentialConstantExpression()) return true;
6475 
6476   const size_t NumFields =
6477       std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
6478 
6479   assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6480                                             E->capture_init_end()) &&
6481          "The number of lambda capture initializers should equal the number of "
6482          "fields within the closure type");
6483 
6484   Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6485   // Iterate through all the lambda's closure object's fields and initialize
6486   // them.
6487   auto *CaptureInitIt = E->capture_init_begin();
6488   const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6489   bool Success = true;
6490   for (const auto *Field : ClosureClass->fields()) {
6491     assert(CaptureInitIt != E->capture_init_end());
6492     // Get the initializer for this field
6493     Expr *const CurFieldInit = *CaptureInitIt++;
6494 
6495     // If there is no initializer, either this is a VLA or an error has
6496     // occurred.
6497     if (!CurFieldInit)
6498       return Error(E);
6499 
6500     APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6501     if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6502       if (!Info.keepEvaluatingAfterFailure())
6503         return false;
6504       Success = false;
6505     }
6506     ++CaptureIt;
6507   }
6508   return Success;
6509 }
6510 
6511 static bool EvaluateRecord(const Expr *E, const LValue &This,
6512                            APValue &Result, EvalInfo &Info) {
6513   assert(E->isRValue() && E->getType()->isRecordType() &&
6514          "can't evaluate expression as a record rvalue");
6515   return RecordExprEvaluator(Info, This, Result).Visit(E);
6516 }
6517 
6518 //===----------------------------------------------------------------------===//
6519 // Temporary Evaluation
6520 //
6521 // Temporaries are represented in the AST as rvalues, but generally behave like
6522 // lvalues. The full-object of which the temporary is a subobject is implicitly
6523 // materialized so that a reference can bind to it.
6524 //===----------------------------------------------------------------------===//
6525 namespace {
6526 class TemporaryExprEvaluator
6527   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6528 public:
6529   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
6530     LValueExprEvaluatorBaseTy(Info, Result, false) {}
6531 
6532   /// Visit an expression which constructs the value of this temporary.
6533   bool VisitConstructExpr(const Expr *E) {
6534     Result.set(E, Info.CurrentCall->Index);
6535     return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6536                            Info, Result, E);
6537   }
6538 
6539   bool VisitCastExpr(const CastExpr *E) {
6540     switch (E->getCastKind()) {
6541     default:
6542       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6543 
6544     case CK_ConstructorConversion:
6545       return VisitConstructExpr(E->getSubExpr());
6546     }
6547   }
6548   bool VisitInitListExpr(const InitListExpr *E) {
6549     return VisitConstructExpr(E);
6550   }
6551   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6552     return VisitConstructExpr(E);
6553   }
6554   bool VisitCallExpr(const CallExpr *E) {
6555     return VisitConstructExpr(E);
6556   }
6557   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6558     return VisitConstructExpr(E);
6559   }
6560   bool VisitLambdaExpr(const LambdaExpr *E) {
6561     return VisitConstructExpr(E);
6562   }
6563 };
6564 } // end anonymous namespace
6565 
6566 /// Evaluate an expression of record type as a temporary.
6567 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
6568   assert(E->isRValue() && E->getType()->isRecordType());
6569   return TemporaryExprEvaluator(Info, Result).Visit(E);
6570 }
6571 
6572 //===----------------------------------------------------------------------===//
6573 // Vector Evaluation
6574 //===----------------------------------------------------------------------===//
6575 
6576 namespace {
6577   class VectorExprEvaluator
6578   : public ExprEvaluatorBase<VectorExprEvaluator> {
6579     APValue &Result;
6580   public:
6581 
6582     VectorExprEvaluator(EvalInfo &info, APValue &Result)
6583       : ExprEvaluatorBaseTy(info), Result(Result) {}
6584 
6585     bool Success(ArrayRef<APValue> V, const Expr *E) {
6586       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6587       // FIXME: remove this APValue copy.
6588       Result = APValue(V.data(), V.size());
6589       return true;
6590     }
6591     bool Success(const APValue &V, const Expr *E) {
6592       assert(V.isVector());
6593       Result = V;
6594       return true;
6595     }
6596     bool ZeroInitialization(const Expr *E);
6597 
6598     bool VisitUnaryReal(const UnaryOperator *E)
6599       { return Visit(E->getSubExpr()); }
6600     bool VisitCastExpr(const CastExpr* E);
6601     bool VisitInitListExpr(const InitListExpr *E);
6602     bool VisitUnaryImag(const UnaryOperator *E);
6603     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
6604     //                 binary comparisons, binary and/or/xor,
6605     //                 shufflevector, ExtVectorElementExpr
6606   };
6607 } // end anonymous namespace
6608 
6609 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
6610   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
6611   return VectorExprEvaluator(Info, Result).Visit(E);
6612 }
6613 
6614 bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
6615   const VectorType *VTy = E->getType()->castAs<VectorType>();
6616   unsigned NElts = VTy->getNumElements();
6617 
6618   const Expr *SE = E->getSubExpr();
6619   QualType SETy = SE->getType();
6620 
6621   switch (E->getCastKind()) {
6622   case CK_VectorSplat: {
6623     APValue Val = APValue();
6624     if (SETy->isIntegerType()) {
6625       APSInt IntResult;
6626       if (!EvaluateInteger(SE, IntResult, Info))
6627         return false;
6628       Val = APValue(std::move(IntResult));
6629     } else if (SETy->isRealFloatingType()) {
6630       APFloat FloatResult(0.0);
6631       if (!EvaluateFloat(SE, FloatResult, Info))
6632         return false;
6633       Val = APValue(std::move(FloatResult));
6634     } else {
6635       return Error(E);
6636     }
6637 
6638     // Splat and create vector APValue.
6639     SmallVector<APValue, 4> Elts(NElts, Val);
6640     return Success(Elts, E);
6641   }
6642   case CK_BitCast: {
6643     // Evaluate the operand into an APInt we can extract from.
6644     llvm::APInt SValInt;
6645     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6646       return false;
6647     // Extract the elements
6648     QualType EltTy = VTy->getElementType();
6649     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6650     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6651     SmallVector<APValue, 4> Elts;
6652     if (EltTy->isRealFloatingType()) {
6653       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
6654       unsigned FloatEltSize = EltSize;
6655       if (&Sem == &APFloat::x87DoubleExtended())
6656         FloatEltSize = 80;
6657       for (unsigned i = 0; i < NElts; i++) {
6658         llvm::APInt Elt;
6659         if (BigEndian)
6660           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6661         else
6662           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
6663         Elts.push_back(APValue(APFloat(Sem, Elt)));
6664       }
6665     } else if (EltTy->isIntegerType()) {
6666       for (unsigned i = 0; i < NElts; i++) {
6667         llvm::APInt Elt;
6668         if (BigEndian)
6669           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6670         else
6671           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6672         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6673       }
6674     } else {
6675       return Error(E);
6676     }
6677     return Success(Elts, E);
6678   }
6679   default:
6680     return ExprEvaluatorBaseTy::VisitCastExpr(E);
6681   }
6682 }
6683 
6684 bool
6685 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6686   const VectorType *VT = E->getType()->castAs<VectorType>();
6687   unsigned NumInits = E->getNumInits();
6688   unsigned NumElements = VT->getNumElements();
6689 
6690   QualType EltTy = VT->getElementType();
6691   SmallVector<APValue, 4> Elements;
6692 
6693   // The number of initializers can be less than the number of
6694   // vector elements. For OpenCL, this can be due to nested vector
6695   // initialization. For GCC compatibility, missing trailing elements
6696   // should be initialized with zeroes.
6697   unsigned CountInits = 0, CountElts = 0;
6698   while (CountElts < NumElements) {
6699     // Handle nested vector initialization.
6700     if (CountInits < NumInits
6701         && E->getInit(CountInits)->getType()->isVectorType()) {
6702       APValue v;
6703       if (!EvaluateVector(E->getInit(CountInits), v, Info))
6704         return Error(E);
6705       unsigned vlen = v.getVectorLength();
6706       for (unsigned j = 0; j < vlen; j++)
6707         Elements.push_back(v.getVectorElt(j));
6708       CountElts += vlen;
6709     } else if (EltTy->isIntegerType()) {
6710       llvm::APSInt sInt(32);
6711       if (CountInits < NumInits) {
6712         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
6713           return false;
6714       } else // trailing integer zero.
6715         sInt = Info.Ctx.MakeIntValue(0, EltTy);
6716       Elements.push_back(APValue(sInt));
6717       CountElts++;
6718     } else {
6719       llvm::APFloat f(0.0);
6720       if (CountInits < NumInits) {
6721         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
6722           return false;
6723       } else // trailing float zero.
6724         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6725       Elements.push_back(APValue(f));
6726       CountElts++;
6727     }
6728     CountInits++;
6729   }
6730   return Success(Elements, E);
6731 }
6732 
6733 bool
6734 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
6735   const VectorType *VT = E->getType()->getAs<VectorType>();
6736   QualType EltTy = VT->getElementType();
6737   APValue ZeroElement;
6738   if (EltTy->isIntegerType())
6739     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6740   else
6741     ZeroElement =
6742         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6743 
6744   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
6745   return Success(Elements, E);
6746 }
6747 
6748 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
6749   VisitIgnoredValue(E->getSubExpr());
6750   return ZeroInitialization(E);
6751 }
6752 
6753 //===----------------------------------------------------------------------===//
6754 // Array Evaluation
6755 //===----------------------------------------------------------------------===//
6756 
6757 namespace {
6758   class ArrayExprEvaluator
6759   : public ExprEvaluatorBase<ArrayExprEvaluator> {
6760     const LValue &This;
6761     APValue &Result;
6762   public:
6763 
6764     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6765       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
6766 
6767     bool Success(const APValue &V, const Expr *E) {
6768       assert((V.isArray() || V.isLValue()) &&
6769              "expected array or string literal");
6770       Result = V;
6771       return true;
6772     }
6773 
6774     bool ZeroInitialization(const Expr *E) {
6775       const ConstantArrayType *CAT =
6776           Info.Ctx.getAsConstantArrayType(E->getType());
6777       if (!CAT)
6778         return Error(E);
6779 
6780       Result = APValue(APValue::UninitArray(), 0,
6781                        CAT->getSize().getZExtValue());
6782       if (!Result.hasArrayFiller()) return true;
6783 
6784       // Zero-initialize all elements.
6785       LValue Subobject = This;
6786       Subobject.addArray(Info, E, CAT);
6787       ImplicitValueInitExpr VIE(CAT->getElementType());
6788       return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
6789     }
6790 
6791     bool VisitCallExpr(const CallExpr *E) {
6792       return handleCallExpr(E, Result, &This);
6793     }
6794     bool VisitInitListExpr(const InitListExpr *E);
6795     bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
6796     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
6797     bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6798                                const LValue &Subobject,
6799                                APValue *Value, QualType Type);
6800   };
6801 } // end anonymous namespace
6802 
6803 static bool EvaluateArray(const Expr *E, const LValue &This,
6804                           APValue &Result, EvalInfo &Info) {
6805   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
6806   return ArrayExprEvaluator(Info, This, Result).Visit(E);
6807 }
6808 
6809 // Return true iff the given array filler may depend on the element index.
6810 static bool MaybeElementDependentArrayFiller(const Expr *FillerExpr) {
6811   // For now, just whitelist non-class value-initialization and initialization
6812   // lists comprised of them.
6813   if (isa<ImplicitValueInitExpr>(FillerExpr))
6814     return false;
6815   if (const InitListExpr *ILE = dyn_cast<InitListExpr>(FillerExpr)) {
6816     for (unsigned I = 0, E = ILE->getNumInits(); I != E; ++I) {
6817       if (MaybeElementDependentArrayFiller(ILE->getInit(I)))
6818         return true;
6819     }
6820     return false;
6821   }
6822   return true;
6823 }
6824 
6825 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6826   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6827   if (!CAT)
6828     return Error(E);
6829 
6830   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6831   // an appropriately-typed string literal enclosed in braces.
6832   if (E->isStringLiteralInit()) {
6833     LValue LV;
6834     if (!EvaluateLValue(E->getInit(0), LV, Info))
6835       return false;
6836     APValue Val;
6837     LV.moveInto(Val);
6838     return Success(Val, E);
6839   }
6840 
6841   bool Success = true;
6842 
6843   assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6844          "zero-initialized array shouldn't have any initialized elts");
6845   APValue Filler;
6846   if (Result.isArray() && Result.hasArrayFiller())
6847     Filler = Result.getArrayFiller();
6848 
6849   unsigned NumEltsToInit = E->getNumInits();
6850   unsigned NumElts = CAT->getSize().getZExtValue();
6851   const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
6852 
6853   // If the initializer might depend on the array index, run it for each
6854   // array element.
6855   if (NumEltsToInit != NumElts && MaybeElementDependentArrayFiller(FillerExpr))
6856     NumEltsToInit = NumElts;
6857 
6858   DEBUG(llvm::dbgs() << "The number of elements to initialize: " <<
6859         NumEltsToInit << ".\n");
6860 
6861   Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
6862 
6863   // If the array was previously zero-initialized, preserve the
6864   // zero-initialized values.
6865   if (!Filler.isUninit()) {
6866     for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6867       Result.getArrayInitializedElt(I) = Filler;
6868     if (Result.hasArrayFiller())
6869       Result.getArrayFiller() = Filler;
6870   }
6871 
6872   LValue Subobject = This;
6873   Subobject.addArray(Info, E, CAT);
6874   for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6875     const Expr *Init =
6876         Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
6877     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6878                          Info, Subobject, Init) ||
6879         !HandleLValueArrayAdjustment(Info, Init, Subobject,
6880                                      CAT->getElementType(), 1)) {
6881       if (!Info.noteFailure())
6882         return false;
6883       Success = false;
6884     }
6885   }
6886 
6887   if (!Result.hasArrayFiller())
6888     return Success;
6889 
6890   // If we get here, we have a trivial filler, which we can just evaluate
6891   // once and splat over the rest of the array elements.
6892   assert(FillerExpr && "no array filler for incomplete init list");
6893   return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6894                          FillerExpr) && Success;
6895 }
6896 
6897 bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6898   if (E->getCommonExpr() &&
6899       !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6900                 Info, E->getCommonExpr()->getSourceExpr()))
6901     return false;
6902 
6903   auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6904 
6905   uint64_t Elements = CAT->getSize().getZExtValue();
6906   Result = APValue(APValue::UninitArray(), Elements, Elements);
6907 
6908   LValue Subobject = This;
6909   Subobject.addArray(Info, E, CAT);
6910 
6911   bool Success = true;
6912   for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6913     if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6914                          Info, Subobject, E->getSubExpr()) ||
6915         !HandleLValueArrayAdjustment(Info, E, Subobject,
6916                                      CAT->getElementType(), 1)) {
6917       if (!Info.noteFailure())
6918         return false;
6919       Success = false;
6920     }
6921   }
6922 
6923   return Success;
6924 }
6925 
6926 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
6927   return VisitCXXConstructExpr(E, This, &Result, E->getType());
6928 }
6929 
6930 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6931                                                const LValue &Subobject,
6932                                                APValue *Value,
6933                                                QualType Type) {
6934   bool HadZeroInit = !Value->isUninit();
6935 
6936   if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6937     unsigned N = CAT->getSize().getZExtValue();
6938 
6939     // Preserve the array filler if we had prior zero-initialization.
6940     APValue Filler =
6941       HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6942                                              : APValue();
6943 
6944     *Value = APValue(APValue::UninitArray(), N, N);
6945 
6946     if (HadZeroInit)
6947       for (unsigned I = 0; I != N; ++I)
6948         Value->getArrayInitializedElt(I) = Filler;
6949 
6950     // Initialize the elements.
6951     LValue ArrayElt = Subobject;
6952     ArrayElt.addArray(Info, E, CAT);
6953     for (unsigned I = 0; I != N; ++I)
6954       if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6955                                  CAT->getElementType()) ||
6956           !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6957                                        CAT->getElementType(), 1))
6958         return false;
6959 
6960     return true;
6961   }
6962 
6963   if (!Type->isRecordType())
6964     return Error(E);
6965 
6966   return RecordExprEvaluator(Info, Subobject, *Value)
6967              .VisitCXXConstructExpr(E, Type);
6968 }
6969 
6970 //===----------------------------------------------------------------------===//
6971 // Integer Evaluation
6972 //
6973 // As a GNU extension, we support casting pointers to sufficiently-wide integer
6974 // types and back in constant folding. Integer values are thus represented
6975 // either as an integer-valued APValue, or as an lvalue-valued APValue.
6976 //===----------------------------------------------------------------------===//
6977 
6978 namespace {
6979 class IntExprEvaluator
6980   : public ExprEvaluatorBase<IntExprEvaluator> {
6981   APValue &Result;
6982 public:
6983   IntExprEvaluator(EvalInfo &info, APValue &result)
6984     : ExprEvaluatorBaseTy(info), Result(result) {}
6985 
6986   bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
6987     assert(E->getType()->isIntegralOrEnumerationType() &&
6988            "Invalid evaluation result.");
6989     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
6990            "Invalid evaluation result.");
6991     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
6992            "Invalid evaluation result.");
6993     Result = APValue(SI);
6994     return true;
6995   }
6996   bool Success(const llvm::APSInt &SI, const Expr *E) {
6997     return Success(SI, E, Result);
6998   }
6999 
7000   bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
7001     assert(E->getType()->isIntegralOrEnumerationType() &&
7002            "Invalid evaluation result.");
7003     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
7004            "Invalid evaluation result.");
7005     Result = APValue(APSInt(I));
7006     Result.getInt().setIsUnsigned(
7007                             E->getType()->isUnsignedIntegerOrEnumerationType());
7008     return true;
7009   }
7010   bool Success(const llvm::APInt &I, const Expr *E) {
7011     return Success(I, E, Result);
7012   }
7013 
7014   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7015     assert(E->getType()->isIntegralOrEnumerationType() &&
7016            "Invalid evaluation result.");
7017     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
7018     return true;
7019   }
7020   bool Success(uint64_t Value, const Expr *E) {
7021     return Success(Value, E, Result);
7022   }
7023 
7024   bool Success(CharUnits Size, const Expr *E) {
7025     return Success(Size.getQuantity(), E);
7026   }
7027 
7028   bool Success(const APValue &V, const Expr *E) {
7029     if (V.isLValue() || V.isAddrLabelDiff()) {
7030       Result = V;
7031       return true;
7032     }
7033     return Success(V.getInt(), E);
7034   }
7035 
7036   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
7037 
7038   //===--------------------------------------------------------------------===//
7039   //                            Visitor Methods
7040   //===--------------------------------------------------------------------===//
7041 
7042   bool VisitIntegerLiteral(const IntegerLiteral *E) {
7043     return Success(E->getValue(), E);
7044   }
7045   bool VisitCharacterLiteral(const CharacterLiteral *E) {
7046     return Success(E->getValue(), E);
7047   }
7048 
7049   bool CheckReferencedDecl(const Expr *E, const Decl *D);
7050   bool VisitDeclRefExpr(const DeclRefExpr *E) {
7051     if (CheckReferencedDecl(E, E->getDecl()))
7052       return true;
7053 
7054     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
7055   }
7056   bool VisitMemberExpr(const MemberExpr *E) {
7057     if (CheckReferencedDecl(E, E->getMemberDecl())) {
7058       VisitIgnoredBaseExpression(E->getBase());
7059       return true;
7060     }
7061 
7062     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
7063   }
7064 
7065   bool VisitCallExpr(const CallExpr *E);
7066   bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
7067   bool VisitBinaryOperator(const BinaryOperator *E);
7068   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
7069   bool VisitUnaryOperator(const UnaryOperator *E);
7070 
7071   bool VisitCastExpr(const CastExpr* E);
7072   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
7073 
7074   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
7075     return Success(E->getValue(), E);
7076   }
7077 
7078   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7079     return Success(E->getValue(), E);
7080   }
7081 
7082   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7083     if (Info.ArrayInitIndex == uint64_t(-1)) {
7084       // We were asked to evaluate this subexpression independent of the
7085       // enclosing ArrayInitLoopExpr. We can't do that.
7086       Info.FFDiag(E);
7087       return false;
7088     }
7089     return Success(Info.ArrayInitIndex, E);
7090   }
7091 
7092   // Note, GNU defines __null as an integer, not a pointer.
7093   bool VisitGNUNullExpr(const GNUNullExpr *E) {
7094     return ZeroInitialization(E);
7095   }
7096 
7097   bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7098     return Success(E->getValue(), E);
7099   }
7100 
7101   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7102     return Success(E->getValue(), E);
7103   }
7104 
7105   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7106     return Success(E->getValue(), E);
7107   }
7108 
7109   bool VisitUnaryReal(const UnaryOperator *E);
7110   bool VisitUnaryImag(const UnaryOperator *E);
7111 
7112   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
7113   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
7114 
7115   // FIXME: Missing: array subscript of vector, member of vector
7116 };
7117 } // end anonymous namespace
7118 
7119 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7120 /// produce either the integer value or a pointer.
7121 ///
7122 /// GCC has a heinous extension which folds casts between pointer types and
7123 /// pointer-sized integral types. We support this by allowing the evaluation of
7124 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7125 /// Some simple arithmetic on such values is supported (they are treated much
7126 /// like char*).
7127 static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
7128                                     EvalInfo &Info) {
7129   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
7130   return IntExprEvaluator(Info, Result).Visit(E);
7131 }
7132 
7133 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
7134   APValue Val;
7135   if (!EvaluateIntegerOrLValue(E, Val, Info))
7136     return false;
7137   if (!Val.isInt()) {
7138     // FIXME: It would be better to produce the diagnostic for casting
7139     //        a pointer to an integer.
7140     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
7141     return false;
7142   }
7143   Result = Val.getInt();
7144   return true;
7145 }
7146 
7147 /// Check whether the given declaration can be directly converted to an integral
7148 /// rvalue. If not, no diagnostic is produced; there are other things we can
7149 /// try.
7150 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
7151   // Enums are integer constant exprs.
7152   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
7153     // Check for signedness/width mismatches between E type and ECD value.
7154     bool SameSign = (ECD->getInitVal().isSigned()
7155                      == E->getType()->isSignedIntegerOrEnumerationType());
7156     bool SameWidth = (ECD->getInitVal().getBitWidth()
7157                       == Info.Ctx.getIntWidth(E->getType()));
7158     if (SameSign && SameWidth)
7159       return Success(ECD->getInitVal(), E);
7160     else {
7161       // Get rid of mismatch (otherwise Success assertions will fail)
7162       // by computing a new value matching the type of E.
7163       llvm::APSInt Val = ECD->getInitVal();
7164       if (!SameSign)
7165         Val.setIsSigned(!ECD->getInitVal().isSigned());
7166       if (!SameWidth)
7167         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7168       return Success(Val, E);
7169     }
7170   }
7171   return false;
7172 }
7173 
7174 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7175 /// as GCC.
7176 static int EvaluateBuiltinClassifyType(const CallExpr *E,
7177                                        const LangOptions &LangOpts) {
7178   // The following enum mimics the values returned by GCC.
7179   // FIXME: Does GCC differ between lvalue and rvalue references here?
7180   enum gcc_type_class {
7181     no_type_class = -1,
7182     void_type_class, integer_type_class, char_type_class,
7183     enumeral_type_class, boolean_type_class,
7184     pointer_type_class, reference_type_class, offset_type_class,
7185     real_type_class, complex_type_class,
7186     function_type_class, method_type_class,
7187     record_type_class, union_type_class,
7188     array_type_class, string_type_class,
7189     lang_type_class
7190   };
7191 
7192   // If no argument was supplied, default to "no_type_class". This isn't
7193   // ideal, however it is what gcc does.
7194   if (E->getNumArgs() == 0)
7195     return no_type_class;
7196 
7197   QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7198   const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7199 
7200   switch (CanTy->getTypeClass()) {
7201 #define TYPE(ID, BASE)
7202 #define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7203 #define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7204 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7205 #include "clang/AST/TypeNodes.def"
7206       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7207 
7208   case Type::Builtin:
7209     switch (BT->getKind()) {
7210 #define BUILTIN_TYPE(ID, SINGLETON_ID)
7211 #define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7212 #define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7213 #define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7214 #include "clang/AST/BuiltinTypes.def"
7215     case BuiltinType::Void:
7216       return void_type_class;
7217 
7218     case BuiltinType::Bool:
7219       return boolean_type_class;
7220 
7221     case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7222     case BuiltinType::UChar:
7223     case BuiltinType::UShort:
7224     case BuiltinType::UInt:
7225     case BuiltinType::ULong:
7226     case BuiltinType::ULongLong:
7227     case BuiltinType::UInt128:
7228       return integer_type_class;
7229 
7230     case BuiltinType::NullPtr:
7231       return pointer_type_class;
7232 
7233     case BuiltinType::WChar_U:
7234     case BuiltinType::Char16:
7235     case BuiltinType::Char32:
7236     case BuiltinType::ObjCId:
7237     case BuiltinType::ObjCClass:
7238     case BuiltinType::ObjCSel:
7239 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7240     case BuiltinType::Id:
7241 #include "clang/Basic/OpenCLImageTypes.def"
7242     case BuiltinType::OCLSampler:
7243     case BuiltinType::OCLEvent:
7244     case BuiltinType::OCLClkEvent:
7245     case BuiltinType::OCLQueue:
7246     case BuiltinType::OCLReserveID:
7247     case BuiltinType::Dependent:
7248       llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7249     };
7250     break;
7251 
7252   case Type::Enum:
7253     return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7254     break;
7255 
7256   case Type::Pointer:
7257     return pointer_type_class;
7258     break;
7259 
7260   case Type::MemberPointer:
7261     if (CanTy->isMemberDataPointerType())
7262       return offset_type_class;
7263     else {
7264       // We expect member pointers to be either data or function pointers,
7265       // nothing else.
7266       assert(CanTy->isMemberFunctionPointerType());
7267       return method_type_class;
7268     }
7269 
7270   case Type::Complex:
7271     return complex_type_class;
7272 
7273   case Type::FunctionNoProto:
7274   case Type::FunctionProto:
7275     return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7276 
7277   case Type::Record:
7278     if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7279       switch (RT->getDecl()->getTagKind()) {
7280       case TagTypeKind::TTK_Struct:
7281       case TagTypeKind::TTK_Class:
7282       case TagTypeKind::TTK_Interface:
7283         return record_type_class;
7284 
7285       case TagTypeKind::TTK_Enum:
7286         return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7287 
7288       case TagTypeKind::TTK_Union:
7289         return union_type_class;
7290       }
7291     }
7292     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7293 
7294   case Type::ConstantArray:
7295   case Type::VariableArray:
7296   case Type::IncompleteArray:
7297     return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7298 
7299   case Type::BlockPointer:
7300   case Type::LValueReference:
7301   case Type::RValueReference:
7302   case Type::Vector:
7303   case Type::ExtVector:
7304   case Type::Auto:
7305   case Type::DeducedTemplateSpecialization:
7306   case Type::ObjCObject:
7307   case Type::ObjCInterface:
7308   case Type::ObjCObjectPointer:
7309   case Type::Pipe:
7310   case Type::Atomic:
7311     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7312   }
7313 
7314   llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7315 }
7316 
7317 /// EvaluateBuiltinConstantPForLValue - Determine the result of
7318 /// __builtin_constant_p when applied to the given lvalue.
7319 ///
7320 /// An lvalue is only "constant" if it is a pointer or reference to the first
7321 /// character of a string literal.
7322 template<typename LValue>
7323 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
7324   const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
7325   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7326 }
7327 
7328 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7329 /// GCC as we can manage.
7330 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7331   QualType ArgType = Arg->getType();
7332 
7333   // __builtin_constant_p always has one operand. The rules which gcc follows
7334   // are not precisely documented, but are as follows:
7335   //
7336   //  - If the operand is of integral, floating, complex or enumeration type,
7337   //    and can be folded to a known value of that type, it returns 1.
7338   //  - If the operand and can be folded to a pointer to the first character
7339   //    of a string literal (or such a pointer cast to an integral type), it
7340   //    returns 1.
7341   //
7342   // Otherwise, it returns 0.
7343   //
7344   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7345   // its support for this does not currently work.
7346   if (ArgType->isIntegralOrEnumerationType()) {
7347     Expr::EvalResult Result;
7348     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7349       return false;
7350 
7351     APValue &V = Result.Val;
7352     if (V.getKind() == APValue::Int)
7353       return true;
7354     if (V.getKind() == APValue::LValue)
7355       return EvaluateBuiltinConstantPForLValue(V);
7356   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7357     return Arg->isEvaluatable(Ctx);
7358   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7359     LValue LV;
7360     Expr::EvalStatus Status;
7361     EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
7362     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7363                           : EvaluatePointer(Arg, LV, Info)) &&
7364         !Status.HasSideEffects)
7365       return EvaluateBuiltinConstantPForLValue(LV);
7366   }
7367 
7368   // Anything else isn't considered to be sufficiently constant.
7369   return false;
7370 }
7371 
7372 /// Retrieves the "underlying object type" of the given expression,
7373 /// as used by __builtin_object_size.
7374 static QualType getObjectType(APValue::LValueBase B) {
7375   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7376     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
7377       return VD->getType();
7378   } else if (const Expr *E = B.get<const Expr*>()) {
7379     if (isa<CompoundLiteralExpr>(E))
7380       return E->getType();
7381   }
7382 
7383   return QualType();
7384 }
7385 
7386 /// A more selective version of E->IgnoreParenCasts for
7387 /// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
7388 /// to change the type of E.
7389 /// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7390 ///
7391 /// Always returns an RValue with a pointer representation.
7392 static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7393   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7394 
7395   auto *NoParens = E->IgnoreParens();
7396   auto *Cast = dyn_cast<CastExpr>(NoParens);
7397   if (Cast == nullptr)
7398     return NoParens;
7399 
7400   // We only conservatively allow a few kinds of casts, because this code is
7401   // inherently a simple solution that seeks to support the common case.
7402   auto CastKind = Cast->getCastKind();
7403   if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7404       CastKind != CK_AddressSpaceConversion)
7405     return NoParens;
7406 
7407   auto *SubExpr = Cast->getSubExpr();
7408   if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7409     return NoParens;
7410   return ignorePointerCastsAndParens(SubExpr);
7411 }
7412 
7413 /// Checks to see if the given LValue's Designator is at the end of the LValue's
7414 /// record layout. e.g.
7415 ///   struct { struct { int a, b; } fst, snd; } obj;
7416 ///   obj.fst   // no
7417 ///   obj.snd   // yes
7418 ///   obj.fst.a // no
7419 ///   obj.fst.b // no
7420 ///   obj.snd.a // no
7421 ///   obj.snd.b // yes
7422 ///
7423 /// Please note: this function is specialized for how __builtin_object_size
7424 /// views "objects".
7425 ///
7426 /// If this encounters an invalid RecordDecl or otherwise cannot determine the
7427 /// correct result, it will always return true.
7428 static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7429   assert(!LVal.Designator.Invalid);
7430 
7431   auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7432     const RecordDecl *Parent = FD->getParent();
7433     Invalid = Parent->isInvalidDecl();
7434     if (Invalid || Parent->isUnion())
7435       return true;
7436     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
7437     return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7438   };
7439 
7440   auto &Base = LVal.getLValueBase();
7441   if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7442     if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
7443       bool Invalid;
7444       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7445         return Invalid;
7446     } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
7447       for (auto *FD : IFD->chain()) {
7448         bool Invalid;
7449         if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7450           return Invalid;
7451       }
7452     }
7453   }
7454 
7455   unsigned I = 0;
7456   QualType BaseType = getType(Base);
7457   if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
7458     // If we don't know the array bound, conservatively assume we're looking at
7459     // the final array element.
7460     ++I;
7461     if (BaseType->isIncompleteArrayType())
7462       BaseType = Ctx.getAsArrayType(BaseType)->getElementType();
7463     else
7464       BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7465   }
7466 
7467   for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7468     const auto &Entry = LVal.Designator.Entries[I];
7469     if (BaseType->isArrayType()) {
7470       // Because __builtin_object_size treats arrays as objects, we can ignore
7471       // the index iff this is the last array in the Designator.
7472       if (I + 1 == E)
7473         return true;
7474       const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7475       uint64_t Index = Entry.ArrayIndex;
7476       if (Index + 1 != CAT->getSize())
7477         return false;
7478       BaseType = CAT->getElementType();
7479     } else if (BaseType->isAnyComplexType()) {
7480       const auto *CT = BaseType->castAs<ComplexType>();
7481       uint64_t Index = Entry.ArrayIndex;
7482       if (Index != 1)
7483         return false;
7484       BaseType = CT->getElementType();
7485     } else if (auto *FD = getAsField(Entry)) {
7486       bool Invalid;
7487       if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7488         return Invalid;
7489       BaseType = FD->getType();
7490     } else {
7491       assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
7492       return false;
7493     }
7494   }
7495   return true;
7496 }
7497 
7498 /// Tests to see if the LValue has a user-specified designator (that isn't
7499 /// necessarily valid). Note that this always returns 'true' if the LValue has
7500 /// an unsized array as its first designator entry, because there's currently no
7501 /// way to tell if the user typed *foo or foo[0].
7502 static bool refersToCompleteObject(const LValue &LVal) {
7503   if (LVal.Designator.Invalid)
7504     return false;
7505 
7506   if (!LVal.Designator.Entries.empty())
7507     return LVal.Designator.isMostDerivedAnUnsizedArray();
7508 
7509   if (!LVal.InvalidBase)
7510     return true;
7511 
7512   // If `E` is a MemberExpr, then the first part of the designator is hiding in
7513   // the LValueBase.
7514   const auto *E = LVal.Base.dyn_cast<const Expr *>();
7515   return !E || !isa<MemberExpr>(E);
7516 }
7517 
7518 /// Attempts to detect a user writing into a piece of memory that's impossible
7519 /// to figure out the size of by just using types.
7520 static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7521   const SubobjectDesignator &Designator = LVal.Designator;
7522   // Notes:
7523   // - Users can only write off of the end when we have an invalid base. Invalid
7524   //   bases imply we don't know where the memory came from.
7525   // - We used to be a bit more aggressive here; we'd only be conservative if
7526   //   the array at the end was flexible, or if it had 0 or 1 elements. This
7527   //   broke some common standard library extensions (PR30346), but was
7528   //   otherwise seemingly fine. It may be useful to reintroduce this behavior
7529   //   with some sort of whitelist. OTOH, it seems that GCC is always
7530   //   conservative with the last element in structs (if it's an array), so our
7531   //   current behavior is more compatible than a whitelisting approach would
7532   //   be.
7533   return LVal.InvalidBase &&
7534          Designator.Entries.size() == Designator.MostDerivedPathLength &&
7535          Designator.MostDerivedIsArrayElement &&
7536          isDesignatorAtObjectEnd(Ctx, LVal);
7537 }
7538 
7539 /// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7540 /// Fails if the conversion would cause loss of precision.
7541 static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7542                                             CharUnits &Result) {
7543   auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7544   if (Int.ugt(CharUnitsMax))
7545     return false;
7546   Result = CharUnits::fromQuantity(Int.getZExtValue());
7547   return true;
7548 }
7549 
7550 /// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7551 /// determine how many bytes exist from the beginning of the object to either
7552 /// the end of the current subobject, or the end of the object itself, depending
7553 /// on what the LValue looks like + the value of Type.
7554 ///
7555 /// If this returns false, the value of Result is undefined.
7556 static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7557                                unsigned Type, const LValue &LVal,
7558                                CharUnits &EndOffset) {
7559   bool DetermineForCompleteObject = refersToCompleteObject(LVal);
7560 
7561   auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7562     if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7563       return false;
7564     return HandleSizeof(Info, ExprLoc, Ty, Result);
7565   };
7566 
7567   // We want to evaluate the size of the entire object. This is a valid fallback
7568   // for when Type=1 and the designator is invalid, because we're asked for an
7569   // upper-bound.
7570   if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7571     // Type=3 wants a lower bound, so we can't fall back to this.
7572     if (Type == 3 && !DetermineForCompleteObject)
7573       return false;
7574 
7575     llvm::APInt APEndOffset;
7576     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7577         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7578       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7579 
7580     if (LVal.InvalidBase)
7581       return false;
7582 
7583     QualType BaseTy = getObjectType(LVal.getLValueBase());
7584     return CheckedHandleSizeof(BaseTy, EndOffset);
7585   }
7586 
7587   // We want to evaluate the size of a subobject.
7588   const SubobjectDesignator &Designator = LVal.Designator;
7589 
7590   // The following is a moderately common idiom in C:
7591   //
7592   // struct Foo { int a; char c[1]; };
7593   // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7594   // strcpy(&F->c[0], Bar);
7595   //
7596   // In order to not break too much legacy code, we need to support it.
7597   if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7598     // If we can resolve this to an alloc_size call, we can hand that back,
7599     // because we know for certain how many bytes there are to write to.
7600     llvm::APInt APEndOffset;
7601     if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7602         getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7603       return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7604 
7605     // If we cannot determine the size of the initial allocation, then we can't
7606     // given an accurate upper-bound. However, we are still able to give
7607     // conservative lower-bounds for Type=3.
7608     if (Type == 1)
7609       return false;
7610   }
7611 
7612   CharUnits BytesPerElem;
7613   if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
7614     return false;
7615 
7616   // According to the GCC documentation, we want the size of the subobject
7617   // denoted by the pointer. But that's not quite right -- what we actually
7618   // want is the size of the immediately-enclosing array, if there is one.
7619   int64_t ElemsRemaining;
7620   if (Designator.MostDerivedIsArrayElement &&
7621       Designator.Entries.size() == Designator.MostDerivedPathLength) {
7622     uint64_t ArraySize = Designator.getMostDerivedArraySize();
7623     uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7624     ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7625   } else {
7626     ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7627   }
7628 
7629   EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7630   return true;
7631 }
7632 
7633 /// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7634 /// returns true and stores the result in @p Size.
7635 ///
7636 /// If @p WasError is non-null, this will report whether the failure to evaluate
7637 /// is to be treated as an Error in IntExprEvaluator.
7638 static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7639                                          EvalInfo &Info, uint64_t &Size) {
7640   // Determine the denoted object.
7641   LValue LVal;
7642   {
7643     // The operand of __builtin_object_size is never evaluated for side-effects.
7644     // If there are any, but we can determine the pointed-to object anyway, then
7645     // ignore the side-effects.
7646     SpeculativeEvaluationRAII SpeculativeEval(Info);
7647     FoldOffsetRAII Fold(Info);
7648 
7649     if (E->isGLValue()) {
7650       // It's possible for us to be given GLValues if we're called via
7651       // Expr::tryEvaluateObjectSize.
7652       APValue RVal;
7653       if (!EvaluateAsRValue(Info, E, RVal))
7654         return false;
7655       LVal.setFrom(Info.Ctx, RVal);
7656     } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7657                                 /*InvalidBaseOK=*/true))
7658       return false;
7659   }
7660 
7661   // If we point to before the start of the object, there are no accessible
7662   // bytes.
7663   if (LVal.getLValueOffset().isNegative()) {
7664     Size = 0;
7665     return true;
7666   }
7667 
7668   CharUnits EndOffset;
7669   if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7670     return false;
7671 
7672   // If we've fallen outside of the end offset, just pretend there's nothing to
7673   // write to/read from.
7674   if (EndOffset <= LVal.getLValueOffset())
7675     Size = 0;
7676   else
7677     Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7678   return true;
7679 }
7680 
7681 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
7682   if (unsigned BuiltinOp = E->getBuiltinCallee())
7683     return VisitBuiltinCallExpr(E, BuiltinOp);
7684 
7685   return ExprEvaluatorBaseTy::VisitCallExpr(E);
7686 }
7687 
7688 bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7689                                             unsigned BuiltinOp) {
7690   switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
7691   default:
7692     return ExprEvaluatorBaseTy::VisitCallExpr(E);
7693 
7694   case Builtin::BI__builtin_object_size: {
7695     // The type was checked when we built the expression.
7696     unsigned Type =
7697         E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7698     assert(Type <= 3 && "unexpected type");
7699 
7700     uint64_t Size;
7701     if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7702       return Success(Size, E);
7703 
7704     if (E->getArg(0)->HasSideEffects(Info.Ctx))
7705       return Success((Type & 2) ? 0 : -1, E);
7706 
7707     // Expression had no side effects, but we couldn't statically determine the
7708     // size of the referenced object.
7709     switch (Info.EvalMode) {
7710     case EvalInfo::EM_ConstantExpression:
7711     case EvalInfo::EM_PotentialConstantExpression:
7712     case EvalInfo::EM_ConstantFold:
7713     case EvalInfo::EM_EvaluateForOverflow:
7714     case EvalInfo::EM_IgnoreSideEffects:
7715     case EvalInfo::EM_OffsetFold:
7716       // Leave it to IR generation.
7717       return Error(E);
7718     case EvalInfo::EM_ConstantExpressionUnevaluated:
7719     case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
7720       // Reduce it to a constant now.
7721       return Success((Type & 2) ? 0 : -1, E);
7722     }
7723 
7724     llvm_unreachable("unexpected EvalMode");
7725   }
7726 
7727   case Builtin::BI__builtin_bswap16:
7728   case Builtin::BI__builtin_bswap32:
7729   case Builtin::BI__builtin_bswap64: {
7730     APSInt Val;
7731     if (!EvaluateInteger(E->getArg(0), Val, Info))
7732       return false;
7733 
7734     return Success(Val.byteSwap(), E);
7735   }
7736 
7737   case Builtin::BI__builtin_classify_type:
7738     return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
7739 
7740   // FIXME: BI__builtin_clrsb
7741   // FIXME: BI__builtin_clrsbl
7742   // FIXME: BI__builtin_clrsbll
7743 
7744   case Builtin::BI__builtin_clz:
7745   case Builtin::BI__builtin_clzl:
7746   case Builtin::BI__builtin_clzll:
7747   case Builtin::BI__builtin_clzs: {
7748     APSInt Val;
7749     if (!EvaluateInteger(E->getArg(0), Val, Info))
7750       return false;
7751     if (!Val)
7752       return Error(E);
7753 
7754     return Success(Val.countLeadingZeros(), E);
7755   }
7756 
7757   case Builtin::BI__builtin_constant_p:
7758     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7759 
7760   case Builtin::BI__builtin_ctz:
7761   case Builtin::BI__builtin_ctzl:
7762   case Builtin::BI__builtin_ctzll:
7763   case Builtin::BI__builtin_ctzs: {
7764     APSInt Val;
7765     if (!EvaluateInteger(E->getArg(0), Val, Info))
7766       return false;
7767     if (!Val)
7768       return Error(E);
7769 
7770     return Success(Val.countTrailingZeros(), E);
7771   }
7772 
7773   case Builtin::BI__builtin_eh_return_data_regno: {
7774     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7775     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7776     return Success(Operand, E);
7777   }
7778 
7779   case Builtin::BI__builtin_expect:
7780     return Visit(E->getArg(0));
7781 
7782   case Builtin::BI__builtin_ffs:
7783   case Builtin::BI__builtin_ffsl:
7784   case Builtin::BI__builtin_ffsll: {
7785     APSInt Val;
7786     if (!EvaluateInteger(E->getArg(0), Val, Info))
7787       return false;
7788 
7789     unsigned N = Val.countTrailingZeros();
7790     return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7791   }
7792 
7793   case Builtin::BI__builtin_fpclassify: {
7794     APFloat Val(0.0);
7795     if (!EvaluateFloat(E->getArg(5), Val, Info))
7796       return false;
7797     unsigned Arg;
7798     switch (Val.getCategory()) {
7799     case APFloat::fcNaN: Arg = 0; break;
7800     case APFloat::fcInfinity: Arg = 1; break;
7801     case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7802     case APFloat::fcZero: Arg = 4; break;
7803     }
7804     return Visit(E->getArg(Arg));
7805   }
7806 
7807   case Builtin::BI__builtin_isinf_sign: {
7808     APFloat Val(0.0);
7809     return EvaluateFloat(E->getArg(0), Val, Info) &&
7810            Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7811   }
7812 
7813   case Builtin::BI__builtin_isinf: {
7814     APFloat Val(0.0);
7815     return EvaluateFloat(E->getArg(0), Val, Info) &&
7816            Success(Val.isInfinity() ? 1 : 0, E);
7817   }
7818 
7819   case Builtin::BI__builtin_isfinite: {
7820     APFloat Val(0.0);
7821     return EvaluateFloat(E->getArg(0), Val, Info) &&
7822            Success(Val.isFinite() ? 1 : 0, E);
7823   }
7824 
7825   case Builtin::BI__builtin_isnan: {
7826     APFloat Val(0.0);
7827     return EvaluateFloat(E->getArg(0), Val, Info) &&
7828            Success(Val.isNaN() ? 1 : 0, E);
7829   }
7830 
7831   case Builtin::BI__builtin_isnormal: {
7832     APFloat Val(0.0);
7833     return EvaluateFloat(E->getArg(0), Val, Info) &&
7834            Success(Val.isNormal() ? 1 : 0, E);
7835   }
7836 
7837   case Builtin::BI__builtin_parity:
7838   case Builtin::BI__builtin_parityl:
7839   case Builtin::BI__builtin_parityll: {
7840     APSInt Val;
7841     if (!EvaluateInteger(E->getArg(0), Val, Info))
7842       return false;
7843 
7844     return Success(Val.countPopulation() % 2, E);
7845   }
7846 
7847   case Builtin::BI__builtin_popcount:
7848   case Builtin::BI__builtin_popcountl:
7849   case Builtin::BI__builtin_popcountll: {
7850     APSInt Val;
7851     if (!EvaluateInteger(E->getArg(0), Val, Info))
7852       return false;
7853 
7854     return Success(Val.countPopulation(), E);
7855   }
7856 
7857   case Builtin::BIstrlen:
7858   case Builtin::BIwcslen:
7859     // A call to strlen is not a constant expression.
7860     if (Info.getLangOpts().CPlusPlus11)
7861       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7862         << /*isConstexpr*/0 << /*isConstructor*/0
7863         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7864     else
7865       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7866     LLVM_FALLTHROUGH;
7867   case Builtin::BI__builtin_strlen:
7868   case Builtin::BI__builtin_wcslen: {
7869     // As an extension, we support __builtin_strlen() as a constant expression,
7870     // and support folding strlen() to a constant.
7871     LValue String;
7872     if (!EvaluatePointer(E->getArg(0), String, Info))
7873       return false;
7874 
7875     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7876 
7877     // Fast path: if it's a string literal, search the string value.
7878     if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7879             String.getLValueBase().dyn_cast<const Expr *>())) {
7880       // The string literal may have embedded null characters. Find the first
7881       // one and truncate there.
7882       StringRef Str = S->getBytes();
7883       int64_t Off = String.Offset.getQuantity();
7884       if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7885           S->getCharByteWidth() == 1 &&
7886           // FIXME: Add fast-path for wchar_t too.
7887           Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
7888         Str = Str.substr(Off);
7889 
7890         StringRef::size_type Pos = Str.find(0);
7891         if (Pos != StringRef::npos)
7892           Str = Str.substr(0, Pos);
7893 
7894         return Success(Str.size(), E);
7895       }
7896 
7897       // Fall through to slow path to issue appropriate diagnostic.
7898     }
7899 
7900     // Slow path: scan the bytes of the string looking for the terminating 0.
7901     for (uint64_t Strlen = 0; /**/; ++Strlen) {
7902       APValue Char;
7903       if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7904           !Char.isInt())
7905         return false;
7906       if (!Char.getInt())
7907         return Success(Strlen, E);
7908       if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7909         return false;
7910     }
7911   }
7912 
7913   case Builtin::BIstrcmp:
7914   case Builtin::BIwcscmp:
7915   case Builtin::BIstrncmp:
7916   case Builtin::BIwcsncmp:
7917   case Builtin::BImemcmp:
7918   case Builtin::BIwmemcmp:
7919     // A call to strlen is not a constant expression.
7920     if (Info.getLangOpts().CPlusPlus11)
7921       Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7922         << /*isConstexpr*/0 << /*isConstructor*/0
7923         << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
7924     else
7925       Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7926     LLVM_FALLTHROUGH;
7927   case Builtin::BI__builtin_strcmp:
7928   case Builtin::BI__builtin_wcscmp:
7929   case Builtin::BI__builtin_strncmp:
7930   case Builtin::BI__builtin_wcsncmp:
7931   case Builtin::BI__builtin_memcmp:
7932   case Builtin::BI__builtin_wmemcmp: {
7933     LValue String1, String2;
7934     if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7935         !EvaluatePointer(E->getArg(1), String2, Info))
7936       return false;
7937 
7938     QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7939 
7940     uint64_t MaxLength = uint64_t(-1);
7941     if (BuiltinOp != Builtin::BIstrcmp &&
7942         BuiltinOp != Builtin::BIwcscmp &&
7943         BuiltinOp != Builtin::BI__builtin_strcmp &&
7944         BuiltinOp != Builtin::BI__builtin_wcscmp) {
7945       APSInt N;
7946       if (!EvaluateInteger(E->getArg(2), N, Info))
7947         return false;
7948       MaxLength = N.getExtValue();
7949     }
7950     bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
7951                        BuiltinOp != Builtin::BIwmemcmp &&
7952                        BuiltinOp != Builtin::BI__builtin_memcmp &&
7953                        BuiltinOp != Builtin::BI__builtin_wmemcmp);
7954     for (; MaxLength; --MaxLength) {
7955       APValue Char1, Char2;
7956       if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7957           !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7958           !Char1.isInt() || !Char2.isInt())
7959         return false;
7960       if (Char1.getInt() != Char2.getInt())
7961         return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7962       if (StopAtNull && !Char1.getInt())
7963         return Success(0, E);
7964       assert(!(StopAtNull && !Char2.getInt()));
7965       if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7966           !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7967         return false;
7968     }
7969     // We hit the strncmp / memcmp limit.
7970     return Success(0, E);
7971   }
7972 
7973   case Builtin::BI__atomic_always_lock_free:
7974   case Builtin::BI__atomic_is_lock_free:
7975   case Builtin::BI__c11_atomic_is_lock_free: {
7976     APSInt SizeVal;
7977     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7978       return false;
7979 
7980     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7981     // of two less than the maximum inline atomic width, we know it is
7982     // lock-free.  If the size isn't a power of two, or greater than the
7983     // maximum alignment where we promote atomics, we know it is not lock-free
7984     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
7985     // the answer can only be determined at runtime; for example, 16-byte
7986     // atomics have lock-free implementations on some, but not all,
7987     // x86-64 processors.
7988 
7989     // Check power-of-two.
7990     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
7991     if (Size.isPowerOfTwo()) {
7992       // Check against inlining width.
7993       unsigned InlineWidthBits =
7994           Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7995       if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7996         if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7997             Size == CharUnits::One() ||
7998             E->getArg(1)->isNullPointerConstant(Info.Ctx,
7999                                                 Expr::NPC_NeverValueDependent))
8000           // OK, we will inline appropriately-aligned operations of this size,
8001           // and _Atomic(T) is appropriately-aligned.
8002           return Success(1, E);
8003 
8004         QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
8005           castAs<PointerType>()->getPointeeType();
8006         if (!PointeeType->isIncompleteType() &&
8007             Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
8008           // OK, we will inline operations on this object.
8009           return Success(1, E);
8010         }
8011       }
8012     }
8013 
8014     return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
8015         Success(0, E) : Error(E);
8016   }
8017   case Builtin::BIomp_is_initial_device:
8018     // We can decide statically which value the runtime would return if called.
8019     return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
8020   }
8021 }
8022 
8023 static bool HasSameBase(const LValue &A, const LValue &B) {
8024   if (!A.getLValueBase())
8025     return !B.getLValueBase();
8026   if (!B.getLValueBase())
8027     return false;
8028 
8029   if (A.getLValueBase().getOpaqueValue() !=
8030       B.getLValueBase().getOpaqueValue()) {
8031     const Decl *ADecl = GetLValueBaseDecl(A);
8032     if (!ADecl)
8033       return false;
8034     const Decl *BDecl = GetLValueBaseDecl(B);
8035     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
8036       return false;
8037   }
8038 
8039   return IsGlobalLValue(A.getLValueBase()) ||
8040          A.getLValueCallIndex() == B.getLValueCallIndex();
8041 }
8042 
8043 /// \brief Determine whether this is a pointer past the end of the complete
8044 /// object referred to by the lvalue.
8045 static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8046                                             const LValue &LV) {
8047   // A null pointer can be viewed as being "past the end" but we don't
8048   // choose to look at it that way here.
8049   if (!LV.getLValueBase())
8050     return false;
8051 
8052   // If the designator is valid and refers to a subobject, we're not pointing
8053   // past the end.
8054   if (!LV.getLValueDesignator().Invalid &&
8055       !LV.getLValueDesignator().isOnePastTheEnd())
8056     return false;
8057 
8058   // A pointer to an incomplete type might be past-the-end if the type's size is
8059   // zero.  We cannot tell because the type is incomplete.
8060   QualType Ty = getType(LV.getLValueBase());
8061   if (Ty->isIncompleteType())
8062     return true;
8063 
8064   // We're a past-the-end pointer if we point to the byte after the object,
8065   // no matter what our type or path is.
8066   auto Size = Ctx.getTypeSizeInChars(Ty);
8067   return LV.getLValueOffset() == Size;
8068 }
8069 
8070 namespace {
8071 
8072 /// \brief Data recursive integer evaluator of certain binary operators.
8073 ///
8074 /// We use a data recursive algorithm for binary operators so that we are able
8075 /// to handle extreme cases of chained binary operators without causing stack
8076 /// overflow.
8077 class DataRecursiveIntBinOpEvaluator {
8078   struct EvalResult {
8079     APValue Val;
8080     bool Failed;
8081 
8082     EvalResult() : Failed(false) { }
8083 
8084     void swap(EvalResult &RHS) {
8085       Val.swap(RHS.Val);
8086       Failed = RHS.Failed;
8087       RHS.Failed = false;
8088     }
8089   };
8090 
8091   struct Job {
8092     const Expr *E;
8093     EvalResult LHSResult; // meaningful only for binary operator expression.
8094     enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
8095 
8096     Job() = default;
8097     Job(Job &&) = default;
8098 
8099     void startSpeculativeEval(EvalInfo &Info) {
8100       SpecEvalRAII = SpeculativeEvaluationRAII(Info);
8101     }
8102 
8103   private:
8104     SpeculativeEvaluationRAII SpecEvalRAII;
8105   };
8106 
8107   SmallVector<Job, 16> Queue;
8108 
8109   IntExprEvaluator &IntEval;
8110   EvalInfo &Info;
8111   APValue &FinalResult;
8112 
8113 public:
8114   DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8115     : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8116 
8117   /// \brief True if \param E is a binary operator that we are going to handle
8118   /// data recursively.
8119   /// We handle binary operators that are comma, logical, or that have operands
8120   /// with integral or enumeration type.
8121   static bool shouldEnqueue(const BinaryOperator *E) {
8122     return E->getOpcode() == BO_Comma ||
8123            E->isLogicalOp() ||
8124            (E->isRValue() &&
8125             E->getType()->isIntegralOrEnumerationType() &&
8126             E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8127             E->getRHS()->getType()->isIntegralOrEnumerationType());
8128   }
8129 
8130   bool Traverse(const BinaryOperator *E) {
8131     enqueue(E);
8132     EvalResult PrevResult;
8133     while (!Queue.empty())
8134       process(PrevResult);
8135 
8136     if (PrevResult.Failed) return false;
8137 
8138     FinalResult.swap(PrevResult.Val);
8139     return true;
8140   }
8141 
8142 private:
8143   bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8144     return IntEval.Success(Value, E, Result);
8145   }
8146   bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8147     return IntEval.Success(Value, E, Result);
8148   }
8149   bool Error(const Expr *E) {
8150     return IntEval.Error(E);
8151   }
8152   bool Error(const Expr *E, diag::kind D) {
8153     return IntEval.Error(E, D);
8154   }
8155 
8156   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8157     return Info.CCEDiag(E, D);
8158   }
8159 
8160   // \brief Returns true if visiting the RHS is necessary, false otherwise.
8161   bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8162                          bool &SuppressRHSDiags);
8163 
8164   bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8165                   const BinaryOperator *E, APValue &Result);
8166 
8167   void EvaluateExpr(const Expr *E, EvalResult &Result) {
8168     Result.Failed = !Evaluate(Result.Val, Info, E);
8169     if (Result.Failed)
8170       Result.Val = APValue();
8171   }
8172 
8173   void process(EvalResult &Result);
8174 
8175   void enqueue(const Expr *E) {
8176     E = E->IgnoreParens();
8177     Queue.resize(Queue.size()+1);
8178     Queue.back().E = E;
8179     Queue.back().Kind = Job::AnyExprKind;
8180   }
8181 };
8182 
8183 }
8184 
8185 bool DataRecursiveIntBinOpEvaluator::
8186        VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
8187                          bool &SuppressRHSDiags) {
8188   if (E->getOpcode() == BO_Comma) {
8189     // Ignore LHS but note if we could not evaluate it.
8190     if (LHSResult.Failed)
8191       return Info.noteSideEffect();
8192     return true;
8193   }
8194 
8195   if (E->isLogicalOp()) {
8196     bool LHSAsBool;
8197     if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
8198       // We were able to evaluate the LHS, see if we can get away with not
8199       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
8200       if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8201         Success(LHSAsBool, E, LHSResult.Val);
8202         return false; // Ignore RHS
8203       }
8204     } else {
8205       LHSResult.Failed = true;
8206 
8207       // Since we weren't able to evaluate the left hand side, it
8208       // might have had side effects.
8209       if (!Info.noteSideEffect())
8210         return false;
8211 
8212       // We can't evaluate the LHS; however, sometimes the result
8213       // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8214       // Don't ignore RHS and suppress diagnostics from this arm.
8215       SuppressRHSDiags = true;
8216     }
8217 
8218     return true;
8219   }
8220 
8221   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8222          E->getRHS()->getType()->isIntegralOrEnumerationType());
8223 
8224   if (LHSResult.Failed && !Info.noteFailure())
8225     return false; // Ignore RHS;
8226 
8227   return true;
8228 }
8229 
8230 static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8231                                     bool IsSub) {
8232   // Compute the new offset in the appropriate width, wrapping at 64 bits.
8233   // FIXME: When compiling for a 32-bit target, we should use 32-bit
8234   // offsets.
8235   assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8236   CharUnits &Offset = LVal.getLValueOffset();
8237   uint64_t Offset64 = Offset.getQuantity();
8238   uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8239   Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8240                                          : Offset64 + Index64);
8241 }
8242 
8243 bool DataRecursiveIntBinOpEvaluator::
8244        VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8245                   const BinaryOperator *E, APValue &Result) {
8246   if (E->getOpcode() == BO_Comma) {
8247     if (RHSResult.Failed)
8248       return false;
8249     Result = RHSResult.Val;
8250     return true;
8251   }
8252 
8253   if (E->isLogicalOp()) {
8254     bool lhsResult, rhsResult;
8255     bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8256     bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
8257 
8258     if (LHSIsOK) {
8259       if (RHSIsOK) {
8260         if (E->getOpcode() == BO_LOr)
8261           return Success(lhsResult || rhsResult, E, Result);
8262         else
8263           return Success(lhsResult && rhsResult, E, Result);
8264       }
8265     } else {
8266       if (RHSIsOK) {
8267         // We can't evaluate the LHS; however, sometimes the result
8268         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8269         if (rhsResult == (E->getOpcode() == BO_LOr))
8270           return Success(rhsResult, E, Result);
8271       }
8272     }
8273 
8274     return false;
8275   }
8276 
8277   assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8278          E->getRHS()->getType()->isIntegralOrEnumerationType());
8279 
8280   if (LHSResult.Failed || RHSResult.Failed)
8281     return false;
8282 
8283   const APValue &LHSVal = LHSResult.Val;
8284   const APValue &RHSVal = RHSResult.Val;
8285 
8286   // Handle cases like (unsigned long)&a + 4.
8287   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8288     Result = LHSVal;
8289     addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
8290     return true;
8291   }
8292 
8293   // Handle cases like 4 + (unsigned long)&a
8294   if (E->getOpcode() == BO_Add &&
8295       RHSVal.isLValue() && LHSVal.isInt()) {
8296     Result = RHSVal;
8297     addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
8298     return true;
8299   }
8300 
8301   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8302     // Handle (intptr_t)&&A - (intptr_t)&&B.
8303     if (!LHSVal.getLValueOffset().isZero() ||
8304         !RHSVal.getLValueOffset().isZero())
8305       return false;
8306     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8307     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8308     if (!LHSExpr || !RHSExpr)
8309       return false;
8310     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8311     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8312     if (!LHSAddrExpr || !RHSAddrExpr)
8313       return false;
8314     // Make sure both labels come from the same function.
8315     if (LHSAddrExpr->getLabel()->getDeclContext() !=
8316         RHSAddrExpr->getLabel()->getDeclContext())
8317       return false;
8318     Result = APValue(LHSAddrExpr, RHSAddrExpr);
8319     return true;
8320   }
8321 
8322   // All the remaining cases expect both operands to be an integer
8323   if (!LHSVal.isInt() || !RHSVal.isInt())
8324     return Error(E);
8325 
8326   // Set up the width and signedness manually, in case it can't be deduced
8327   // from the operation we're performing.
8328   // FIXME: Don't do this in the cases where we can deduce it.
8329   APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8330                E->getType()->isUnsignedIntegerOrEnumerationType());
8331   if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8332                          RHSVal.getInt(), Value))
8333     return false;
8334   return Success(Value, E, Result);
8335 }
8336 
8337 void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
8338   Job &job = Queue.back();
8339 
8340   switch (job.Kind) {
8341     case Job::AnyExprKind: {
8342       if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8343         if (shouldEnqueue(Bop)) {
8344           job.Kind = Job::BinOpKind;
8345           enqueue(Bop->getLHS());
8346           return;
8347         }
8348       }
8349 
8350       EvaluateExpr(job.E, Result);
8351       Queue.pop_back();
8352       return;
8353     }
8354 
8355     case Job::BinOpKind: {
8356       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8357       bool SuppressRHSDiags = false;
8358       if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
8359         Queue.pop_back();
8360         return;
8361       }
8362       if (SuppressRHSDiags)
8363         job.startSpeculativeEval(Info);
8364       job.LHSResult.swap(Result);
8365       job.Kind = Job::BinOpVisitedLHSKind;
8366       enqueue(Bop->getRHS());
8367       return;
8368     }
8369 
8370     case Job::BinOpVisitedLHSKind: {
8371       const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8372       EvalResult RHS;
8373       RHS.swap(Result);
8374       Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
8375       Queue.pop_back();
8376       return;
8377     }
8378   }
8379 
8380   llvm_unreachable("Invalid Job::Kind!");
8381 }
8382 
8383 namespace {
8384 /// Used when we determine that we should fail, but can keep evaluating prior to
8385 /// noting that we had a failure.
8386 class DelayedNoteFailureRAII {
8387   EvalInfo &Info;
8388   bool NoteFailure;
8389 
8390 public:
8391   DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8392       : Info(Info), NoteFailure(NoteFailure) {}
8393   ~DelayedNoteFailureRAII() {
8394     if (NoteFailure) {
8395       bool ContinueAfterFailure = Info.noteFailure();
8396       (void)ContinueAfterFailure;
8397       assert(ContinueAfterFailure &&
8398              "Shouldn't have kept evaluating on failure.");
8399     }
8400   }
8401 };
8402 }
8403 
8404 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
8405   // We don't call noteFailure immediately because the assignment happens after
8406   // we evaluate LHS and RHS.
8407   if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
8408     return Error(E);
8409 
8410   DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
8411   if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8412     return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
8413 
8414   QualType LHSTy = E->getLHS()->getType();
8415   QualType RHSTy = E->getRHS()->getType();
8416 
8417   if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
8418     ComplexValue LHS, RHS;
8419     bool LHSOK;
8420     if (E->isAssignmentOp()) {
8421       LValue LV;
8422       EvaluateLValue(E->getLHS(), LV, Info);
8423       LHSOK = false;
8424     } else if (LHSTy->isRealFloatingType()) {
8425       LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8426       if (LHSOK) {
8427         LHS.makeComplexFloat();
8428         LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8429       }
8430     } else {
8431       LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8432     }
8433     if (!LHSOK && !Info.noteFailure())
8434       return false;
8435 
8436     if (E->getRHS()->getType()->isRealFloatingType()) {
8437       if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8438         return false;
8439       RHS.makeComplexFloat();
8440       RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8441     } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
8442       return false;
8443 
8444     if (LHS.isComplexFloat()) {
8445       APFloat::cmpResult CR_r =
8446         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
8447       APFloat::cmpResult CR_i =
8448         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8449 
8450       if (E->getOpcode() == BO_EQ)
8451         return Success((CR_r == APFloat::cmpEqual &&
8452                         CR_i == APFloat::cmpEqual), E);
8453       else {
8454         assert(E->getOpcode() == BO_NE &&
8455                "Invalid complex comparison.");
8456         return Success(((CR_r == APFloat::cmpGreaterThan ||
8457                          CR_r == APFloat::cmpLessThan ||
8458                          CR_r == APFloat::cmpUnordered) ||
8459                         (CR_i == APFloat::cmpGreaterThan ||
8460                          CR_i == APFloat::cmpLessThan ||
8461                          CR_i == APFloat::cmpUnordered)), E);
8462       }
8463     } else {
8464       if (E->getOpcode() == BO_EQ)
8465         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8466                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8467       else {
8468         assert(E->getOpcode() == BO_NE &&
8469                "Invalid compex comparison.");
8470         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8471                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8472       }
8473     }
8474   }
8475 
8476   if (LHSTy->isRealFloatingType() &&
8477       RHSTy->isRealFloatingType()) {
8478     APFloat RHS(0.0), LHS(0.0);
8479 
8480     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
8481     if (!LHSOK && !Info.noteFailure())
8482       return false;
8483 
8484     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
8485       return false;
8486 
8487     APFloat::cmpResult CR = LHS.compare(RHS);
8488 
8489     switch (E->getOpcode()) {
8490     default:
8491       llvm_unreachable("Invalid binary operator!");
8492     case BO_LT:
8493       return Success(CR == APFloat::cmpLessThan, E);
8494     case BO_GT:
8495       return Success(CR == APFloat::cmpGreaterThan, E);
8496     case BO_LE:
8497       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
8498     case BO_GE:
8499       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
8500                      E);
8501     case BO_EQ:
8502       return Success(CR == APFloat::cmpEqual, E);
8503     case BO_NE:
8504       return Success(CR == APFloat::cmpGreaterThan
8505                      || CR == APFloat::cmpLessThan
8506                      || CR == APFloat::cmpUnordered, E);
8507     }
8508   }
8509 
8510   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
8511     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
8512       LValue LHSValue, RHSValue;
8513 
8514       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
8515       if (!LHSOK && !Info.noteFailure())
8516         return false;
8517 
8518       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8519         return false;
8520 
8521       // Reject differing bases from the normal codepath; we special-case
8522       // comparisons to null.
8523       if (!HasSameBase(LHSValue, RHSValue)) {
8524         if (E->getOpcode() == BO_Sub) {
8525           // Handle &&A - &&B.
8526           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
8527             return Error(E);
8528           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
8529           const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
8530           if (!LHSExpr || !RHSExpr)
8531             return Error(E);
8532           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8533           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8534           if (!LHSAddrExpr || !RHSAddrExpr)
8535             return Error(E);
8536           // Make sure both labels come from the same function.
8537           if (LHSAddrExpr->getLabel()->getDeclContext() !=
8538               RHSAddrExpr->getLabel()->getDeclContext())
8539             return Error(E);
8540           return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
8541         }
8542         // Inequalities and subtractions between unrelated pointers have
8543         // unspecified or undefined behavior.
8544         if (!E->isEqualityOp())
8545           return Error(E);
8546         // A constant address may compare equal to the address of a symbol.
8547         // The one exception is that address of an object cannot compare equal
8548         // to a null pointer constant.
8549         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8550             (!RHSValue.Base && !RHSValue.Offset.isZero()))
8551           return Error(E);
8552         // It's implementation-defined whether distinct literals will have
8553         // distinct addresses. In clang, the result of such a comparison is
8554         // unspecified, so it is not a constant expression. However, we do know
8555         // that the address of a literal will be non-null.
8556         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8557             LHSValue.Base && RHSValue.Base)
8558           return Error(E);
8559         // We can't tell whether weak symbols will end up pointing to the same
8560         // object.
8561         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
8562           return Error(E);
8563         // We can't compare the address of the start of one object with the
8564         // past-the-end address of another object, per C++ DR1652.
8565         if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8566              isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8567             (RHSValue.Base && RHSValue.Offset.isZero() &&
8568              isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8569           return Error(E);
8570         // We can't tell whether an object is at the same address as another
8571         // zero sized object.
8572         if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8573             (LHSValue.Base && isZeroSized(RHSValue)))
8574           return Error(E);
8575         // Pointers with different bases cannot represent the same object.
8576         // (Note that clang defaults to -fmerge-all-constants, which can
8577         // lead to inconsistent results for comparisons involving the address
8578         // of a constant; this generally doesn't matter in practice.)
8579         return Success(E->getOpcode() == BO_NE, E);
8580       }
8581 
8582       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8583       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8584 
8585       SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8586       SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8587 
8588       if (E->getOpcode() == BO_Sub) {
8589         // C++11 [expr.add]p6:
8590         //   Unless both pointers point to elements of the same array object, or
8591         //   one past the last element of the array object, the behavior is
8592         //   undefined.
8593         if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8594             !AreElementsOfSameArray(getType(LHSValue.Base),
8595                                     LHSDesignator, RHSDesignator))
8596           CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8597 
8598         QualType Type = E->getLHS()->getType();
8599         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
8600 
8601         CharUnits ElementSize;
8602         if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
8603           return false;
8604 
8605         // As an extension, a type may have zero size (empty struct or union in
8606         // C, array of zero length). Pointer subtraction in such cases has
8607         // undefined behavior, so is not constant.
8608         if (ElementSize.isZero()) {
8609           Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
8610             << ElementType;
8611           return false;
8612         }
8613 
8614         // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8615         // and produce incorrect results when it overflows. Such behavior
8616         // appears to be non-conforming, but is common, so perhaps we should
8617         // assume the standard intended for such cases to be undefined behavior
8618         // and check for them.
8619 
8620         // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8621         // overflow in the final conversion to ptrdiff_t.
8622         APSInt LHS(
8623           llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8624         APSInt RHS(
8625           llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8626         APSInt ElemSize(
8627           llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8628         APSInt TrueResult = (LHS - RHS) / ElemSize;
8629         APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8630 
8631         if (Result.extend(65) != TrueResult &&
8632             !HandleOverflow(Info, E, TrueResult, E->getType()))
8633           return false;
8634         return Success(Result, E);
8635       }
8636 
8637       // C++11 [expr.rel]p3:
8638       //   Pointers to void (after pointer conversions) can be compared, with a
8639       //   result defined as follows: If both pointers represent the same
8640       //   address or are both the null pointer value, the result is true if the
8641       //   operator is <= or >= and false otherwise; otherwise the result is
8642       //   unspecified.
8643       // We interpret this as applying to pointers to *cv* void.
8644       if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
8645           E->isRelationalOp())
8646         CCEDiag(E, diag::note_constexpr_void_comparison);
8647 
8648       // C++11 [expr.rel]p2:
8649       // - If two pointers point to non-static data members of the same object,
8650       //   or to subobjects or array elements fo such members, recursively, the
8651       //   pointer to the later declared member compares greater provided the
8652       //   two members have the same access control and provided their class is
8653       //   not a union.
8654       //   [...]
8655       // - Otherwise pointer comparisons are unspecified.
8656       if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8657           E->isRelationalOp()) {
8658         bool WasArrayIndex;
8659         unsigned Mismatch =
8660           FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8661                                  RHSDesignator, WasArrayIndex);
8662         // At the point where the designators diverge, the comparison has a
8663         // specified value if:
8664         //  - we are comparing array indices
8665         //  - we are comparing fields of a union, or fields with the same access
8666         // Otherwise, the result is unspecified and thus the comparison is not a
8667         // constant expression.
8668         if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8669             Mismatch < RHSDesignator.Entries.size()) {
8670           const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8671           const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8672           if (!LF && !RF)
8673             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8674           else if (!LF)
8675             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8676               << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8677               << RF->getParent() << RF;
8678           else if (!RF)
8679             CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8680               << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8681               << LF->getParent() << LF;
8682           else if (!LF->getParent()->isUnion() &&
8683                    LF->getAccess() != RF->getAccess())
8684             CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8685               << LF << LF->getAccess() << RF << RF->getAccess()
8686               << LF->getParent();
8687         }
8688       }
8689 
8690       // The comparison here must be unsigned, and performed with the same
8691       // width as the pointer.
8692       unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8693       uint64_t CompareLHS = LHSOffset.getQuantity();
8694       uint64_t CompareRHS = RHSOffset.getQuantity();
8695       assert(PtrSize <= 64 && "Unexpected pointer width");
8696       uint64_t Mask = ~0ULL >> (64 - PtrSize);
8697       CompareLHS &= Mask;
8698       CompareRHS &= Mask;
8699 
8700       // If there is a base and this is a relational operator, we can only
8701       // compare pointers within the object in question; otherwise, the result
8702       // depends on where the object is located in memory.
8703       if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8704         QualType BaseTy = getType(LHSValue.Base);
8705         if (BaseTy->isIncompleteType())
8706           return Error(E);
8707         CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8708         uint64_t OffsetLimit = Size.getQuantity();
8709         if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8710           return Error(E);
8711       }
8712 
8713       switch (E->getOpcode()) {
8714       default: llvm_unreachable("missing comparison operator");
8715       case BO_LT: return Success(CompareLHS < CompareRHS, E);
8716       case BO_GT: return Success(CompareLHS > CompareRHS, E);
8717       case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8718       case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8719       case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8720       case BO_NE: return Success(CompareLHS != CompareRHS, E);
8721       }
8722     }
8723   }
8724 
8725   if (LHSTy->isMemberPointerType()) {
8726     assert(E->isEqualityOp() && "unexpected member pointer operation");
8727     assert(RHSTy->isMemberPointerType() && "invalid comparison");
8728 
8729     MemberPtr LHSValue, RHSValue;
8730 
8731     bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
8732     if (!LHSOK && !Info.noteFailure())
8733       return false;
8734 
8735     if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8736       return false;
8737 
8738     // C++11 [expr.eq]p2:
8739     //   If both operands are null, they compare equal. Otherwise if only one is
8740     //   null, they compare unequal.
8741     if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8742       bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8743       return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8744     }
8745 
8746     //   Otherwise if either is a pointer to a virtual member function, the
8747     //   result is unspecified.
8748     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8749       if (MD->isVirtual())
8750         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8751     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8752       if (MD->isVirtual())
8753         CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8754 
8755     //   Otherwise they compare equal if and only if they would refer to the
8756     //   same member of the same most derived object or the same subobject if
8757     //   they were dereferenced with a hypothetical object of the associated
8758     //   class type.
8759     bool Equal = LHSValue == RHSValue;
8760     return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8761   }
8762 
8763   if (LHSTy->isNullPtrType()) {
8764     assert(E->isComparisonOp() && "unexpected nullptr operation");
8765     assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8766     // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8767     // are compared, the result is true of the operator is <=, >= or ==, and
8768     // false otherwise.
8769     BinaryOperator::Opcode Opcode = E->getOpcode();
8770     return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8771   }
8772 
8773   assert((!LHSTy->isIntegralOrEnumerationType() ||
8774           !RHSTy->isIntegralOrEnumerationType()) &&
8775          "DataRecursiveIntBinOpEvaluator should have handled integral types");
8776   // We can't continue from here for non-integral types.
8777   return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8778 }
8779 
8780 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8781 /// a result as the expression's type.
8782 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8783                                     const UnaryExprOrTypeTraitExpr *E) {
8784   switch(E->getKind()) {
8785   case UETT_AlignOf: {
8786     if (E->isArgumentType())
8787       return Success(GetAlignOfType(Info, E->getArgumentType()), E);
8788     else
8789       return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
8790   }
8791 
8792   case UETT_VecStep: {
8793     QualType Ty = E->getTypeOfArgument();
8794 
8795     if (Ty->isVectorType()) {
8796       unsigned n = Ty->castAs<VectorType>()->getNumElements();
8797 
8798       // The vec_step built-in functions that take a 3-component
8799       // vector return 4. (OpenCL 1.1 spec 6.11.12)
8800       if (n == 3)
8801         n = 4;
8802 
8803       return Success(n, E);
8804     } else
8805       return Success(1, E);
8806   }
8807 
8808   case UETT_SizeOf: {
8809     QualType SrcTy = E->getTypeOfArgument();
8810     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8811     //   the result is the size of the referenced type."
8812     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8813       SrcTy = Ref->getPointeeType();
8814 
8815     CharUnits Sizeof;
8816     if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
8817       return false;
8818     return Success(Sizeof, E);
8819   }
8820   case UETT_OpenMPRequiredSimdAlign:
8821     assert(E->isArgumentType());
8822     return Success(
8823         Info.Ctx.toCharUnitsFromBits(
8824                     Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8825             .getQuantity(),
8826         E);
8827   }
8828 
8829   llvm_unreachable("unknown expr/type trait");
8830 }
8831 
8832 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
8833   CharUnits Result;
8834   unsigned n = OOE->getNumComponents();
8835   if (n == 0)
8836     return Error(OOE);
8837   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
8838   for (unsigned i = 0; i != n; ++i) {
8839     OffsetOfNode ON = OOE->getComponent(i);
8840     switch (ON.getKind()) {
8841     case OffsetOfNode::Array: {
8842       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
8843       APSInt IdxResult;
8844       if (!EvaluateInteger(Idx, IdxResult, Info))
8845         return false;
8846       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8847       if (!AT)
8848         return Error(OOE);
8849       CurrentType = AT->getElementType();
8850       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8851       Result += IdxResult.getSExtValue() * ElementSize;
8852       break;
8853     }
8854 
8855     case OffsetOfNode::Field: {
8856       FieldDecl *MemberDecl = ON.getField();
8857       const RecordType *RT = CurrentType->getAs<RecordType>();
8858       if (!RT)
8859         return Error(OOE);
8860       RecordDecl *RD = RT->getDecl();
8861       if (RD->isInvalidDecl()) return false;
8862       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8863       unsigned i = MemberDecl->getFieldIndex();
8864       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
8865       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
8866       CurrentType = MemberDecl->getType().getNonReferenceType();
8867       break;
8868     }
8869 
8870     case OffsetOfNode::Identifier:
8871       llvm_unreachable("dependent __builtin_offsetof");
8872 
8873     case OffsetOfNode::Base: {
8874       CXXBaseSpecifier *BaseSpec = ON.getBase();
8875       if (BaseSpec->isVirtual())
8876         return Error(OOE);
8877 
8878       // Find the layout of the class whose base we are looking into.
8879       const RecordType *RT = CurrentType->getAs<RecordType>();
8880       if (!RT)
8881         return Error(OOE);
8882       RecordDecl *RD = RT->getDecl();
8883       if (RD->isInvalidDecl()) return false;
8884       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8885 
8886       // Find the base class itself.
8887       CurrentType = BaseSpec->getType();
8888       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8889       if (!BaseRT)
8890         return Error(OOE);
8891 
8892       // Add the offset to the base.
8893       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
8894       break;
8895     }
8896     }
8897   }
8898   return Success(Result, OOE);
8899 }
8900 
8901 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8902   switch (E->getOpcode()) {
8903   default:
8904     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8905     // See C99 6.6p3.
8906     return Error(E);
8907   case UO_Extension:
8908     // FIXME: Should extension allow i-c-e extension expressions in its scope?
8909     // If so, we could clear the diagnostic ID.
8910     return Visit(E->getSubExpr());
8911   case UO_Plus:
8912     // The result is just the value.
8913     return Visit(E->getSubExpr());
8914   case UO_Minus: {
8915     if (!Visit(E->getSubExpr()))
8916       return false;
8917     if (!Result.isInt()) return Error(E);
8918     const APSInt &Value = Result.getInt();
8919     if (Value.isSigned() && Value.isMinSignedValue() && E->canOverflow() &&
8920         !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8921                         E->getType()))
8922       return false;
8923     return Success(-Value, E);
8924   }
8925   case UO_Not: {
8926     if (!Visit(E->getSubExpr()))
8927       return false;
8928     if (!Result.isInt()) return Error(E);
8929     return Success(~Result.getInt(), E);
8930   }
8931   case UO_LNot: {
8932     bool bres;
8933     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
8934       return false;
8935     return Success(!bres, E);
8936   }
8937   }
8938 }
8939 
8940 /// HandleCast - This is used to evaluate implicit or explicit casts where the
8941 /// result type is integer.
8942 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8943   const Expr *SubExpr = E->getSubExpr();
8944   QualType DestType = E->getType();
8945   QualType SrcType = SubExpr->getType();
8946 
8947   switch (E->getCastKind()) {
8948   case CK_BaseToDerived:
8949   case CK_DerivedToBase:
8950   case CK_UncheckedDerivedToBase:
8951   case CK_Dynamic:
8952   case CK_ToUnion:
8953   case CK_ArrayToPointerDecay:
8954   case CK_FunctionToPointerDecay:
8955   case CK_NullToPointer:
8956   case CK_NullToMemberPointer:
8957   case CK_BaseToDerivedMemberPointer:
8958   case CK_DerivedToBaseMemberPointer:
8959   case CK_ReinterpretMemberPointer:
8960   case CK_ConstructorConversion:
8961   case CK_IntegralToPointer:
8962   case CK_ToVoid:
8963   case CK_VectorSplat:
8964   case CK_IntegralToFloating:
8965   case CK_FloatingCast:
8966   case CK_CPointerToObjCPointerCast:
8967   case CK_BlockPointerToObjCPointerCast:
8968   case CK_AnyPointerToBlockPointerCast:
8969   case CK_ObjCObjectLValueCast:
8970   case CK_FloatingRealToComplex:
8971   case CK_FloatingComplexToReal:
8972   case CK_FloatingComplexCast:
8973   case CK_FloatingComplexToIntegralComplex:
8974   case CK_IntegralRealToComplex:
8975   case CK_IntegralComplexCast:
8976   case CK_IntegralComplexToFloatingComplex:
8977   case CK_BuiltinFnToFnPtr:
8978   case CK_ZeroToOCLEvent:
8979   case CK_ZeroToOCLQueue:
8980   case CK_NonAtomicToAtomic:
8981   case CK_AddressSpaceConversion:
8982   case CK_IntToOCLSampler:
8983     llvm_unreachable("invalid cast kind for integral value");
8984 
8985   case CK_BitCast:
8986   case CK_Dependent:
8987   case CK_LValueBitCast:
8988   case CK_ARCProduceObject:
8989   case CK_ARCConsumeObject:
8990   case CK_ARCReclaimReturnedObject:
8991   case CK_ARCExtendBlockObject:
8992   case CK_CopyAndAutoreleaseBlockObject:
8993     return Error(E);
8994 
8995   case CK_UserDefinedConversion:
8996   case CK_LValueToRValue:
8997   case CK_AtomicToNonAtomic:
8998   case CK_NoOp:
8999     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9000 
9001   case CK_MemberPointerToBoolean:
9002   case CK_PointerToBoolean:
9003   case CK_IntegralToBoolean:
9004   case CK_FloatingToBoolean:
9005   case CK_BooleanToSignedIntegral:
9006   case CK_FloatingComplexToBoolean:
9007   case CK_IntegralComplexToBoolean: {
9008     bool BoolResult;
9009     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
9010       return false;
9011     uint64_t IntResult = BoolResult;
9012     if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
9013       IntResult = (uint64_t)-1;
9014     return Success(IntResult, E);
9015   }
9016 
9017   case CK_IntegralCast: {
9018     if (!Visit(SubExpr))
9019       return false;
9020 
9021     if (!Result.isInt()) {
9022       // Allow casts of address-of-label differences if they are no-ops
9023       // or narrowing.  (The narrowing case isn't actually guaranteed to
9024       // be constant-evaluatable except in some narrow cases which are hard
9025       // to detect here.  We let it through on the assumption the user knows
9026       // what they are doing.)
9027       if (Result.isAddrLabelDiff())
9028         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
9029       // Only allow casts of lvalues if they are lossless.
9030       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
9031     }
9032 
9033     return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
9034                                       Result.getInt()), E);
9035   }
9036 
9037   case CK_PointerToIntegral: {
9038     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
9039 
9040     LValue LV;
9041     if (!EvaluatePointer(SubExpr, LV, Info))
9042       return false;
9043 
9044     if (LV.getLValueBase()) {
9045       // Only allow based lvalue casts if they are lossless.
9046       // FIXME: Allow a larger integer size than the pointer size, and allow
9047       // narrowing back down to pointer width in subsequent integral casts.
9048       // FIXME: Check integer type's active bits, not its type size.
9049       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
9050         return Error(E);
9051 
9052       LV.Designator.setInvalid();
9053       LV.moveInto(Result);
9054       return true;
9055     }
9056 
9057     uint64_t V;
9058     if (LV.isNullPointer())
9059       V = Info.Ctx.getTargetNullPointerValue(SrcType);
9060     else
9061       V = LV.getLValueOffset().getQuantity();
9062 
9063     APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
9064     return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
9065   }
9066 
9067   case CK_IntegralComplexToReal: {
9068     ComplexValue C;
9069     if (!EvaluateComplex(SubExpr, C, Info))
9070       return false;
9071     return Success(C.getComplexIntReal(), E);
9072   }
9073 
9074   case CK_FloatingToIntegral: {
9075     APFloat F(0.0);
9076     if (!EvaluateFloat(SubExpr, F, Info))
9077       return false;
9078 
9079     APSInt Value;
9080     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9081       return false;
9082     return Success(Value, E);
9083   }
9084   }
9085 
9086   llvm_unreachable("unknown cast resulting in integral value");
9087 }
9088 
9089 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9090   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9091     ComplexValue LV;
9092     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9093       return false;
9094     if (!LV.isComplexInt())
9095       return Error(E);
9096     return Success(LV.getComplexIntReal(), E);
9097   }
9098 
9099   return Visit(E->getSubExpr());
9100 }
9101 
9102 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9103   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
9104     ComplexValue LV;
9105     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9106       return false;
9107     if (!LV.isComplexInt())
9108       return Error(E);
9109     return Success(LV.getComplexIntImag(), E);
9110   }
9111 
9112   VisitIgnoredValue(E->getSubExpr());
9113   return Success(0, E);
9114 }
9115 
9116 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9117   return Success(E->getPackLength(), E);
9118 }
9119 
9120 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9121   return Success(E->getValue(), E);
9122 }
9123 
9124 //===----------------------------------------------------------------------===//
9125 // Float Evaluation
9126 //===----------------------------------------------------------------------===//
9127 
9128 namespace {
9129 class FloatExprEvaluator
9130   : public ExprEvaluatorBase<FloatExprEvaluator> {
9131   APFloat &Result;
9132 public:
9133   FloatExprEvaluator(EvalInfo &info, APFloat &result)
9134     : ExprEvaluatorBaseTy(info), Result(result) {}
9135 
9136   bool Success(const APValue &V, const Expr *e) {
9137     Result = V.getFloat();
9138     return true;
9139   }
9140 
9141   bool ZeroInitialization(const Expr *E) {
9142     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9143     return true;
9144   }
9145 
9146   bool VisitCallExpr(const CallExpr *E);
9147 
9148   bool VisitUnaryOperator(const UnaryOperator *E);
9149   bool VisitBinaryOperator(const BinaryOperator *E);
9150   bool VisitFloatingLiteral(const FloatingLiteral *E);
9151   bool VisitCastExpr(const CastExpr *E);
9152 
9153   bool VisitUnaryReal(const UnaryOperator *E);
9154   bool VisitUnaryImag(const UnaryOperator *E);
9155 
9156   // FIXME: Missing: array subscript of vector, member of vector
9157 };
9158 } // end anonymous namespace
9159 
9160 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
9161   assert(E->isRValue() && E->getType()->isRealFloatingType());
9162   return FloatExprEvaluator(Info, Result).Visit(E);
9163 }
9164 
9165 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
9166                                   QualType ResultTy,
9167                                   const Expr *Arg,
9168                                   bool SNaN,
9169                                   llvm::APFloat &Result) {
9170   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9171   if (!S) return false;
9172 
9173   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9174 
9175   llvm::APInt fill;
9176 
9177   // Treat empty strings as if they were zero.
9178   if (S->getString().empty())
9179     fill = llvm::APInt(32, 0);
9180   else if (S->getString().getAsInteger(0, fill))
9181     return false;
9182 
9183   if (Context.getTargetInfo().isNan2008()) {
9184     if (SNaN)
9185       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9186     else
9187       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9188   } else {
9189     // Prior to IEEE 754-2008, architectures were allowed to choose whether
9190     // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9191     // a different encoding to what became a standard in 2008, and for pre-
9192     // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9193     // sNaN. This is now known as "legacy NaN" encoding.
9194     if (SNaN)
9195       Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9196     else
9197       Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9198   }
9199 
9200   return true;
9201 }
9202 
9203 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
9204   switch (E->getBuiltinCallee()) {
9205   default:
9206     return ExprEvaluatorBaseTy::VisitCallExpr(E);
9207 
9208   case Builtin::BI__builtin_huge_val:
9209   case Builtin::BI__builtin_huge_valf:
9210   case Builtin::BI__builtin_huge_vall:
9211   case Builtin::BI__builtin_huge_valf128:
9212   case Builtin::BI__builtin_inf:
9213   case Builtin::BI__builtin_inff:
9214   case Builtin::BI__builtin_infl:
9215   case Builtin::BI__builtin_inff128: {
9216     const llvm::fltSemantics &Sem =
9217       Info.Ctx.getFloatTypeSemantics(E->getType());
9218     Result = llvm::APFloat::getInf(Sem);
9219     return true;
9220   }
9221 
9222   case Builtin::BI__builtin_nans:
9223   case Builtin::BI__builtin_nansf:
9224   case Builtin::BI__builtin_nansl:
9225   case Builtin::BI__builtin_nansf128:
9226     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9227                                true, Result))
9228       return Error(E);
9229     return true;
9230 
9231   case Builtin::BI__builtin_nan:
9232   case Builtin::BI__builtin_nanf:
9233   case Builtin::BI__builtin_nanl:
9234   case Builtin::BI__builtin_nanf128:
9235     // If this is __builtin_nan() turn this into a nan, otherwise we
9236     // can't constant fold it.
9237     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9238                                false, Result))
9239       return Error(E);
9240     return true;
9241 
9242   case Builtin::BI__builtin_fabs:
9243   case Builtin::BI__builtin_fabsf:
9244   case Builtin::BI__builtin_fabsl:
9245   case Builtin::BI__builtin_fabsf128:
9246     if (!EvaluateFloat(E->getArg(0), Result, Info))
9247       return false;
9248 
9249     if (Result.isNegative())
9250       Result.changeSign();
9251     return true;
9252 
9253   // FIXME: Builtin::BI__builtin_powi
9254   // FIXME: Builtin::BI__builtin_powif
9255   // FIXME: Builtin::BI__builtin_powil
9256 
9257   case Builtin::BI__builtin_copysign:
9258   case Builtin::BI__builtin_copysignf:
9259   case Builtin::BI__builtin_copysignl:
9260   case Builtin::BI__builtin_copysignf128: {
9261     APFloat RHS(0.);
9262     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9263         !EvaluateFloat(E->getArg(1), RHS, Info))
9264       return false;
9265     Result.copySign(RHS);
9266     return true;
9267   }
9268   }
9269 }
9270 
9271 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9272   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9273     ComplexValue CV;
9274     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9275       return false;
9276     Result = CV.FloatReal;
9277     return true;
9278   }
9279 
9280   return Visit(E->getSubExpr());
9281 }
9282 
9283 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
9284   if (E->getSubExpr()->getType()->isAnyComplexType()) {
9285     ComplexValue CV;
9286     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9287       return false;
9288     Result = CV.FloatImag;
9289     return true;
9290   }
9291 
9292   VisitIgnoredValue(E->getSubExpr());
9293   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9294   Result = llvm::APFloat::getZero(Sem);
9295   return true;
9296 }
9297 
9298 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9299   switch (E->getOpcode()) {
9300   default: return Error(E);
9301   case UO_Plus:
9302     return EvaluateFloat(E->getSubExpr(), Result, Info);
9303   case UO_Minus:
9304     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9305       return false;
9306     Result.changeSign();
9307     return true;
9308   }
9309 }
9310 
9311 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9312   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9313     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9314 
9315   APFloat RHS(0.0);
9316   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
9317   if (!LHSOK && !Info.noteFailure())
9318     return false;
9319   return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9320          handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
9321 }
9322 
9323 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9324   Result = E->getValue();
9325   return true;
9326 }
9327 
9328 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9329   const Expr* SubExpr = E->getSubExpr();
9330 
9331   switch (E->getCastKind()) {
9332   default:
9333     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9334 
9335   case CK_IntegralToFloating: {
9336     APSInt IntResult;
9337     return EvaluateInteger(SubExpr, IntResult, Info) &&
9338            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9339                                 E->getType(), Result);
9340   }
9341 
9342   case CK_FloatingCast: {
9343     if (!Visit(SubExpr))
9344       return false;
9345     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9346                                   Result);
9347   }
9348 
9349   case CK_FloatingComplexToReal: {
9350     ComplexValue V;
9351     if (!EvaluateComplex(SubExpr, V, Info))
9352       return false;
9353     Result = V.getComplexFloatReal();
9354     return true;
9355   }
9356   }
9357 }
9358 
9359 //===----------------------------------------------------------------------===//
9360 // Complex Evaluation (for float and integer)
9361 //===----------------------------------------------------------------------===//
9362 
9363 namespace {
9364 class ComplexExprEvaluator
9365   : public ExprEvaluatorBase<ComplexExprEvaluator> {
9366   ComplexValue &Result;
9367 
9368 public:
9369   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
9370     : ExprEvaluatorBaseTy(info), Result(Result) {}
9371 
9372   bool Success(const APValue &V, const Expr *e) {
9373     Result.setFrom(V);
9374     return true;
9375   }
9376 
9377   bool ZeroInitialization(const Expr *E);
9378 
9379   //===--------------------------------------------------------------------===//
9380   //                            Visitor Methods
9381   //===--------------------------------------------------------------------===//
9382 
9383   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
9384   bool VisitCastExpr(const CastExpr *E);
9385   bool VisitBinaryOperator(const BinaryOperator *E);
9386   bool VisitUnaryOperator(const UnaryOperator *E);
9387   bool VisitInitListExpr(const InitListExpr *E);
9388 };
9389 } // end anonymous namespace
9390 
9391 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9392                             EvalInfo &Info) {
9393   assert(E->isRValue() && E->getType()->isAnyComplexType());
9394   return ComplexExprEvaluator(Info, Result).Visit(E);
9395 }
9396 
9397 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
9398   QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
9399   if (ElemTy->isRealFloatingType()) {
9400     Result.makeComplexFloat();
9401     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9402     Result.FloatReal = Zero;
9403     Result.FloatImag = Zero;
9404   } else {
9405     Result.makeComplexInt();
9406     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9407     Result.IntReal = Zero;
9408     Result.IntImag = Zero;
9409   }
9410   return true;
9411 }
9412 
9413 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9414   const Expr* SubExpr = E->getSubExpr();
9415 
9416   if (SubExpr->getType()->isRealFloatingType()) {
9417     Result.makeComplexFloat();
9418     APFloat &Imag = Result.FloatImag;
9419     if (!EvaluateFloat(SubExpr, Imag, Info))
9420       return false;
9421 
9422     Result.FloatReal = APFloat(Imag.getSemantics());
9423     return true;
9424   } else {
9425     assert(SubExpr->getType()->isIntegerType() &&
9426            "Unexpected imaginary literal.");
9427 
9428     Result.makeComplexInt();
9429     APSInt &Imag = Result.IntImag;
9430     if (!EvaluateInteger(SubExpr, Imag, Info))
9431       return false;
9432 
9433     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9434     return true;
9435   }
9436 }
9437 
9438 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
9439 
9440   switch (E->getCastKind()) {
9441   case CK_BitCast:
9442   case CK_BaseToDerived:
9443   case CK_DerivedToBase:
9444   case CK_UncheckedDerivedToBase:
9445   case CK_Dynamic:
9446   case CK_ToUnion:
9447   case CK_ArrayToPointerDecay:
9448   case CK_FunctionToPointerDecay:
9449   case CK_NullToPointer:
9450   case CK_NullToMemberPointer:
9451   case CK_BaseToDerivedMemberPointer:
9452   case CK_DerivedToBaseMemberPointer:
9453   case CK_MemberPointerToBoolean:
9454   case CK_ReinterpretMemberPointer:
9455   case CK_ConstructorConversion:
9456   case CK_IntegralToPointer:
9457   case CK_PointerToIntegral:
9458   case CK_PointerToBoolean:
9459   case CK_ToVoid:
9460   case CK_VectorSplat:
9461   case CK_IntegralCast:
9462   case CK_BooleanToSignedIntegral:
9463   case CK_IntegralToBoolean:
9464   case CK_IntegralToFloating:
9465   case CK_FloatingToIntegral:
9466   case CK_FloatingToBoolean:
9467   case CK_FloatingCast:
9468   case CK_CPointerToObjCPointerCast:
9469   case CK_BlockPointerToObjCPointerCast:
9470   case CK_AnyPointerToBlockPointerCast:
9471   case CK_ObjCObjectLValueCast:
9472   case CK_FloatingComplexToReal:
9473   case CK_FloatingComplexToBoolean:
9474   case CK_IntegralComplexToReal:
9475   case CK_IntegralComplexToBoolean:
9476   case CK_ARCProduceObject:
9477   case CK_ARCConsumeObject:
9478   case CK_ARCReclaimReturnedObject:
9479   case CK_ARCExtendBlockObject:
9480   case CK_CopyAndAutoreleaseBlockObject:
9481   case CK_BuiltinFnToFnPtr:
9482   case CK_ZeroToOCLEvent:
9483   case CK_ZeroToOCLQueue:
9484   case CK_NonAtomicToAtomic:
9485   case CK_AddressSpaceConversion:
9486   case CK_IntToOCLSampler:
9487     llvm_unreachable("invalid cast kind for complex value");
9488 
9489   case CK_LValueToRValue:
9490   case CK_AtomicToNonAtomic:
9491   case CK_NoOp:
9492     return ExprEvaluatorBaseTy::VisitCastExpr(E);
9493 
9494   case CK_Dependent:
9495   case CK_LValueBitCast:
9496   case CK_UserDefinedConversion:
9497     return Error(E);
9498 
9499   case CK_FloatingRealToComplex: {
9500     APFloat &Real = Result.FloatReal;
9501     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
9502       return false;
9503 
9504     Result.makeComplexFloat();
9505     Result.FloatImag = APFloat(Real.getSemantics());
9506     return true;
9507   }
9508 
9509   case CK_FloatingComplexCast: {
9510     if (!Visit(E->getSubExpr()))
9511       return false;
9512 
9513     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9514     QualType From
9515       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9516 
9517     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9518            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
9519   }
9520 
9521   case CK_FloatingComplexToIntegralComplex: {
9522     if (!Visit(E->getSubExpr()))
9523       return false;
9524 
9525     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9526     QualType From
9527       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9528     Result.makeComplexInt();
9529     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9530                                 To, Result.IntReal) &&
9531            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9532                                 To, Result.IntImag);
9533   }
9534 
9535   case CK_IntegralRealToComplex: {
9536     APSInt &Real = Result.IntReal;
9537     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9538       return false;
9539 
9540     Result.makeComplexInt();
9541     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9542     return true;
9543   }
9544 
9545   case CK_IntegralComplexCast: {
9546     if (!Visit(E->getSubExpr()))
9547       return false;
9548 
9549     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9550     QualType From
9551       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9552 
9553     Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9554     Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
9555     return true;
9556   }
9557 
9558   case CK_IntegralComplexToFloatingComplex: {
9559     if (!Visit(E->getSubExpr()))
9560       return false;
9561 
9562     QualType To = E->getType()->castAs<ComplexType>()->getElementType();
9563     QualType From
9564       = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
9565     Result.makeComplexFloat();
9566     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9567                                 To, Result.FloatReal) &&
9568            HandleIntToFloatCast(Info, E, From, Result.IntImag,
9569                                 To, Result.FloatImag);
9570   }
9571   }
9572 
9573   llvm_unreachable("unknown cast resulting in complex value");
9574 }
9575 
9576 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
9577   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9578     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9579 
9580   // Track whether the LHS or RHS is real at the type system level. When this is
9581   // the case we can simplify our evaluation strategy.
9582   bool LHSReal = false, RHSReal = false;
9583 
9584   bool LHSOK;
9585   if (E->getLHS()->getType()->isRealFloatingType()) {
9586     LHSReal = true;
9587     APFloat &Real = Result.FloatReal;
9588     LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9589     if (LHSOK) {
9590       Result.makeComplexFloat();
9591       Result.FloatImag = APFloat(Real.getSemantics());
9592     }
9593   } else {
9594     LHSOK = Visit(E->getLHS());
9595   }
9596   if (!LHSOK && !Info.noteFailure())
9597     return false;
9598 
9599   ComplexValue RHS;
9600   if (E->getRHS()->getType()->isRealFloatingType()) {
9601     RHSReal = true;
9602     APFloat &Real = RHS.FloatReal;
9603     if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9604       return false;
9605     RHS.makeComplexFloat();
9606     RHS.FloatImag = APFloat(Real.getSemantics());
9607   } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
9608     return false;
9609 
9610   assert(!(LHSReal && RHSReal) &&
9611          "Cannot have both operands of a complex operation be real.");
9612   switch (E->getOpcode()) {
9613   default: return Error(E);
9614   case BO_Add:
9615     if (Result.isComplexFloat()) {
9616       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9617                                        APFloat::rmNearestTiesToEven);
9618       if (LHSReal)
9619         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9620       else if (!RHSReal)
9621         Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9622                                          APFloat::rmNearestTiesToEven);
9623     } else {
9624       Result.getComplexIntReal() += RHS.getComplexIntReal();
9625       Result.getComplexIntImag() += RHS.getComplexIntImag();
9626     }
9627     break;
9628   case BO_Sub:
9629     if (Result.isComplexFloat()) {
9630       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9631                                             APFloat::rmNearestTiesToEven);
9632       if (LHSReal) {
9633         Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9634         Result.getComplexFloatImag().changeSign();
9635       } else if (!RHSReal) {
9636         Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9637                                               APFloat::rmNearestTiesToEven);
9638       }
9639     } else {
9640       Result.getComplexIntReal() -= RHS.getComplexIntReal();
9641       Result.getComplexIntImag() -= RHS.getComplexIntImag();
9642     }
9643     break;
9644   case BO_Mul:
9645     if (Result.isComplexFloat()) {
9646       // This is an implementation of complex multiplication according to the
9647       // constraints laid out in C11 Annex G. The implemention uses the
9648       // following naming scheme:
9649       //   (a + ib) * (c + id)
9650       ComplexValue LHS = Result;
9651       APFloat &A = LHS.getComplexFloatReal();
9652       APFloat &B = LHS.getComplexFloatImag();
9653       APFloat &C = RHS.getComplexFloatReal();
9654       APFloat &D = RHS.getComplexFloatImag();
9655       APFloat &ResR = Result.getComplexFloatReal();
9656       APFloat &ResI = Result.getComplexFloatImag();
9657       if (LHSReal) {
9658         assert(!RHSReal && "Cannot have two real operands for a complex op!");
9659         ResR = A * C;
9660         ResI = A * D;
9661       } else if (RHSReal) {
9662         ResR = C * A;
9663         ResI = C * B;
9664       } else {
9665         // In the fully general case, we need to handle NaNs and infinities
9666         // robustly.
9667         APFloat AC = A * C;
9668         APFloat BD = B * D;
9669         APFloat AD = A * D;
9670         APFloat BC = B * C;
9671         ResR = AC - BD;
9672         ResI = AD + BC;
9673         if (ResR.isNaN() && ResI.isNaN()) {
9674           bool Recalc = false;
9675           if (A.isInfinity() || B.isInfinity()) {
9676             A = APFloat::copySign(
9677                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9678             B = APFloat::copySign(
9679                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9680             if (C.isNaN())
9681               C = APFloat::copySign(APFloat(C.getSemantics()), C);
9682             if (D.isNaN())
9683               D = APFloat::copySign(APFloat(D.getSemantics()), D);
9684             Recalc = true;
9685           }
9686           if (C.isInfinity() || D.isInfinity()) {
9687             C = APFloat::copySign(
9688                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9689             D = APFloat::copySign(
9690                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9691             if (A.isNaN())
9692               A = APFloat::copySign(APFloat(A.getSemantics()), A);
9693             if (B.isNaN())
9694               B = APFloat::copySign(APFloat(B.getSemantics()), B);
9695             Recalc = true;
9696           }
9697           if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9698                           AD.isInfinity() || BC.isInfinity())) {
9699             if (A.isNaN())
9700               A = APFloat::copySign(APFloat(A.getSemantics()), A);
9701             if (B.isNaN())
9702               B = APFloat::copySign(APFloat(B.getSemantics()), B);
9703             if (C.isNaN())
9704               C = APFloat::copySign(APFloat(C.getSemantics()), C);
9705             if (D.isNaN())
9706               D = APFloat::copySign(APFloat(D.getSemantics()), D);
9707             Recalc = true;
9708           }
9709           if (Recalc) {
9710             ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9711             ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9712           }
9713         }
9714       }
9715     } else {
9716       ComplexValue LHS = Result;
9717       Result.getComplexIntReal() =
9718         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9719          LHS.getComplexIntImag() * RHS.getComplexIntImag());
9720       Result.getComplexIntImag() =
9721         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9722          LHS.getComplexIntImag() * RHS.getComplexIntReal());
9723     }
9724     break;
9725   case BO_Div:
9726     if (Result.isComplexFloat()) {
9727       // This is an implementation of complex division according to the
9728       // constraints laid out in C11 Annex G. The implemention uses the
9729       // following naming scheme:
9730       //   (a + ib) / (c + id)
9731       ComplexValue LHS = Result;
9732       APFloat &A = LHS.getComplexFloatReal();
9733       APFloat &B = LHS.getComplexFloatImag();
9734       APFloat &C = RHS.getComplexFloatReal();
9735       APFloat &D = RHS.getComplexFloatImag();
9736       APFloat &ResR = Result.getComplexFloatReal();
9737       APFloat &ResI = Result.getComplexFloatImag();
9738       if (RHSReal) {
9739         ResR = A / C;
9740         ResI = B / C;
9741       } else {
9742         if (LHSReal) {
9743           // No real optimizations we can do here, stub out with zero.
9744           B = APFloat::getZero(A.getSemantics());
9745         }
9746         int DenomLogB = 0;
9747         APFloat MaxCD = maxnum(abs(C), abs(D));
9748         if (MaxCD.isFinite()) {
9749           DenomLogB = ilogb(MaxCD);
9750           C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9751           D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
9752         }
9753         APFloat Denom = C * C + D * D;
9754         ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9755                       APFloat::rmNearestTiesToEven);
9756         ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9757                       APFloat::rmNearestTiesToEven);
9758         if (ResR.isNaN() && ResI.isNaN()) {
9759           if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9760             ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9761             ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9762           } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9763                      D.isFinite()) {
9764             A = APFloat::copySign(
9765                 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9766             B = APFloat::copySign(
9767                 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9768             ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9769             ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9770           } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9771             C = APFloat::copySign(
9772                 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9773             D = APFloat::copySign(
9774                 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9775             ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9776             ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9777           }
9778         }
9779       }
9780     } else {
9781       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9782         return Error(E, diag::note_expr_divide_by_zero);
9783 
9784       ComplexValue LHS = Result;
9785       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9786         RHS.getComplexIntImag() * RHS.getComplexIntImag();
9787       Result.getComplexIntReal() =
9788         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9789          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9790       Result.getComplexIntImag() =
9791         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9792          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9793     }
9794     break;
9795   }
9796 
9797   return true;
9798 }
9799 
9800 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9801   // Get the operand value into 'Result'.
9802   if (!Visit(E->getSubExpr()))
9803     return false;
9804 
9805   switch (E->getOpcode()) {
9806   default:
9807     return Error(E);
9808   case UO_Extension:
9809     return true;
9810   case UO_Plus:
9811     // The result is always just the subexpr.
9812     return true;
9813   case UO_Minus:
9814     if (Result.isComplexFloat()) {
9815       Result.getComplexFloatReal().changeSign();
9816       Result.getComplexFloatImag().changeSign();
9817     }
9818     else {
9819       Result.getComplexIntReal() = -Result.getComplexIntReal();
9820       Result.getComplexIntImag() = -Result.getComplexIntImag();
9821     }
9822     return true;
9823   case UO_Not:
9824     if (Result.isComplexFloat())
9825       Result.getComplexFloatImag().changeSign();
9826     else
9827       Result.getComplexIntImag() = -Result.getComplexIntImag();
9828     return true;
9829   }
9830 }
9831 
9832 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9833   if (E->getNumInits() == 2) {
9834     if (E->getType()->isComplexType()) {
9835       Result.makeComplexFloat();
9836       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9837         return false;
9838       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9839         return false;
9840     } else {
9841       Result.makeComplexInt();
9842       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9843         return false;
9844       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9845         return false;
9846     }
9847     return true;
9848   }
9849   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9850 }
9851 
9852 //===----------------------------------------------------------------------===//
9853 // Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9854 // implicit conversion.
9855 //===----------------------------------------------------------------------===//
9856 
9857 namespace {
9858 class AtomicExprEvaluator :
9859     public ExprEvaluatorBase<AtomicExprEvaluator> {
9860   const LValue *This;
9861   APValue &Result;
9862 public:
9863   AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9864       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
9865 
9866   bool Success(const APValue &V, const Expr *E) {
9867     Result = V;
9868     return true;
9869   }
9870 
9871   bool ZeroInitialization(const Expr *E) {
9872     ImplicitValueInitExpr VIE(
9873         E->getType()->castAs<AtomicType>()->getValueType());
9874     // For atomic-qualified class (and array) types in C++, initialize the
9875     // _Atomic-wrapped subobject directly, in-place.
9876     return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9877                 : Evaluate(Result, Info, &VIE);
9878   }
9879 
9880   bool VisitCastExpr(const CastExpr *E) {
9881     switch (E->getCastKind()) {
9882     default:
9883       return ExprEvaluatorBaseTy::VisitCastExpr(E);
9884     case CK_NonAtomicToAtomic:
9885       return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9886                   : Evaluate(Result, Info, E->getSubExpr());
9887     }
9888   }
9889 };
9890 } // end anonymous namespace
9891 
9892 static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9893                            EvalInfo &Info) {
9894   assert(E->isRValue() && E->getType()->isAtomicType());
9895   return AtomicExprEvaluator(Info, This, Result).Visit(E);
9896 }
9897 
9898 //===----------------------------------------------------------------------===//
9899 // Void expression evaluation, primarily for a cast to void on the LHS of a
9900 // comma operator
9901 //===----------------------------------------------------------------------===//
9902 
9903 namespace {
9904 class VoidExprEvaluator
9905   : public ExprEvaluatorBase<VoidExprEvaluator> {
9906 public:
9907   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9908 
9909   bool Success(const APValue &V, const Expr *e) { return true; }
9910 
9911   bool ZeroInitialization(const Expr *E) { return true; }
9912 
9913   bool VisitCastExpr(const CastExpr *E) {
9914     switch (E->getCastKind()) {
9915     default:
9916       return ExprEvaluatorBaseTy::VisitCastExpr(E);
9917     case CK_ToVoid:
9918       VisitIgnoredValue(E->getSubExpr());
9919       return true;
9920     }
9921   }
9922 
9923   bool VisitCallExpr(const CallExpr *E) {
9924     switch (E->getBuiltinCallee()) {
9925     default:
9926       return ExprEvaluatorBaseTy::VisitCallExpr(E);
9927     case Builtin::BI__assume:
9928     case Builtin::BI__builtin_assume:
9929       // The argument is not evaluated!
9930       return true;
9931     }
9932   }
9933 };
9934 } // end anonymous namespace
9935 
9936 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9937   assert(E->isRValue() && E->getType()->isVoidType());
9938   return VoidExprEvaluator(Info).Visit(E);
9939 }
9940 
9941 //===----------------------------------------------------------------------===//
9942 // Top level Expr::EvaluateAsRValue method.
9943 //===----------------------------------------------------------------------===//
9944 
9945 static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
9946   // In C, function designators are not lvalues, but we evaluate them as if they
9947   // are.
9948   QualType T = E->getType();
9949   if (E->isGLValue() || T->isFunctionType()) {
9950     LValue LV;
9951     if (!EvaluateLValue(E, LV, Info))
9952       return false;
9953     LV.moveInto(Result);
9954   } else if (T->isVectorType()) {
9955     if (!EvaluateVector(E, Result, Info))
9956       return false;
9957   } else if (T->isIntegralOrEnumerationType()) {
9958     if (!IntExprEvaluator(Info, Result).Visit(E))
9959       return false;
9960   } else if (T->hasPointerRepresentation()) {
9961     LValue LV;
9962     if (!EvaluatePointer(E, LV, Info))
9963       return false;
9964     LV.moveInto(Result);
9965   } else if (T->isRealFloatingType()) {
9966     llvm::APFloat F(0.0);
9967     if (!EvaluateFloat(E, F, Info))
9968       return false;
9969     Result = APValue(F);
9970   } else if (T->isAnyComplexType()) {
9971     ComplexValue C;
9972     if (!EvaluateComplex(E, C, Info))
9973       return false;
9974     C.moveInto(Result);
9975   } else if (T->isMemberPointerType()) {
9976     MemberPtr P;
9977     if (!EvaluateMemberPointer(E, P, Info))
9978       return false;
9979     P.moveInto(Result);
9980     return true;
9981   } else if (T->isArrayType()) {
9982     LValue LV;
9983     LV.set(E, Info.CurrentCall->Index);
9984     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9985     if (!EvaluateArray(E, LV, Value, Info))
9986       return false;
9987     Result = Value;
9988   } else if (T->isRecordType()) {
9989     LValue LV;
9990     LV.set(E, Info.CurrentCall->Index);
9991     APValue &Value = Info.CurrentCall->createTemporary(E, false);
9992     if (!EvaluateRecord(E, LV, Value, Info))
9993       return false;
9994     Result = Value;
9995   } else if (T->isVoidType()) {
9996     if (!Info.getLangOpts().CPlusPlus11)
9997       Info.CCEDiag(E, diag::note_constexpr_nonliteral)
9998         << E->getType();
9999     if (!EvaluateVoid(E, Info))
10000       return false;
10001   } else if (T->isAtomicType()) {
10002     QualType Unqual = T.getAtomicUnqualifiedType();
10003     if (Unqual->isArrayType() || Unqual->isRecordType()) {
10004       LValue LV;
10005       LV.set(E, Info.CurrentCall->Index);
10006       APValue &Value = Info.CurrentCall->createTemporary(E, false);
10007       if (!EvaluateAtomic(E, &LV, Value, Info))
10008         return false;
10009     } else {
10010       if (!EvaluateAtomic(E, nullptr, Result, Info))
10011         return false;
10012     }
10013   } else if (Info.getLangOpts().CPlusPlus11) {
10014     Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
10015     return false;
10016   } else {
10017     Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
10018     return false;
10019   }
10020 
10021   return true;
10022 }
10023 
10024 /// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
10025 /// cases, the in-place evaluation is essential, since later initializers for
10026 /// an object can indirectly refer to subobjects which were initialized earlier.
10027 static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
10028                             const Expr *E, bool AllowNonLiteralTypes) {
10029   assert(!E->isValueDependent());
10030 
10031   if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
10032     return false;
10033 
10034   if (E->isRValue()) {
10035     // Evaluate arrays and record types in-place, so that later initializers can
10036     // refer to earlier-initialized members of the object.
10037     QualType T = E->getType();
10038     if (T->isArrayType())
10039       return EvaluateArray(E, This, Result, Info);
10040     else if (T->isRecordType())
10041       return EvaluateRecord(E, This, Result, Info);
10042     else if (T->isAtomicType()) {
10043       QualType Unqual = T.getAtomicUnqualifiedType();
10044       if (Unqual->isArrayType() || Unqual->isRecordType())
10045         return EvaluateAtomic(E, &This, Result, Info);
10046     }
10047   }
10048 
10049   // For any other type, in-place evaluation is unimportant.
10050   return Evaluate(Result, Info, E);
10051 }
10052 
10053 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10054 /// lvalue-to-rvalue cast if it is an lvalue.
10055 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
10056   if (E->getType().isNull())
10057     return false;
10058 
10059   if (!CheckLiteralType(Info, E))
10060     return false;
10061 
10062   if (!::Evaluate(Result, Info, E))
10063     return false;
10064 
10065   if (E->isGLValue()) {
10066     LValue LV;
10067     LV.setFrom(Info.Ctx, Result);
10068     if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
10069       return false;
10070   }
10071 
10072   // Check this core constant expression is a constant expression.
10073   return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
10074 }
10075 
10076 static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
10077                                  const ASTContext &Ctx, bool &IsConst) {
10078   // Fast-path evaluations of integer literals, since we sometimes see files
10079   // containing vast quantities of these.
10080   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10081     Result.Val = APValue(APSInt(L->getValue(),
10082                                 L->getType()->isUnsignedIntegerType()));
10083     IsConst = true;
10084     return true;
10085   }
10086 
10087   // This case should be rare, but we need to check it before we check on
10088   // the type below.
10089   if (Exp->getType().isNull()) {
10090     IsConst = false;
10091     return true;
10092   }
10093 
10094   // FIXME: Evaluating values of large array and record types can cause
10095   // performance problems. Only do so in C++11 for now.
10096   if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10097                           Exp->getType()->isRecordType()) &&
10098       !Ctx.getLangOpts().CPlusPlus11) {
10099     IsConst = false;
10100     return true;
10101   }
10102   return false;
10103 }
10104 
10105 
10106 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
10107 /// any crazy technique (that has nothing to do with language standards) that
10108 /// we want to.  If this function returns true, it returns the folded constant
10109 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10110 /// will be applied to the result.
10111 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
10112   bool IsConst;
10113   if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
10114     return IsConst;
10115 
10116   EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
10117   return ::EvaluateAsRValue(Info, this, Result.Val);
10118 }
10119 
10120 bool Expr::EvaluateAsBooleanCondition(bool &Result,
10121                                       const ASTContext &Ctx) const {
10122   EvalResult Scratch;
10123   return EvaluateAsRValue(Scratch, Ctx) &&
10124          HandleConversionToBool(Scratch.Val, Result);
10125 }
10126 
10127 static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10128                                       Expr::SideEffectsKind SEK) {
10129   return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10130          (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10131 }
10132 
10133 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10134                          SideEffectsKind AllowSideEffects) const {
10135   if (!getType()->isIntegralOrEnumerationType())
10136     return false;
10137 
10138   EvalResult ExprResult;
10139   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
10140       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10141     return false;
10142 
10143   Result = ExprResult.Val.getInt();
10144   return true;
10145 }
10146 
10147 bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10148                            SideEffectsKind AllowSideEffects) const {
10149   if (!getType()->isRealFloatingType())
10150     return false;
10151 
10152   EvalResult ExprResult;
10153   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10154       hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10155     return false;
10156 
10157   Result = ExprResult.Val.getFloat();
10158   return true;
10159 }
10160 
10161 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
10162   EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
10163 
10164   LValue LV;
10165   if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10166       !CheckLValueConstantExpression(Info, getExprLoc(),
10167                                      Ctx.getLValueReferenceType(getType()), LV))
10168     return false;
10169 
10170   LV.moveInto(Result.Val);
10171   return true;
10172 }
10173 
10174 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10175                                  const VarDecl *VD,
10176                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
10177   // FIXME: Evaluating initializers for large array and record types can cause
10178   // performance problems. Only do so in C++11 for now.
10179   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
10180       !Ctx.getLangOpts().CPlusPlus11)
10181     return false;
10182 
10183   Expr::EvalStatus EStatus;
10184   EStatus.Diag = &Notes;
10185 
10186   EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10187                                       ? EvalInfo::EM_ConstantExpression
10188                                       : EvalInfo::EM_ConstantFold);
10189   InitInfo.setEvaluatingDecl(VD, Value);
10190 
10191   LValue LVal;
10192   LVal.set(VD);
10193 
10194   // C++11 [basic.start.init]p2:
10195   //  Variables with static storage duration or thread storage duration shall be
10196   //  zero-initialized before any other initialization takes place.
10197   // This behavior is not present in C.
10198   if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
10199       !VD->getType()->isReferenceType()) {
10200     ImplicitValueInitExpr VIE(VD->getType());
10201     if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
10202                          /*AllowNonLiteralTypes=*/true))
10203       return false;
10204   }
10205 
10206   if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10207                        /*AllowNonLiteralTypes=*/true) ||
10208       EStatus.HasSideEffects)
10209     return false;
10210 
10211   return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10212                                  Value);
10213 }
10214 
10215 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10216 /// constant folded, but discard the result.
10217 bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
10218   EvalResult Result;
10219   return EvaluateAsRValue(Result, Ctx) &&
10220          !hasUnacceptableSideEffect(Result, SEK);
10221 }
10222 
10223 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
10224                     SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
10225   EvalResult EvalResult;
10226   EvalResult.Diag = Diag;
10227   bool Result = EvaluateAsRValue(EvalResult, Ctx);
10228   (void)Result;
10229   assert(Result && "Could not evaluate expression");
10230   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
10231 
10232   return EvalResult.Val.getInt();
10233 }
10234 
10235 void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
10236   bool IsConst;
10237   EvalResult EvalResult;
10238   if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
10239     EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
10240     (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10241   }
10242 }
10243 
10244 bool Expr::EvalResult::isGlobalLValue() const {
10245   assert(Val.isLValue());
10246   return IsGlobalLValue(Val.getLValueBase());
10247 }
10248 
10249 
10250 /// isIntegerConstantExpr - this recursive routine will test if an expression is
10251 /// an integer constant expression.
10252 
10253 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10254 /// comma, etc
10255 
10256 // CheckICE - This function does the fundamental ICE checking: the returned
10257 // ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10258 // and a (possibly null) SourceLocation indicating the location of the problem.
10259 //
10260 // Note that to reduce code duplication, this helper does no evaluation
10261 // itself; the caller checks whether the expression is evaluatable, and
10262 // in the rare cases where CheckICE actually cares about the evaluated
10263 // value, it calls into Evaluate.
10264 
10265 namespace {
10266 
10267 enum ICEKind {
10268   /// This expression is an ICE.
10269   IK_ICE,
10270   /// This expression is not an ICE, but if it isn't evaluated, it's
10271   /// a legal subexpression for an ICE. This return value is used to handle
10272   /// the comma operator in C99 mode, and non-constant subexpressions.
10273   IK_ICEIfUnevaluated,
10274   /// This expression is not an ICE, and is not a legal subexpression for one.
10275   IK_NotICE
10276 };
10277 
10278 struct ICEDiag {
10279   ICEKind Kind;
10280   SourceLocation Loc;
10281 
10282   ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
10283 };
10284 
10285 }
10286 
10287 static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10288 
10289 static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
10290 
10291 static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
10292   Expr::EvalResult EVResult;
10293   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
10294       !EVResult.Val.isInt())
10295     return ICEDiag(IK_NotICE, E->getLocStart());
10296 
10297   return NoDiag();
10298 }
10299 
10300 static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
10301   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
10302   if (!E->getType()->isIntegralOrEnumerationType())
10303     return ICEDiag(IK_NotICE, E->getLocStart());
10304 
10305   switch (E->getStmtClass()) {
10306 #define ABSTRACT_STMT(Node)
10307 #define STMT(Node, Base) case Expr::Node##Class:
10308 #define EXPR(Node, Base)
10309 #include "clang/AST/StmtNodes.inc"
10310   case Expr::PredefinedExprClass:
10311   case Expr::FloatingLiteralClass:
10312   case Expr::ImaginaryLiteralClass:
10313   case Expr::StringLiteralClass:
10314   case Expr::ArraySubscriptExprClass:
10315   case Expr::OMPArraySectionExprClass:
10316   case Expr::MemberExprClass:
10317   case Expr::CompoundAssignOperatorClass:
10318   case Expr::CompoundLiteralExprClass:
10319   case Expr::ExtVectorElementExprClass:
10320   case Expr::DesignatedInitExprClass:
10321   case Expr::ArrayInitLoopExprClass:
10322   case Expr::ArrayInitIndexExprClass:
10323   case Expr::NoInitExprClass:
10324   case Expr::DesignatedInitUpdateExprClass:
10325   case Expr::ImplicitValueInitExprClass:
10326   case Expr::ParenListExprClass:
10327   case Expr::VAArgExprClass:
10328   case Expr::AddrLabelExprClass:
10329   case Expr::StmtExprClass:
10330   case Expr::CXXMemberCallExprClass:
10331   case Expr::CUDAKernelCallExprClass:
10332   case Expr::CXXDynamicCastExprClass:
10333   case Expr::CXXTypeidExprClass:
10334   case Expr::CXXUuidofExprClass:
10335   case Expr::MSPropertyRefExprClass:
10336   case Expr::MSPropertySubscriptExprClass:
10337   case Expr::CXXNullPtrLiteralExprClass:
10338   case Expr::UserDefinedLiteralClass:
10339   case Expr::CXXThisExprClass:
10340   case Expr::CXXThrowExprClass:
10341   case Expr::CXXNewExprClass:
10342   case Expr::CXXDeleteExprClass:
10343   case Expr::CXXPseudoDestructorExprClass:
10344   case Expr::UnresolvedLookupExprClass:
10345   case Expr::TypoExprClass:
10346   case Expr::DependentScopeDeclRefExprClass:
10347   case Expr::CXXConstructExprClass:
10348   case Expr::CXXInheritedCtorInitExprClass:
10349   case Expr::CXXStdInitializerListExprClass:
10350   case Expr::CXXBindTemporaryExprClass:
10351   case Expr::ExprWithCleanupsClass:
10352   case Expr::CXXTemporaryObjectExprClass:
10353   case Expr::CXXUnresolvedConstructExprClass:
10354   case Expr::CXXDependentScopeMemberExprClass:
10355   case Expr::UnresolvedMemberExprClass:
10356   case Expr::ObjCStringLiteralClass:
10357   case Expr::ObjCBoxedExprClass:
10358   case Expr::ObjCArrayLiteralClass:
10359   case Expr::ObjCDictionaryLiteralClass:
10360   case Expr::ObjCEncodeExprClass:
10361   case Expr::ObjCMessageExprClass:
10362   case Expr::ObjCSelectorExprClass:
10363   case Expr::ObjCProtocolExprClass:
10364   case Expr::ObjCIvarRefExprClass:
10365   case Expr::ObjCPropertyRefExprClass:
10366   case Expr::ObjCSubscriptRefExprClass:
10367   case Expr::ObjCIsaExprClass:
10368   case Expr::ObjCAvailabilityCheckExprClass:
10369   case Expr::ShuffleVectorExprClass:
10370   case Expr::ConvertVectorExprClass:
10371   case Expr::BlockExprClass:
10372   case Expr::NoStmtClass:
10373   case Expr::OpaqueValueExprClass:
10374   case Expr::PackExpansionExprClass:
10375   case Expr::SubstNonTypeTemplateParmPackExprClass:
10376   case Expr::FunctionParmPackExprClass:
10377   case Expr::AsTypeExprClass:
10378   case Expr::ObjCIndirectCopyRestoreExprClass:
10379   case Expr::MaterializeTemporaryExprClass:
10380   case Expr::PseudoObjectExprClass:
10381   case Expr::AtomicExprClass:
10382   case Expr::LambdaExprClass:
10383   case Expr::CXXFoldExprClass:
10384   case Expr::CoawaitExprClass:
10385   case Expr::DependentCoawaitExprClass:
10386   case Expr::CoyieldExprClass:
10387     return ICEDiag(IK_NotICE, E->getLocStart());
10388 
10389   case Expr::InitListExprClass: {
10390     // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10391     // form "T x = { a };" is equivalent to "T x = a;".
10392     // Unless we're initializing a reference, T is a scalar as it is known to be
10393     // of integral or enumeration type.
10394     if (E->isRValue())
10395       if (cast<InitListExpr>(E)->getNumInits() == 1)
10396         return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10397     return ICEDiag(IK_NotICE, E->getLocStart());
10398   }
10399 
10400   case Expr::SizeOfPackExprClass:
10401   case Expr::GNUNullExprClass:
10402     // GCC considers the GNU __null value to be an integral constant expression.
10403     return NoDiag();
10404 
10405   case Expr::SubstNonTypeTemplateParmExprClass:
10406     return
10407       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10408 
10409   case Expr::ParenExprClass:
10410     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
10411   case Expr::GenericSelectionExprClass:
10412     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
10413   case Expr::IntegerLiteralClass:
10414   case Expr::CharacterLiteralClass:
10415   case Expr::ObjCBoolLiteralExprClass:
10416   case Expr::CXXBoolLiteralExprClass:
10417   case Expr::CXXScalarValueInitExprClass:
10418   case Expr::TypeTraitExprClass:
10419   case Expr::ArrayTypeTraitExprClass:
10420   case Expr::ExpressionTraitExprClass:
10421   case Expr::CXXNoexceptExprClass:
10422     return NoDiag();
10423   case Expr::CallExprClass:
10424   case Expr::CXXOperatorCallExprClass: {
10425     // C99 6.6/3 allows function calls within unevaluated subexpressions of
10426     // constant expressions, but they can never be ICEs because an ICE cannot
10427     // contain an operand of (pointer to) function type.
10428     const CallExpr *CE = cast<CallExpr>(E);
10429     if (CE->getBuiltinCallee())
10430       return CheckEvalInICE(E, Ctx);
10431     return ICEDiag(IK_NotICE, E->getLocStart());
10432   }
10433   case Expr::DeclRefExprClass: {
10434     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10435       return NoDiag();
10436     const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
10437     if (Ctx.getLangOpts().CPlusPlus &&
10438         D && IsConstNonVolatile(D->getType())) {
10439       // Parameter variables are never constants.  Without this check,
10440       // getAnyInitializer() can find a default argument, which leads
10441       // to chaos.
10442       if (isa<ParmVarDecl>(D))
10443         return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10444 
10445       // C++ 7.1.5.1p2
10446       //   A variable of non-volatile const-qualified integral or enumeration
10447       //   type initialized by an ICE can be used in ICEs.
10448       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
10449         if (!Dcl->getType()->isIntegralOrEnumerationType())
10450           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10451 
10452         const VarDecl *VD;
10453         // Look for a declaration of this variable that has an initializer, and
10454         // check whether it is an ICE.
10455         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10456           return NoDiag();
10457         else
10458           return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
10459       }
10460     }
10461     return ICEDiag(IK_NotICE, E->getLocStart());
10462   }
10463   case Expr::UnaryOperatorClass: {
10464     const UnaryOperator *Exp = cast<UnaryOperator>(E);
10465     switch (Exp->getOpcode()) {
10466     case UO_PostInc:
10467     case UO_PostDec:
10468     case UO_PreInc:
10469     case UO_PreDec:
10470     case UO_AddrOf:
10471     case UO_Deref:
10472     case UO_Coawait:
10473       // C99 6.6/3 allows increment and decrement within unevaluated
10474       // subexpressions of constant expressions, but they can never be ICEs
10475       // because an ICE cannot contain an lvalue operand.
10476       return ICEDiag(IK_NotICE, E->getLocStart());
10477     case UO_Extension:
10478     case UO_LNot:
10479     case UO_Plus:
10480     case UO_Minus:
10481     case UO_Not:
10482     case UO_Real:
10483     case UO_Imag:
10484       return CheckICE(Exp->getSubExpr(), Ctx);
10485     }
10486 
10487     // OffsetOf falls through here.
10488     LLVM_FALLTHROUGH;
10489   }
10490   case Expr::OffsetOfExprClass: {
10491     // Note that per C99, offsetof must be an ICE. And AFAIK, using
10492     // EvaluateAsRValue matches the proposed gcc behavior for cases like
10493     // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
10494     // compliance: we should warn earlier for offsetof expressions with
10495     // array subscripts that aren't ICEs, and if the array subscripts
10496     // are ICEs, the value of the offsetof must be an integer constant.
10497     return CheckEvalInICE(E, Ctx);
10498   }
10499   case Expr::UnaryExprOrTypeTraitExprClass: {
10500     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10501     if ((Exp->getKind() ==  UETT_SizeOf) &&
10502         Exp->getTypeOfArgument()->isVariableArrayType())
10503       return ICEDiag(IK_NotICE, E->getLocStart());
10504     return NoDiag();
10505   }
10506   case Expr::BinaryOperatorClass: {
10507     const BinaryOperator *Exp = cast<BinaryOperator>(E);
10508     switch (Exp->getOpcode()) {
10509     case BO_PtrMemD:
10510     case BO_PtrMemI:
10511     case BO_Assign:
10512     case BO_MulAssign:
10513     case BO_DivAssign:
10514     case BO_RemAssign:
10515     case BO_AddAssign:
10516     case BO_SubAssign:
10517     case BO_ShlAssign:
10518     case BO_ShrAssign:
10519     case BO_AndAssign:
10520     case BO_XorAssign:
10521     case BO_OrAssign:
10522     case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
10523       // C99 6.6/3 allows assignments within unevaluated subexpressions of
10524       // constant expressions, but they can never be ICEs because an ICE cannot
10525       // contain an lvalue operand.
10526       return ICEDiag(IK_NotICE, E->getLocStart());
10527 
10528     case BO_Mul:
10529     case BO_Div:
10530     case BO_Rem:
10531     case BO_Add:
10532     case BO_Sub:
10533     case BO_Shl:
10534     case BO_Shr:
10535     case BO_LT:
10536     case BO_GT:
10537     case BO_LE:
10538     case BO_GE:
10539     case BO_EQ:
10540     case BO_NE:
10541     case BO_And:
10542     case BO_Xor:
10543     case BO_Or:
10544     case BO_Comma: {
10545       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10546       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10547       if (Exp->getOpcode() == BO_Div ||
10548           Exp->getOpcode() == BO_Rem) {
10549         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
10550         // we don't evaluate one.
10551         if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
10552           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
10553           if (REval == 0)
10554             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10555           if (REval.isSigned() && REval.isAllOnesValue()) {
10556             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
10557             if (LEval.isMinSignedValue())
10558               return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10559           }
10560         }
10561       }
10562       if (Exp->getOpcode() == BO_Comma) {
10563         if (Ctx.getLangOpts().C99) {
10564           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10565           // if it isn't evaluated.
10566           if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10567             return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
10568         } else {
10569           // In both C89 and C++, commas in ICEs are illegal.
10570           return ICEDiag(IK_NotICE, E->getLocStart());
10571         }
10572       }
10573       return Worst(LHSResult, RHSResult);
10574     }
10575     case BO_LAnd:
10576     case BO_LOr: {
10577       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10578       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
10579       if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
10580         // Rare case where the RHS has a comma "side-effect"; we need
10581         // to actually check the condition to see whether the side
10582         // with the comma is evaluated.
10583         if ((Exp->getOpcode() == BO_LAnd) !=
10584             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
10585           return RHSResult;
10586         return NoDiag();
10587       }
10588 
10589       return Worst(LHSResult, RHSResult);
10590     }
10591     }
10592     LLVM_FALLTHROUGH;
10593   }
10594   case Expr::ImplicitCastExprClass:
10595   case Expr::CStyleCastExprClass:
10596   case Expr::CXXFunctionalCastExprClass:
10597   case Expr::CXXStaticCastExprClass:
10598   case Expr::CXXReinterpretCastExprClass:
10599   case Expr::CXXConstCastExprClass:
10600   case Expr::ObjCBridgedCastExprClass: {
10601     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
10602     if (isa<ExplicitCastExpr>(E)) {
10603       if (const FloatingLiteral *FL
10604             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10605         unsigned DestWidth = Ctx.getIntWidth(E->getType());
10606         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10607         APSInt IgnoredVal(DestWidth, !DestSigned);
10608         bool Ignored;
10609         // If the value does not fit in the destination type, the behavior is
10610         // undefined, so we are not required to treat it as a constant
10611         // expression.
10612         if (FL->getValue().convertToInteger(IgnoredVal,
10613                                             llvm::APFloat::rmTowardZero,
10614                                             &Ignored) & APFloat::opInvalidOp)
10615           return ICEDiag(IK_NotICE, E->getLocStart());
10616         return NoDiag();
10617       }
10618     }
10619     switch (cast<CastExpr>(E)->getCastKind()) {
10620     case CK_LValueToRValue:
10621     case CK_AtomicToNonAtomic:
10622     case CK_NonAtomicToAtomic:
10623     case CK_NoOp:
10624     case CK_IntegralToBoolean:
10625     case CK_IntegralCast:
10626       return CheckICE(SubExpr, Ctx);
10627     default:
10628       return ICEDiag(IK_NotICE, E->getLocStart());
10629     }
10630   }
10631   case Expr::BinaryConditionalOperatorClass: {
10632     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10633     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
10634     if (CommonResult.Kind == IK_NotICE) return CommonResult;
10635     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10636     if (FalseResult.Kind == IK_NotICE) return FalseResult;
10637     if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10638     if (FalseResult.Kind == IK_ICEIfUnevaluated &&
10639         Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
10640     return FalseResult;
10641   }
10642   case Expr::ConditionalOperatorClass: {
10643     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10644     // If the condition (ignoring parens) is a __builtin_constant_p call,
10645     // then only the true side is actually considered in an integer constant
10646     // expression, and it is fully evaluated.  This is an important GNU
10647     // extension.  See GCC PR38377 for discussion.
10648     if (const CallExpr *CallCE
10649         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
10650       if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
10651         return CheckEvalInICE(E, Ctx);
10652     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
10653     if (CondResult.Kind == IK_NotICE)
10654       return CondResult;
10655 
10656     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10657     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
10658 
10659     if (TrueResult.Kind == IK_NotICE)
10660       return TrueResult;
10661     if (FalseResult.Kind == IK_NotICE)
10662       return FalseResult;
10663     if (CondResult.Kind == IK_ICEIfUnevaluated)
10664       return CondResult;
10665     if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
10666       return NoDiag();
10667     // Rare case where the diagnostics depend on which side is evaluated
10668     // Note that if we get here, CondResult is 0, and at least one of
10669     // TrueResult and FalseResult is non-zero.
10670     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
10671       return FalseResult;
10672     return TrueResult;
10673   }
10674   case Expr::CXXDefaultArgExprClass:
10675     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
10676   case Expr::CXXDefaultInitExprClass:
10677     return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
10678   case Expr::ChooseExprClass: {
10679     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
10680   }
10681   }
10682 
10683   llvm_unreachable("Invalid StmtClass!");
10684 }
10685 
10686 /// Evaluate an expression as a C++11 integral constant expression.
10687 static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
10688                                                     const Expr *E,
10689                                                     llvm::APSInt *Value,
10690                                                     SourceLocation *Loc) {
10691   if (!E->getType()->isIntegralOrEnumerationType()) {
10692     if (Loc) *Loc = E->getExprLoc();
10693     return false;
10694   }
10695 
10696   APValue Result;
10697   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
10698     return false;
10699 
10700   if (!Result.isInt()) {
10701     if (Loc) *Loc = E->getExprLoc();
10702     return false;
10703   }
10704 
10705   if (Value) *Value = Result.getInt();
10706   return true;
10707 }
10708 
10709 bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10710                                  SourceLocation *Loc) const {
10711   if (Ctx.getLangOpts().CPlusPlus11)
10712     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
10713 
10714   ICEDiag D = CheckICE(this, Ctx);
10715   if (D.Kind != IK_ICE) {
10716     if (Loc) *Loc = D.Loc;
10717     return false;
10718   }
10719   return true;
10720 }
10721 
10722 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
10723                                  SourceLocation *Loc, bool isEvaluated) const {
10724   if (Ctx.getLangOpts().CPlusPlus11)
10725     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10726 
10727   if (!isIntegerConstantExpr(Ctx, Loc))
10728     return false;
10729   // The only possible side-effects here are due to UB discovered in the
10730   // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10731   // required to treat the expression as an ICE, so we produce the folded
10732   // value.
10733   if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
10734     llvm_unreachable("ICE cannot be evaluated!");
10735   return true;
10736 }
10737 
10738 bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
10739   return CheckICE(this, Ctx).Kind == IK_ICE;
10740 }
10741 
10742 bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
10743                                SourceLocation *Loc) const {
10744   // We support this checking in C++98 mode in order to diagnose compatibility
10745   // issues.
10746   assert(Ctx.getLangOpts().CPlusPlus);
10747 
10748   // Build evaluation settings.
10749   Expr::EvalStatus Status;
10750   SmallVector<PartialDiagnosticAt, 8> Diags;
10751   Status.Diag = &Diags;
10752   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
10753 
10754   APValue Scratch;
10755   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10756 
10757   if (!Diags.empty()) {
10758     IsConstExpr = false;
10759     if (Loc) *Loc = Diags[0].first;
10760   } else if (!IsConstExpr) {
10761     // FIXME: This shouldn't happen.
10762     if (Loc) *Loc = getExprLoc();
10763   }
10764 
10765   return IsConstExpr;
10766 }
10767 
10768 bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10769                                     const FunctionDecl *Callee,
10770                                     ArrayRef<const Expr*> Args,
10771                                     const Expr *This) const {
10772   Expr::EvalStatus Status;
10773   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10774 
10775   LValue ThisVal;
10776   const LValue *ThisPtr = nullptr;
10777   if (This) {
10778 #ifndef NDEBUG
10779     auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10780     assert(MD && "Don't provide `this` for non-methods.");
10781     assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10782 #endif
10783     if (EvaluateObjectArgument(Info, This, ThisVal))
10784       ThisPtr = &ThisVal;
10785     if (Info.EvalStatus.HasSideEffects)
10786       return false;
10787   }
10788 
10789   ArgVector ArgValues(Args.size());
10790   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10791        I != E; ++I) {
10792     if ((*I)->isValueDependent() ||
10793         !Evaluate(ArgValues[I - Args.begin()], Info, *I))
10794       // If evaluation fails, throw away the argument entirely.
10795       ArgValues[I - Args.begin()] = APValue();
10796     if (Info.EvalStatus.HasSideEffects)
10797       return false;
10798   }
10799 
10800   // Build fake call to Callee.
10801   CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
10802                        ArgValues.data());
10803   return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10804 }
10805 
10806 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
10807                                    SmallVectorImpl<
10808                                      PartialDiagnosticAt> &Diags) {
10809   // FIXME: It would be useful to check constexpr function templates, but at the
10810   // moment the constant expression evaluator cannot cope with the non-rigorous
10811   // ASTs which we build for dependent expressions.
10812   if (FD->isDependentContext())
10813     return true;
10814 
10815   Expr::EvalStatus Status;
10816   Status.Diag = &Diags;
10817 
10818   EvalInfo Info(FD->getASTContext(), Status,
10819                 EvalInfo::EM_PotentialConstantExpression);
10820 
10821   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
10822   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
10823 
10824   // Fabricate an arbitrary expression on the stack and pretend that it
10825   // is a temporary being used as the 'this' pointer.
10826   LValue This;
10827   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
10828   This.set(&VIE, Info.CurrentCall->Index);
10829 
10830   ArrayRef<const Expr*> Args;
10831 
10832   APValue Scratch;
10833   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10834     // Evaluate the call as a constant initializer, to allow the construction
10835     // of objects of non-literal types.
10836     Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
10837     HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10838   } else {
10839     SourceLocation Loc = FD->getLocation();
10840     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
10841                        Args, FD->getBody(), Info, Scratch, nullptr);
10842   }
10843 
10844   return Diags.empty();
10845 }
10846 
10847 bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10848                                               const FunctionDecl *FD,
10849                                               SmallVectorImpl<
10850                                                 PartialDiagnosticAt> &Diags) {
10851   Expr::EvalStatus Status;
10852   Status.Diag = &Diags;
10853 
10854   EvalInfo Info(FD->getASTContext(), Status,
10855                 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10856 
10857   // Fabricate a call stack frame to give the arguments a plausible cover story.
10858   ArrayRef<const Expr*> Args;
10859   ArgVector ArgValues(0);
10860   bool Success = EvaluateArgs(Args, ArgValues, Info);
10861   (void)Success;
10862   assert(Success &&
10863          "Failed to set up arguments for potential constant evaluation");
10864   CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
10865 
10866   APValue ResultScratch;
10867   Evaluate(ResultScratch, Info, E);
10868   return Diags.empty();
10869 }
10870 
10871 bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10872                                  unsigned Type) const {
10873   if (!getType()->isPointerType())
10874     return false;
10875 
10876   Expr::EvalStatus Status;
10877   EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
10878   return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
10879 }
10880