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