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