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