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 rules only, at the moment), or, if folding failed too,
27 //    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/CharUnits.h"
39 #include "clang/AST/RecordLayout.h"
40 #include "clang/AST/StmtVisitor.h"
41 #include "clang/AST/TypeLoc.h"
42 #include "clang/AST/ASTDiagnostic.h"
43 #include "clang/AST/Expr.h"
44 #include "clang/Basic/Builtins.h"
45 #include "clang/Basic/TargetInfo.h"
46 #include "llvm/ADT/SmallString.h"
47 #include <cstring>
48 
49 using namespace clang;
50 using llvm::APSInt;
51 using llvm::APFloat;
52 
53 /// EvalInfo - This is a private struct used by the evaluator to capture
54 /// information about a subexpression as it is folded.  It retains information
55 /// about the AST context, but also maintains information about the folded
56 /// expression.
57 ///
58 /// If an expression could be evaluated, it is still possible it is not a C
59 /// "integer constant expression" or constant expression.  If not, this struct
60 /// captures information about how and why not.
61 ///
62 /// One bit of information passed *into* the request for constant folding
63 /// indicates whether the subexpression is "evaluated" or not according to C
64 /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
65 /// evaluate the expression regardless of what the RHS is, but C only allows
66 /// certain things in certain situations.
67 namespace {
68   struct LValue;
69   struct CallStackFrame;
70   struct EvalInfo;
71 
72   QualType getType(APValue::LValueBase B) {
73     if (!B) return QualType();
74     if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
75       return D->getType();
76     return B.get<const Expr*>()->getType();
77   }
78 
79   /// Get an LValue path entry, which is known to not be an array index, as a
80   /// field declaration.
81   const FieldDecl *getAsField(APValue::LValuePathEntry E) {
82     APValue::BaseOrMemberType Value;
83     Value.setFromOpaqueValue(E.BaseOrMember);
84     return dyn_cast<FieldDecl>(Value.getPointer());
85   }
86   /// Get an LValue path entry, which is known to not be an array index, as a
87   /// base class declaration.
88   const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
89     APValue::BaseOrMemberType Value;
90     Value.setFromOpaqueValue(E.BaseOrMember);
91     return dyn_cast<CXXRecordDecl>(Value.getPointer());
92   }
93   /// Determine whether this LValue path entry for a base class names a virtual
94   /// base class.
95   bool isVirtualBaseClass(APValue::LValuePathEntry E) {
96     APValue::BaseOrMemberType Value;
97     Value.setFromOpaqueValue(E.BaseOrMember);
98     return Value.getInt();
99   }
100 
101   /// Find the path length and type of the most-derived subobject in the given
102   /// path, and find the size of the containing array, if any.
103   static
104   unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
105                                     ArrayRef<APValue::LValuePathEntry> Path,
106                                     uint64_t &ArraySize, QualType &Type) {
107     unsigned MostDerivedLength = 0;
108     Type = Base;
109     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
110       if (Type->isArrayType()) {
111         const ConstantArrayType *CAT =
112           cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
113         Type = CAT->getElementType();
114         ArraySize = CAT->getSize().getZExtValue();
115         MostDerivedLength = I + 1;
116       } else if (const FieldDecl *FD = getAsField(Path[I])) {
117         Type = FD->getType();
118         ArraySize = 0;
119         MostDerivedLength = I + 1;
120       } else {
121         // Path[I] describes a base class.
122         ArraySize = 0;
123       }
124     }
125     return MostDerivedLength;
126   }
127 
128   // The order of this enum is important for diagnostics.
129   enum CheckSubobjectKind {
130     CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex
131   };
132 
133   /// A path from a glvalue to a subobject of that glvalue.
134   struct SubobjectDesignator {
135     /// True if the subobject was named in a manner not supported by C++11. Such
136     /// lvalues can still be folded, but they are not core constant expressions
137     /// and we cannot perform lvalue-to-rvalue conversions on them.
138     bool Invalid : 1;
139 
140     /// Is this a pointer one past the end of an object?
141     bool IsOnePastTheEnd : 1;
142 
143     /// The length of the path to the most-derived object of which this is a
144     /// subobject.
145     unsigned MostDerivedPathLength : 30;
146 
147     /// The size of the array of which the most-derived object is an element, or
148     /// 0 if the most-derived object is not an array element.
149     uint64_t MostDerivedArraySize;
150 
151     /// The type of the most derived object referred to by this address.
152     QualType MostDerivedType;
153 
154     typedef APValue::LValuePathEntry PathEntry;
155 
156     /// The entries on the path from the glvalue to the designated subobject.
157     SmallVector<PathEntry, 8> Entries;
158 
159     SubobjectDesignator() : Invalid(true) {}
160 
161     explicit SubobjectDesignator(QualType T)
162       : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
163         MostDerivedArraySize(0), MostDerivedType(T) {}
164 
165     SubobjectDesignator(ASTContext &Ctx, const APValue &V)
166       : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
167         MostDerivedPathLength(0), MostDerivedArraySize(0) {
168       if (!Invalid) {
169         IsOnePastTheEnd = V.isLValueOnePastTheEnd();
170         ArrayRef<PathEntry> VEntries = V.getLValuePath();
171         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
172         if (V.getLValueBase())
173           MostDerivedPathLength =
174               findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
175                                        V.getLValuePath(), MostDerivedArraySize,
176                                        MostDerivedType);
177       }
178     }
179 
180     void setInvalid() {
181       Invalid = true;
182       Entries.clear();
183     }
184 
185     /// Determine whether this is a one-past-the-end pointer.
186     bool isOnePastTheEnd() const {
187       if (IsOnePastTheEnd)
188         return true;
189       if (MostDerivedArraySize &&
190           Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
191         return true;
192       return false;
193     }
194 
195     /// Check that this refers to a valid subobject.
196     bool isValidSubobject() const {
197       if (Invalid)
198         return false;
199       return !isOnePastTheEnd();
200     }
201     /// Check that this refers to a valid subobject, and if not, produce a
202     /// relevant diagnostic and set the designator as invalid.
203     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
204 
205     /// Update this designator to refer to the first element within this array.
206     void addArrayUnchecked(const ConstantArrayType *CAT) {
207       PathEntry Entry;
208       Entry.ArrayIndex = 0;
209       Entries.push_back(Entry);
210 
211       // This is a most-derived object.
212       MostDerivedType = CAT->getElementType();
213       MostDerivedArraySize = CAT->getSize().getZExtValue();
214       MostDerivedPathLength = Entries.size();
215     }
216     /// Update this designator to refer to the given base or member of this
217     /// object.
218     void addDeclUnchecked(const Decl *D, bool Virtual = false) {
219       PathEntry Entry;
220       APValue::BaseOrMemberType Value(D, Virtual);
221       Entry.BaseOrMember = Value.getOpaqueValue();
222       Entries.push_back(Entry);
223 
224       // If this isn't a base class, it's a new most-derived object.
225       if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
226         MostDerivedType = FD->getType();
227         MostDerivedArraySize = 0;
228         MostDerivedPathLength = Entries.size();
229       }
230     }
231     void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
232     /// Add N to the address of this subobject.
233     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
234       if (Invalid) return;
235       if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
236         Entries.back().ArrayIndex += N;
237         if (Entries.back().ArrayIndex > MostDerivedArraySize) {
238           diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
239           setInvalid();
240         }
241         return;
242       }
243       // [expr.add]p4: For the purposes of these operators, a pointer to a
244       // nonarray object behaves the same as a pointer to the first element of
245       // an array of length one with the type of the object as its element type.
246       if (IsOnePastTheEnd && N == (uint64_t)-1)
247         IsOnePastTheEnd = false;
248       else if (!IsOnePastTheEnd && N == 1)
249         IsOnePastTheEnd = true;
250       else if (N != 0) {
251         diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
252         setInvalid();
253       }
254     }
255   };
256 
257   /// A core constant value. This can be the value of any constant expression,
258   /// or a pointer or reference to a non-static object or function parameter.
259   ///
260   /// For an LValue, the base and offset are stored in the APValue subobject,
261   /// but the other information is stored in the SubobjectDesignator. For all
262   /// other value kinds, the value is stored directly in the APValue subobject.
263   class CCValue : public APValue {
264     typedef llvm::APSInt APSInt;
265     typedef llvm::APFloat APFloat;
266     /// If the value is a reference or pointer into a parameter or temporary,
267     /// this is the corresponding call stack frame.
268     CallStackFrame *CallFrame;
269     /// If the value is a reference or pointer, this is a description of how the
270     /// subobject was specified.
271     SubobjectDesignator Designator;
272   public:
273     struct GlobalValue {};
274 
275     CCValue() {}
276     explicit CCValue(const APSInt &I) : APValue(I) {}
277     explicit CCValue(const APFloat &F) : APValue(F) {}
278     CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
279     CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
280     CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
281     CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
282     CCValue(LValueBase B, const CharUnits &O, CallStackFrame *F,
283             const SubobjectDesignator &D) :
284       APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
285     CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
286       APValue(V), CallFrame(0), Designator(Ctx, V) {}
287     CCValue(const ValueDecl *D, bool IsDerivedMember,
288             ArrayRef<const CXXRecordDecl*> Path) :
289       APValue(D, IsDerivedMember, Path) {}
290     CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
291       APValue(LHSExpr, RHSExpr) {}
292 
293     CallStackFrame *getLValueFrame() const {
294       assert(getKind() == LValue);
295       return CallFrame;
296     }
297     SubobjectDesignator &getLValueDesignator() {
298       assert(getKind() == LValue);
299       return Designator;
300     }
301     const SubobjectDesignator &getLValueDesignator() const {
302       return const_cast<CCValue*>(this)->getLValueDesignator();
303     }
304   };
305 
306   /// A stack frame in the constexpr call stack.
307   struct CallStackFrame {
308     EvalInfo &Info;
309 
310     /// Parent - The caller of this stack frame.
311     CallStackFrame *Caller;
312 
313     /// CallLoc - The location of the call expression for this call.
314     SourceLocation CallLoc;
315 
316     /// Callee - The function which was called.
317     const FunctionDecl *Callee;
318 
319     /// This - The binding for the this pointer in this call, if any.
320     const LValue *This;
321 
322     /// ParmBindings - Parameter bindings for this function call, indexed by
323     /// parameters' function scope indices.
324     const CCValue *Arguments;
325 
326     typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
327     typedef MapTy::const_iterator temp_iterator;
328     /// Temporaries - Temporary lvalues materialized within this stack frame.
329     MapTy Temporaries;
330 
331     CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
332                    const FunctionDecl *Callee, const LValue *This,
333                    const CCValue *Arguments);
334     ~CallStackFrame();
335   };
336 
337   /// A partial diagnostic which we might know in advance that we are not going
338   /// to emit.
339   class OptionalDiagnostic {
340     PartialDiagnostic *Diag;
341 
342   public:
343     explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
344 
345     template<typename T>
346     OptionalDiagnostic &operator<<(const T &v) {
347       if (Diag)
348         *Diag << v;
349       return *this;
350     }
351   };
352 
353   struct EvalInfo {
354     ASTContext &Ctx;
355 
356     /// EvalStatus - Contains information about the evaluation.
357     Expr::EvalStatus &EvalStatus;
358 
359     /// CurrentCall - The top of the constexpr call stack.
360     CallStackFrame *CurrentCall;
361 
362     /// CallStackDepth - The number of calls in the call stack right now.
363     unsigned CallStackDepth;
364 
365     typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
366     /// OpaqueValues - Values used as the common expression in a
367     /// BinaryConditionalOperator.
368     MapTy OpaqueValues;
369 
370     /// BottomFrame - The frame in which evaluation started. This must be
371     /// initialized after CurrentCall and CallStackDepth.
372     CallStackFrame BottomFrame;
373 
374     /// EvaluatingDecl - This is the declaration whose initializer is being
375     /// evaluated, if any.
376     const VarDecl *EvaluatingDecl;
377 
378     /// EvaluatingDeclValue - This is the value being constructed for the
379     /// declaration whose initializer is being evaluated, if any.
380     APValue *EvaluatingDeclValue;
381 
382     /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
383     /// notes attached to it will also be stored, otherwise they will not be.
384     bool HasActiveDiagnostic;
385 
386     /// CheckingPotentialConstantExpression - Are we checking whether the
387     /// expression is a potential constant expression? If so, some diagnostics
388     /// are suppressed.
389     bool CheckingPotentialConstantExpression;
390 
391 
392     EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
393       : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
394         CallStackDepth(0), BottomFrame(*this, SourceLocation(), 0, 0, 0),
395         EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
396         CheckingPotentialConstantExpression(false) {}
397 
398     const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
399       MapTy::const_iterator i = OpaqueValues.find(e);
400       if (i == OpaqueValues.end()) return 0;
401       return &i->second;
402     }
403 
404     void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
405       EvaluatingDecl = VD;
406       EvaluatingDeclValue = &Value;
407     }
408 
409     const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
410 
411     bool CheckCallLimit(SourceLocation Loc) {
412       // Don't perform any constexpr calls (other than the call we're checking)
413       // when checking a potential constant expression.
414       if (CheckingPotentialConstantExpression && CallStackDepth > 1)
415         return false;
416       if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
417         return true;
418       Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
419         << getLangOpts().ConstexprCallDepth;
420       return false;
421     }
422 
423   private:
424     /// Add a diagnostic to the diagnostics list.
425     PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
426       PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
427       EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
428       return EvalStatus.Diag->back().second;
429     }
430 
431     /// Add notes containing a call stack to the current point of evaluation.
432     void addCallStack(unsigned Limit);
433 
434   public:
435     /// Diagnose that the evaluation cannot be folded.
436     OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
437                               = diag::note_invalid_subexpr_in_const_expr,
438                             unsigned ExtraNotes = 0) {
439       // If we have a prior diagnostic, it will be noting that the expression
440       // isn't a constant expression. This diagnostic is more important.
441       // FIXME: We might want to show both diagnostics to the user.
442       if (EvalStatus.Diag) {
443         unsigned CallStackNotes = CallStackDepth - 1;
444         unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
445         if (Limit)
446           CallStackNotes = std::min(CallStackNotes, Limit + 1);
447         if (CheckingPotentialConstantExpression)
448           CallStackNotes = 0;
449 
450         HasActiveDiagnostic = true;
451         EvalStatus.Diag->clear();
452         EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
453         addDiag(Loc, DiagId);
454         if (!CheckingPotentialConstantExpression)
455           addCallStack(Limit);
456         return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
457       }
458       HasActiveDiagnostic = false;
459       return OptionalDiagnostic();
460     }
461 
462     /// Diagnose that the evaluation does not produce a C++11 core constant
463     /// expression.
464     OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
465                                  = diag::note_invalid_subexpr_in_const_expr,
466                                unsigned ExtraNotes = 0) {
467       // Don't override a previous diagnostic.
468       if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
469         return OptionalDiagnostic();
470       return Diag(Loc, DiagId, ExtraNotes);
471     }
472 
473     /// Add a note to a prior diagnostic.
474     OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
475       if (!HasActiveDiagnostic)
476         return OptionalDiagnostic();
477       return OptionalDiagnostic(&addDiag(Loc, DiagId));
478     }
479 
480     /// Add a stack of notes to a prior diagnostic.
481     void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
482       if (HasActiveDiagnostic) {
483         EvalStatus.Diag->insert(EvalStatus.Diag->end(),
484                                 Diags.begin(), Diags.end());
485       }
486     }
487 
488     /// Should we continue evaluation as much as possible after encountering a
489     /// construct which can't be folded?
490     bool keepEvaluatingAfterFailure() {
491       return CheckingPotentialConstantExpression && EvalStatus.Diag->empty();
492     }
493   };
494 }
495 
496 bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
497                                          CheckSubobjectKind CSK) {
498   if (Invalid)
499     return false;
500   if (isOnePastTheEnd()) {
501     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
502       << CSK;
503     setInvalid();
504     return false;
505   }
506   return true;
507 }
508 
509 void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
510                                                     const Expr *E, uint64_t N) {
511   if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
512     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
513       << static_cast<int>(N) << /*array*/ 0
514       << static_cast<unsigned>(MostDerivedArraySize);
515   else
516     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
517       << static_cast<int>(N) << /*non-array*/ 1;
518   setInvalid();
519 }
520 
521 CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
522                                const FunctionDecl *Callee, const LValue *This,
523                                const CCValue *Arguments)
524     : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
525       This(This), Arguments(Arguments) {
526   Info.CurrentCall = this;
527   ++Info.CallStackDepth;
528 }
529 
530 CallStackFrame::~CallStackFrame() {
531   assert(Info.CurrentCall == this && "calls retired out of order");
532   --Info.CallStackDepth;
533   Info.CurrentCall = Caller;
534 }
535 
536 /// Produce a string describing the given constexpr call.
537 static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
538   unsigned ArgIndex = 0;
539   bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
540                       !isa<CXXConstructorDecl>(Frame->Callee);
541 
542   if (!IsMemberCall)
543     Out << *Frame->Callee << '(';
544 
545   for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
546        E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
547     if (ArgIndex > (unsigned)IsMemberCall)
548       Out << ", ";
549 
550     const ParmVarDecl *Param = *I;
551     const CCValue &Arg = Frame->Arguments[ArgIndex];
552     if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
553       Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
554     else {
555       // Deliberately slice off the frame to form an APValue we can print.
556       APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
557                     Arg.getLValueDesignator().Entries,
558                     Arg.getLValueDesignator().IsOnePastTheEnd);
559       Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
560     }
561 
562     if (ArgIndex == 0 && IsMemberCall)
563       Out << "->" << *Frame->Callee << '(';
564   }
565 
566   Out << ')';
567 }
568 
569 void EvalInfo::addCallStack(unsigned Limit) {
570   // Determine which calls to skip, if any.
571   unsigned ActiveCalls = CallStackDepth - 1;
572   unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
573   if (Limit && Limit < ActiveCalls) {
574     SkipStart = Limit / 2 + Limit % 2;
575     SkipEnd = ActiveCalls - Limit / 2;
576   }
577 
578   // Walk the call stack and add the diagnostics.
579   unsigned CallIdx = 0;
580   for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
581        Frame = Frame->Caller, ++CallIdx) {
582     // Skip this call?
583     if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
584       if (CallIdx == SkipStart) {
585         // Note that we're skipping calls.
586         addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
587           << unsigned(ActiveCalls - Limit);
588       }
589       continue;
590     }
591 
592     llvm::SmallVector<char, 128> Buffer;
593     llvm::raw_svector_ostream Out(Buffer);
594     describeCall(Frame, Out);
595     addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
596   }
597 }
598 
599 namespace {
600   struct ComplexValue {
601   private:
602     bool IsInt;
603 
604   public:
605     APSInt IntReal, IntImag;
606     APFloat FloatReal, FloatImag;
607 
608     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
609 
610     void makeComplexFloat() { IsInt = false; }
611     bool isComplexFloat() const { return !IsInt; }
612     APFloat &getComplexFloatReal() { return FloatReal; }
613     APFloat &getComplexFloatImag() { return FloatImag; }
614 
615     void makeComplexInt() { IsInt = true; }
616     bool isComplexInt() const { return IsInt; }
617     APSInt &getComplexIntReal() { return IntReal; }
618     APSInt &getComplexIntImag() { return IntImag; }
619 
620     void moveInto(CCValue &v) const {
621       if (isComplexFloat())
622         v = CCValue(FloatReal, FloatImag);
623       else
624         v = CCValue(IntReal, IntImag);
625     }
626     void setFrom(const CCValue &v) {
627       assert(v.isComplexFloat() || v.isComplexInt());
628       if (v.isComplexFloat()) {
629         makeComplexFloat();
630         FloatReal = v.getComplexFloatReal();
631         FloatImag = v.getComplexFloatImag();
632       } else {
633         makeComplexInt();
634         IntReal = v.getComplexIntReal();
635         IntImag = v.getComplexIntImag();
636       }
637     }
638   };
639 
640   struct LValue {
641     APValue::LValueBase Base;
642     CharUnits Offset;
643     CallStackFrame *Frame;
644     SubobjectDesignator Designator;
645 
646     const APValue::LValueBase getLValueBase() const { return Base; }
647     CharUnits &getLValueOffset() { return Offset; }
648     const CharUnits &getLValueOffset() const { return Offset; }
649     CallStackFrame *getLValueFrame() const { return Frame; }
650     SubobjectDesignator &getLValueDesignator() { return Designator; }
651     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
652 
653     void moveInto(CCValue &V) const {
654       V = CCValue(Base, Offset, Frame, Designator);
655     }
656     void setFrom(const CCValue &V) {
657       assert(V.isLValue());
658       Base = V.getLValueBase();
659       Offset = V.getLValueOffset();
660       Frame = V.getLValueFrame();
661       Designator = V.getLValueDesignator();
662     }
663 
664     void set(APValue::LValueBase B, CallStackFrame *F = 0) {
665       Base = B;
666       Offset = CharUnits::Zero();
667       Frame = F;
668       Designator = SubobjectDesignator(getType(B));
669     }
670 
671     // Check that this LValue is not based on a null pointer. If it is, produce
672     // a diagnostic and mark the designator as invalid.
673     bool checkNullPointer(EvalInfo &Info, const Expr *E,
674                           CheckSubobjectKind CSK) {
675       if (Designator.Invalid)
676         return false;
677       if (!Base) {
678         Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
679           << CSK;
680         Designator.setInvalid();
681         return false;
682       }
683       return true;
684     }
685 
686     // Check this LValue refers to an object. If not, set the designator to be
687     // invalid and emit a diagnostic.
688     bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
689       return checkNullPointer(Info, E, CSK) &&
690              Designator.checkSubobject(Info, E, CSK);
691     }
692 
693     void addDecl(EvalInfo &Info, const Expr *E,
694                  const Decl *D, bool Virtual = false) {
695       checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
696       Designator.addDeclUnchecked(D, Virtual);
697     }
698     void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
699       checkSubobject(Info, E, CSK_ArrayToPointer);
700       Designator.addArrayUnchecked(CAT);
701     }
702     void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
703       if (!checkNullPointer(Info, E, CSK_ArrayIndex))
704         return;
705       Designator.adjustIndex(Info, E, N);
706     }
707   };
708 
709   struct MemberPtr {
710     MemberPtr() {}
711     explicit MemberPtr(const ValueDecl *Decl) :
712       DeclAndIsDerivedMember(Decl, false), Path() {}
713 
714     /// The member or (direct or indirect) field referred to by this member
715     /// pointer, or 0 if this is a null member pointer.
716     const ValueDecl *getDecl() const {
717       return DeclAndIsDerivedMember.getPointer();
718     }
719     /// Is this actually a member of some type derived from the relevant class?
720     bool isDerivedMember() const {
721       return DeclAndIsDerivedMember.getInt();
722     }
723     /// Get the class which the declaration actually lives in.
724     const CXXRecordDecl *getContainingRecord() const {
725       return cast<CXXRecordDecl>(
726           DeclAndIsDerivedMember.getPointer()->getDeclContext());
727     }
728 
729     void moveInto(CCValue &V) const {
730       V = CCValue(getDecl(), isDerivedMember(), Path);
731     }
732     void setFrom(const CCValue &V) {
733       assert(V.isMemberPointer());
734       DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
735       DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
736       Path.clear();
737       ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
738       Path.insert(Path.end(), P.begin(), P.end());
739     }
740 
741     /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
742     /// whether the member is a member of some class derived from the class type
743     /// of the member pointer.
744     llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
745     /// Path - The path of base/derived classes from the member declaration's
746     /// class (exclusive) to the class type of the member pointer (inclusive).
747     SmallVector<const CXXRecordDecl*, 4> Path;
748 
749     /// Perform a cast towards the class of the Decl (either up or down the
750     /// hierarchy).
751     bool castBack(const CXXRecordDecl *Class) {
752       assert(!Path.empty());
753       const CXXRecordDecl *Expected;
754       if (Path.size() >= 2)
755         Expected = Path[Path.size() - 2];
756       else
757         Expected = getContainingRecord();
758       if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
759         // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
760         // if B does not contain the original member and is not a base or
761         // derived class of the class containing the original member, the result
762         // of the cast is undefined.
763         // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
764         // (D::*). We consider that to be a language defect.
765         return false;
766       }
767       Path.pop_back();
768       return true;
769     }
770     /// Perform a base-to-derived member pointer cast.
771     bool castToDerived(const CXXRecordDecl *Derived) {
772       if (!getDecl())
773         return true;
774       if (!isDerivedMember()) {
775         Path.push_back(Derived);
776         return true;
777       }
778       if (!castBack(Derived))
779         return false;
780       if (Path.empty())
781         DeclAndIsDerivedMember.setInt(false);
782       return true;
783     }
784     /// Perform a derived-to-base member pointer cast.
785     bool castToBase(const CXXRecordDecl *Base) {
786       if (!getDecl())
787         return true;
788       if (Path.empty())
789         DeclAndIsDerivedMember.setInt(true);
790       if (isDerivedMember()) {
791         Path.push_back(Base);
792         return true;
793       }
794       return castBack(Base);
795     }
796   };
797 
798   /// Kinds of constant expression checking, for diagnostics.
799   enum CheckConstantExpressionKind {
800     CCEK_Constant,    ///< A normal constant.
801     CCEK_ReturnValue, ///< A constexpr function return value.
802     CCEK_MemberInit   ///< A constexpr constructor mem-initializer.
803   };
804 }
805 
806 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
807 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
808                                        const LValue &This, const Expr *E,
809                                        CheckConstantExpressionKind CCEK
810                                         = CCEK_Constant);
811 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
812 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
813 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
814                                   EvalInfo &Info);
815 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
816 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
817 static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
818                                     EvalInfo &Info);
819 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
820 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
821 
822 //===----------------------------------------------------------------------===//
823 // Misc utilities
824 //===----------------------------------------------------------------------===//
825 
826 /// Should this call expression be treated as a string literal?
827 static bool IsStringLiteralCall(const CallExpr *E) {
828   unsigned Builtin = E->isBuiltinCall();
829   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
830           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
831 }
832 
833 static bool IsGlobalLValue(APValue::LValueBase B) {
834   // C++11 [expr.const]p3 An address constant expression is a prvalue core
835   // constant expression of pointer type that evaluates to...
836 
837   // ... a null pointer value, or a prvalue core constant expression of type
838   // std::nullptr_t.
839   if (!B) return true;
840 
841   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
842     // ... the address of an object with static storage duration,
843     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
844       return VD->hasGlobalStorage();
845     // ... the address of a function,
846     return isa<FunctionDecl>(D);
847   }
848 
849   const Expr *E = B.get<const Expr*>();
850   switch (E->getStmtClass()) {
851   default:
852     return false;
853   case Expr::CompoundLiteralExprClass:
854     return cast<CompoundLiteralExpr>(E)->isFileScope();
855   // A string literal has static storage duration.
856   case Expr::StringLiteralClass:
857   case Expr::PredefinedExprClass:
858   case Expr::ObjCStringLiteralClass:
859   case Expr::ObjCEncodeExprClass:
860   case Expr::CXXTypeidExprClass:
861     return true;
862   case Expr::CallExprClass:
863     return IsStringLiteralCall(cast<CallExpr>(E));
864   // For GCC compatibility, &&label has static storage duration.
865   case Expr::AddrLabelExprClass:
866     return true;
867   // A Block literal expression may be used as the initialization value for
868   // Block variables at global or local static scope.
869   case Expr::BlockExprClass:
870     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
871   case Expr::ImplicitValueInitExprClass:
872     // FIXME:
873     // We can never form an lvalue with an implicit value initialization as its
874     // base through expression evaluation, so these only appear in one case: the
875     // implicit variable declaration we invent when checking whether a constexpr
876     // constructor can produce a constant expression. We must assume that such
877     // an expression might be a global lvalue.
878     return true;
879   }
880 }
881 
882 /// Check that this reference or pointer core constant expression is a valid
883 /// value for an address or reference constant expression. Type T should be
884 /// either LValue or CCValue. Return true if we can fold this expression,
885 /// whether or not it's a constant expression.
886 template<typename T>
887 static bool CheckLValueConstantExpression(EvalInfo &Info, const Expr *E,
888                                           const T &LVal, APValue &Value,
889                                           CheckConstantExpressionKind CCEK) {
890   APValue::LValueBase Base = LVal.getLValueBase();
891   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
892 
893   if (!IsGlobalLValue(Base)) {
894     if (Info.getLangOpts().CPlusPlus0x) {
895       const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
896       Info.Diag(E->getExprLoc(), diag::note_constexpr_non_global, 1)
897         << E->isGLValue() << !Designator.Entries.empty()
898         << !!VD << CCEK << VD;
899       if (VD)
900         Info.Note(VD->getLocation(), diag::note_declared_at);
901       else
902         Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
903                   diag::note_constexpr_temporary_here);
904     } else {
905       Info.Diag(E->getExprLoc());
906     }
907     // Don't allow references to temporaries to escape.
908     return false;
909   }
910 
911   bool IsReferenceType = E->isGLValue();
912 
913   if (Designator.Invalid) {
914     // This is not a core constant expression. An appropriate diagnostic will
915     // have already been produced.
916     Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
917                     APValue::NoLValuePath());
918     return true;
919   }
920 
921   Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
922                   Designator.Entries, Designator.IsOnePastTheEnd);
923 
924   // Allow address constant expressions to be past-the-end pointers. This is
925   // an extension: the standard requires them to point to an object.
926   if (!IsReferenceType)
927     return true;
928 
929   // A reference constant expression must refer to an object.
930   if (!Base) {
931     // FIXME: diagnostic
932     Info.CCEDiag(E->getExprLoc());
933     return true;
934   }
935 
936   // Does this refer one past the end of some object?
937   if (Designator.isOnePastTheEnd()) {
938     const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
939     Info.Diag(E->getExprLoc(), diag::note_constexpr_past_end, 1)
940       << !Designator.Entries.empty() << !!VD << VD;
941     if (VD)
942       Info.Note(VD->getLocation(), diag::note_declared_at);
943     else
944       Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
945                 diag::note_constexpr_temporary_here);
946   }
947 
948   return true;
949 }
950 
951 /// Check that this core constant expression is of literal type, and if not,
952 /// produce an appropriate diagnostic.
953 static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
954   if (!E->isRValue() || E->getType()->isLiteralType())
955     return true;
956 
957   // Prvalue constant expressions must be of literal types.
958   if (Info.getLangOpts().CPlusPlus0x)
959     Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
960       << E->getType();
961   else
962     Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
963   return false;
964 }
965 
966 /// Check that this core constant expression value is a valid value for a
967 /// constant expression, and if it is, produce the corresponding constant value.
968 /// If not, report an appropriate diagnostic. Does not check that the expression
969 /// is of literal type.
970 static bool CheckConstantExpression(EvalInfo &Info, const Expr *E,
971                                     const CCValue &CCValue, APValue &Value,
972                                     CheckConstantExpressionKind CCEK
973                                       = CCEK_Constant) {
974   if (!CCValue.isLValue()) {
975     Value = CCValue;
976     return true;
977   }
978   return CheckLValueConstantExpression(Info, E, CCValue, Value, CCEK);
979 }
980 
981 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
982   return LVal.Base.dyn_cast<const ValueDecl*>();
983 }
984 
985 static bool IsLiteralLValue(const LValue &Value) {
986   return Value.Base.dyn_cast<const Expr*>() && !Value.Frame;
987 }
988 
989 static bool IsWeakLValue(const LValue &Value) {
990   const ValueDecl *Decl = GetLValueBaseDecl(Value);
991   return Decl && Decl->isWeak();
992 }
993 
994 static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
995   // A null base expression indicates a null pointer.  These are always
996   // evaluatable, and they are false unless the offset is zero.
997   if (!Value.getLValueBase()) {
998     Result = !Value.getLValueOffset().isZero();
999     return true;
1000   }
1001 
1002   // We have a non-null base.  These are generally known to be true, but if it's
1003   // a weak declaration it can be null at runtime.
1004   Result = true;
1005   const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
1006   return !Decl || !Decl->isWeak();
1007 }
1008 
1009 static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
1010   switch (Val.getKind()) {
1011   case APValue::Uninitialized:
1012     return false;
1013   case APValue::Int:
1014     Result = Val.getInt().getBoolValue();
1015     return true;
1016   case APValue::Float:
1017     Result = !Val.getFloat().isZero();
1018     return true;
1019   case APValue::ComplexInt:
1020     Result = Val.getComplexIntReal().getBoolValue() ||
1021              Val.getComplexIntImag().getBoolValue();
1022     return true;
1023   case APValue::ComplexFloat:
1024     Result = !Val.getComplexFloatReal().isZero() ||
1025              !Val.getComplexFloatImag().isZero();
1026     return true;
1027   case APValue::LValue:
1028     return EvalPointerValueAsBool(Val, Result);
1029   case APValue::MemberPointer:
1030     Result = Val.getMemberPointerDecl();
1031     return true;
1032   case APValue::Vector:
1033   case APValue::Array:
1034   case APValue::Struct:
1035   case APValue::Union:
1036   case APValue::AddrLabelDiff:
1037     return false;
1038   }
1039 
1040   llvm_unreachable("unknown APValue kind");
1041 }
1042 
1043 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1044                                        EvalInfo &Info) {
1045   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
1046   CCValue Val;
1047   if (!Evaluate(Val, Info, E))
1048     return false;
1049   return HandleConversionToBool(Val, Result);
1050 }
1051 
1052 template<typename T>
1053 static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1054                            const T &SrcValue, QualType DestType) {
1055   llvm::SmallVector<char, 32> Buffer;
1056   SrcValue.toString(Buffer);
1057   Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
1058     << StringRef(Buffer.data(), Buffer.size()) << DestType;
1059   return false;
1060 }
1061 
1062 static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1063                                  QualType SrcType, const APFloat &Value,
1064                                  QualType DestType, APSInt &Result) {
1065   unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
1066   // Determine whether we are converting to unsigned or signed.
1067   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
1068 
1069   Result = APSInt(DestWidth, !DestSigned);
1070   bool ignored;
1071   if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1072       & APFloat::opInvalidOp)
1073     return HandleOverflow(Info, E, Value, DestType);
1074   return true;
1075 }
1076 
1077 static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1078                                    QualType SrcType, QualType DestType,
1079                                    APFloat &Result) {
1080   APFloat Value = Result;
1081   bool ignored;
1082   if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1083                      APFloat::rmNearestTiesToEven, &ignored)
1084       & APFloat::opOverflow)
1085     return HandleOverflow(Info, E, Value, DestType);
1086   return true;
1087 }
1088 
1089 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
1090                                  APSInt &Value, const ASTContext &Ctx) {
1091   unsigned DestWidth = Ctx.getIntWidth(DestType);
1092   APSInt Result = Value;
1093   // Figure out if this is a truncate, extend or noop cast.
1094   // If the input is signed, do a sign extend, noop, or truncate.
1095   Result = Result.extOrTrunc(DestWidth);
1096   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
1097   return Result;
1098 }
1099 
1100 static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1101                                  QualType SrcType, const APSInt &Value,
1102                                  QualType DestType, APFloat &Result) {
1103   Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1104   if (Result.convertFromAPInt(Value, Value.isSigned(),
1105                               APFloat::rmNearestTiesToEven)
1106       & APFloat::opOverflow)
1107     return HandleOverflow(Info, E, Value, DestType);
1108   return true;
1109 }
1110 
1111 static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1112                                   llvm::APInt &Res) {
1113   CCValue SVal;
1114   if (!Evaluate(SVal, Info, E))
1115     return false;
1116   if (SVal.isInt()) {
1117     Res = SVal.getInt();
1118     return true;
1119   }
1120   if (SVal.isFloat()) {
1121     Res = SVal.getFloat().bitcastToAPInt();
1122     return true;
1123   }
1124   if (SVal.isVector()) {
1125     QualType VecTy = E->getType();
1126     unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1127     QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1128     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1129     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1130     Res = llvm::APInt::getNullValue(VecSize);
1131     for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1132       APValue &Elt = SVal.getVectorElt(i);
1133       llvm::APInt EltAsInt;
1134       if (Elt.isInt()) {
1135         EltAsInt = Elt.getInt();
1136       } else if (Elt.isFloat()) {
1137         EltAsInt = Elt.getFloat().bitcastToAPInt();
1138       } else {
1139         // Don't try to handle vectors of anything other than int or float
1140         // (not sure if it's possible to hit this case).
1141         Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1142         return false;
1143       }
1144       unsigned BaseEltSize = EltAsInt.getBitWidth();
1145       if (BigEndian)
1146         Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1147       else
1148         Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1149     }
1150     return true;
1151   }
1152   // Give up if the input isn't an int, float, or vector.  For example, we
1153   // reject "(v4i16)(intptr_t)&a".
1154   Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1155   return false;
1156 }
1157 
1158 /// Cast an lvalue referring to a base subobject to a derived class, by
1159 /// truncating the lvalue's path to the given length.
1160 static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1161                                const RecordDecl *TruncatedType,
1162                                unsigned TruncatedElements) {
1163   SubobjectDesignator &D = Result.Designator;
1164 
1165   // Check we actually point to a derived class object.
1166   if (TruncatedElements == D.Entries.size())
1167     return true;
1168   assert(TruncatedElements >= D.MostDerivedPathLength &&
1169          "not casting to a derived class");
1170   if (!Result.checkSubobject(Info, E, CSK_Derived))
1171     return false;
1172 
1173   // Truncate the path to the subobject, and remove any derived-to-base offsets.
1174   const RecordDecl *RD = TruncatedType;
1175   for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
1176     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1177     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
1178     if (isVirtualBaseClass(D.Entries[I]))
1179       Result.Offset -= Layout.getVBaseClassOffset(Base);
1180     else
1181       Result.Offset -= Layout.getBaseClassOffset(Base);
1182     RD = Base;
1183   }
1184   D.Entries.resize(TruncatedElements);
1185   return true;
1186 }
1187 
1188 static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1189                                    const CXXRecordDecl *Derived,
1190                                    const CXXRecordDecl *Base,
1191                                    const ASTRecordLayout *RL = 0) {
1192   if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1193   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
1194   Obj.addDecl(Info, E, Base, /*Virtual*/ false);
1195 }
1196 
1197 static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
1198                              const CXXRecordDecl *DerivedDecl,
1199                              const CXXBaseSpecifier *Base) {
1200   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1201 
1202   if (!Base->isVirtual()) {
1203     HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
1204     return true;
1205   }
1206 
1207   SubobjectDesignator &D = Obj.Designator;
1208   if (D.Invalid)
1209     return false;
1210 
1211   // Extract most-derived object and corresponding type.
1212   DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1213   if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1214     return false;
1215 
1216   // Find the virtual base class.
1217   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1218   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
1219   Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
1220   return true;
1221 }
1222 
1223 /// Update LVal to refer to the given field, which must be a member of the type
1224 /// currently described by LVal.
1225 static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
1226                                const FieldDecl *FD,
1227                                const ASTRecordLayout *RL = 0) {
1228   if (!RL)
1229     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1230 
1231   unsigned I = FD->getFieldIndex();
1232   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
1233   LVal.addDecl(Info, E, FD);
1234 }
1235 
1236 /// Update LVal to refer to the given indirect field.
1237 static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1238                                        LValue &LVal,
1239                                        const IndirectFieldDecl *IFD) {
1240   for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1241                                          CE = IFD->chain_end(); C != CE; ++C)
1242     HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1243 }
1244 
1245 /// Get the size of the given type in char units.
1246 static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
1247   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1248   // extension.
1249   if (Type->isVoidType() || Type->isFunctionType()) {
1250     Size = CharUnits::One();
1251     return true;
1252   }
1253 
1254   if (!Type->isConstantSizeType()) {
1255     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1256     // FIXME: Diagnostic.
1257     return false;
1258   }
1259 
1260   Size = Info.Ctx.getTypeSizeInChars(Type);
1261   return true;
1262 }
1263 
1264 /// Update a pointer value to model pointer arithmetic.
1265 /// \param Info - Information about the ongoing evaluation.
1266 /// \param E - The expression being evaluated, for diagnostic purposes.
1267 /// \param LVal - The pointer value to be updated.
1268 /// \param EltTy - The pointee type represented by LVal.
1269 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
1270 static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1271                                         LValue &LVal, QualType EltTy,
1272                                         int64_t Adjustment) {
1273   CharUnits SizeOfPointee;
1274   if (!HandleSizeof(Info, EltTy, SizeOfPointee))
1275     return false;
1276 
1277   // Compute the new offset in the appropriate width.
1278   LVal.Offset += Adjustment * SizeOfPointee;
1279   LVal.adjustIndex(Info, E, Adjustment);
1280   return true;
1281 }
1282 
1283 /// Try to evaluate the initializer for a variable declaration.
1284 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1285                                 const VarDecl *VD,
1286                                 CallStackFrame *Frame, CCValue &Result) {
1287   // If this is a parameter to an active constexpr function call, perform
1288   // argument substitution.
1289   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
1290     // Assume arguments of a potential constant expression are unknown
1291     // constant expressions.
1292     if (Info.CheckingPotentialConstantExpression)
1293       return false;
1294     if (!Frame || !Frame->Arguments) {
1295       Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1296       return false;
1297     }
1298     Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1299     return true;
1300   }
1301 
1302   // Dig out the initializer, and use the declaration which it's attached to.
1303   const Expr *Init = VD->getAnyInitializer(VD);
1304   if (!Init || Init->isValueDependent()) {
1305     // If we're checking a potential constant expression, the variable could be
1306     // initialized later.
1307     if (!Info.CheckingPotentialConstantExpression)
1308       Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1309     return false;
1310   }
1311 
1312   // If we're currently evaluating the initializer of this declaration, use that
1313   // in-flight value.
1314   if (Info.EvaluatingDecl == VD) {
1315     Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1316                      CCValue::GlobalValue());
1317     return !Result.isUninit();
1318   }
1319 
1320   // Never evaluate the initializer of a weak variable. We can't be sure that
1321   // this is the definition which will be used.
1322   if (VD->isWeak()) {
1323     Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1324     return false;
1325   }
1326 
1327   // Check that we can fold the initializer. In C++, we will have already done
1328   // this in the cases where it matters for conformance.
1329   llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1330   if (!VD->evaluateValue(Notes)) {
1331     Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1332               Notes.size() + 1) << VD;
1333     Info.Note(VD->getLocation(), diag::note_declared_at);
1334     Info.addNotes(Notes);
1335     return false;
1336   } else if (!VD->checkInitIsICE()) {
1337     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1338                  Notes.size() + 1) << VD;
1339     Info.Note(VD->getLocation(), diag::note_declared_at);
1340     Info.addNotes(Notes);
1341   }
1342 
1343   Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
1344   return true;
1345 }
1346 
1347 static bool IsConstNonVolatile(QualType T) {
1348   Qualifiers Quals = T.getQualifiers();
1349   return Quals.hasConst() && !Quals.hasVolatile();
1350 }
1351 
1352 /// Get the base index of the given base class within an APValue representing
1353 /// the given derived class.
1354 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1355                              const CXXRecordDecl *Base) {
1356   Base = Base->getCanonicalDecl();
1357   unsigned Index = 0;
1358   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1359          E = Derived->bases_end(); I != E; ++I, ++Index) {
1360     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1361       return Index;
1362   }
1363 
1364   llvm_unreachable("base class missing from derived class's bases list");
1365 }
1366 
1367 /// Extract the designated sub-object of an rvalue.
1368 static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1369                              CCValue &Obj, QualType ObjType,
1370                              const SubobjectDesignator &Sub, QualType SubType) {
1371   if (Sub.Invalid)
1372     // A diagnostic will have already been produced.
1373     return false;
1374   if (Sub.isOnePastTheEnd()) {
1375     Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1376                 (unsigned)diag::note_constexpr_read_past_end :
1377                 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1378     return false;
1379   }
1380   if (Sub.Entries.empty())
1381     return true;
1382   if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1383     // This object might be initialized later.
1384     return false;
1385 
1386   assert(!Obj.isLValue() && "extracting subobject of lvalue");
1387   const APValue *O = &Obj;
1388   // Walk the designator's path to find the subobject.
1389   for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
1390     if (ObjType->isArrayType()) {
1391       // Next subobject is an array element.
1392       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
1393       assert(CAT && "vla in literal type?");
1394       uint64_t Index = Sub.Entries[I].ArrayIndex;
1395       if (CAT->getSize().ule(Index)) {
1396         // Note, it should not be possible to form a pointer with a valid
1397         // designator which points more than one past the end of the array.
1398         Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1399                     (unsigned)diag::note_constexpr_read_past_end :
1400                     (unsigned)diag::note_invalid_subexpr_in_const_expr);
1401         return false;
1402       }
1403       if (O->getArrayInitializedElts() > Index)
1404         O = &O->getArrayInitializedElt(Index);
1405       else
1406         O = &O->getArrayFiller();
1407       ObjType = CAT->getElementType();
1408     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
1409       // Next subobject is a class, struct or union field.
1410       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1411       if (RD->isUnion()) {
1412         const FieldDecl *UnionField = O->getUnionField();
1413         if (!UnionField ||
1414             UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
1415           Info.Diag(E->getExprLoc(),
1416                     diag::note_constexpr_read_inactive_union_member)
1417             << Field << !UnionField << UnionField;
1418           return false;
1419         }
1420         O = &O->getUnionValue();
1421       } else
1422         O = &O->getStructField(Field->getFieldIndex());
1423       ObjType = Field->getType();
1424 
1425       if (ObjType.isVolatileQualified()) {
1426         if (Info.getLangOpts().CPlusPlus) {
1427           // FIXME: Include a description of the path to the volatile subobject.
1428           Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1429             << 2 << Field;
1430           Info.Note(Field->getLocation(), diag::note_declared_at);
1431         } else {
1432           Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1433         }
1434         return false;
1435       }
1436     } else {
1437       // Next subobject is a base class.
1438       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1439       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1440       O = &O->getStructBase(getBaseIndex(Derived, Base));
1441       ObjType = Info.Ctx.getRecordType(Base);
1442     }
1443 
1444     if (O->isUninit()) {
1445       if (!Info.CheckingPotentialConstantExpression)
1446         Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
1447       return false;
1448     }
1449   }
1450 
1451   Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
1452   return true;
1453 }
1454 
1455 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1456 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1457 /// for looking up the glvalue referred to by an entity of reference type.
1458 ///
1459 /// \param Info - Information about the ongoing evaluation.
1460 /// \param Conv - The expression for which we are performing the conversion.
1461 ///               Used for diagnostics.
1462 /// \param Type - The type we expect this conversion to produce.
1463 /// \param LVal - The glvalue on which we are attempting to perform this action.
1464 /// \param RVal - The produced value will be placed here.
1465 static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1466                                            QualType Type,
1467                                            const LValue &LVal, CCValue &RVal) {
1468   // In C, an lvalue-to-rvalue conversion is never a constant expression.
1469   if (!Info.getLangOpts().CPlusPlus)
1470     Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1471 
1472   if (LVal.Designator.Invalid)
1473     // A diagnostic will have already been produced.
1474     return false;
1475 
1476   const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
1477   CallStackFrame *Frame = LVal.Frame;
1478   SourceLocation Loc = Conv->getExprLoc();
1479 
1480   if (!LVal.Base) {
1481     // FIXME: Indirection through a null pointer deserves a specific diagnostic.
1482     Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1483     return false;
1484   }
1485 
1486   // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1487   // is not a constant expression (even if the object is non-volatile). We also
1488   // apply this rule to C++98, in order to conform to the expected 'volatile'
1489   // semantics.
1490   if (Type.isVolatileQualified()) {
1491     if (Info.getLangOpts().CPlusPlus)
1492       Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1493     else
1494       Info.Diag(Loc);
1495     return false;
1496   }
1497 
1498   if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
1499     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1500     // In C++11, constexpr, non-volatile variables initialized with constant
1501     // expressions are constant expressions too. Inside constexpr functions,
1502     // parameters are constant expressions even if they're non-const.
1503     // In C, such things can also be folded, although they are not ICEs.
1504     const VarDecl *VD = dyn_cast<VarDecl>(D);
1505     if (!VD || VD->isInvalidDecl()) {
1506       Info.Diag(Loc);
1507       return false;
1508     }
1509 
1510     // DR1313: If the object is volatile-qualified but the glvalue was not,
1511     // behavior is undefined so the result is not a constant expression.
1512     QualType VT = VD->getType();
1513     if (VT.isVolatileQualified()) {
1514       if (Info.getLangOpts().CPlusPlus) {
1515         Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1516         Info.Note(VD->getLocation(), diag::note_declared_at);
1517       } else {
1518         Info.Diag(Loc);
1519       }
1520       return false;
1521     }
1522 
1523     if (!isa<ParmVarDecl>(VD)) {
1524       if (VD->isConstexpr()) {
1525         // OK, we can read this variable.
1526       } else if (VT->isIntegralOrEnumerationType()) {
1527         if (!VT.isConstQualified()) {
1528           if (Info.getLangOpts().CPlusPlus) {
1529             Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1530             Info.Note(VD->getLocation(), diag::note_declared_at);
1531           } else {
1532             Info.Diag(Loc);
1533           }
1534           return false;
1535         }
1536       } else if (VT->isFloatingType() && VT.isConstQualified()) {
1537         // We support folding of const floating-point types, in order to make
1538         // static const data members of such types (supported as an extension)
1539         // more useful.
1540         if (Info.getLangOpts().CPlusPlus0x) {
1541           Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1542           Info.Note(VD->getLocation(), diag::note_declared_at);
1543         } else {
1544           Info.CCEDiag(Loc);
1545         }
1546       } else {
1547         // FIXME: Allow folding of values of any literal type in all languages.
1548         if (Info.getLangOpts().CPlusPlus0x) {
1549           Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1550           Info.Note(VD->getLocation(), diag::note_declared_at);
1551         } else {
1552           Info.Diag(Loc);
1553         }
1554         return false;
1555       }
1556     }
1557 
1558     if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
1559       return false;
1560 
1561     if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
1562       return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
1563 
1564     // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1565     // conversion. This happens when the declaration and the lvalue should be
1566     // considered synonymous, for instance when initializing an array of char
1567     // from a string literal. Continue as if the initializer lvalue was the
1568     // value we were originally given.
1569     assert(RVal.getLValueOffset().isZero() &&
1570            "offset for lvalue init of non-reference");
1571     Base = RVal.getLValueBase().get<const Expr*>();
1572     Frame = RVal.getLValueFrame();
1573   }
1574 
1575   // Volatile temporary objects cannot be read in constant expressions.
1576   if (Base->getType().isVolatileQualified()) {
1577     if (Info.getLangOpts().CPlusPlus) {
1578       Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1579       Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1580     } else {
1581       Info.Diag(Loc);
1582     }
1583     return false;
1584   }
1585 
1586   // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1587   if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
1588     const SubobjectDesignator &Designator = LVal.Designator;
1589     if (Designator.Invalid || Designator.Entries.size() != 1) {
1590       Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1591       return false;
1592     }
1593 
1594     assert(Type->isIntegerType() && "string element not integer type");
1595     uint64_t Index = Designator.Entries[0].ArrayIndex;
1596     const ConstantArrayType *CAT =
1597         Info.Ctx.getAsConstantArrayType(S->getType());
1598     if (Index >= CAT->getSize().getZExtValue()) {
1599       // Note, it should not be possible to form a pointer which points more
1600       // than one past the end of the array without producing a prior const expr
1601       // diagnostic.
1602       Info.Diag(Loc, diag::note_constexpr_read_past_end);
1603       return false;
1604     }
1605     APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1606                  Type->isUnsignedIntegerType());
1607     if (Index < S->getLength())
1608       Value = S->getCodeUnit(Index);
1609     RVal = CCValue(Value);
1610     return true;
1611   }
1612 
1613   if (Frame) {
1614     // If this is a temporary expression with a nontrivial initializer, grab the
1615     // value from the relevant stack frame.
1616     RVal = Frame->Temporaries[Base];
1617   } else if (const CompoundLiteralExpr *CLE
1618              = dyn_cast<CompoundLiteralExpr>(Base)) {
1619     // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1620     // initializer until now for such expressions. Such an expression can't be
1621     // an ICE in C, so this only matters for fold.
1622     assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1623     if (!Evaluate(RVal, Info, CLE->getInitializer()))
1624       return false;
1625   } else {
1626     Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1627     return false;
1628   }
1629 
1630   return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1631                           Type);
1632 }
1633 
1634 /// Build an lvalue for the object argument of a member function call.
1635 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1636                                    LValue &This) {
1637   if (Object->getType()->isPointerType())
1638     return EvaluatePointer(Object, This, Info);
1639 
1640   if (Object->isGLValue())
1641     return EvaluateLValue(Object, This, Info);
1642 
1643   if (Object->getType()->isLiteralType())
1644     return EvaluateTemporary(Object, This, Info);
1645 
1646   return false;
1647 }
1648 
1649 /// HandleMemberPointerAccess - Evaluate a member access operation and build an
1650 /// lvalue referring to the result.
1651 ///
1652 /// \param Info - Information about the ongoing evaluation.
1653 /// \param BO - The member pointer access operation.
1654 /// \param LV - Filled in with a reference to the resulting object.
1655 /// \param IncludeMember - Specifies whether the member itself is included in
1656 ///        the resulting LValue subobject designator. This is not possible when
1657 ///        creating a bound member function.
1658 /// \return The field or method declaration to which the member pointer refers,
1659 ///         or 0 if evaluation fails.
1660 static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1661                                                   const BinaryOperator *BO,
1662                                                   LValue &LV,
1663                                                   bool IncludeMember = true) {
1664   assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1665 
1666   bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1667   if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
1668     return 0;
1669 
1670   MemberPtr MemPtr;
1671   if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1672     return 0;
1673 
1674   // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1675   // member value, the behavior is undefined.
1676   if (!MemPtr.getDecl())
1677     return 0;
1678 
1679   if (!EvalObjOK)
1680     return 0;
1681 
1682   if (MemPtr.isDerivedMember()) {
1683     // This is a member of some derived class. Truncate LV appropriately.
1684     // The end of the derived-to-base path for the base object must match the
1685     // derived-to-base path for the member pointer.
1686     if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
1687         LV.Designator.Entries.size())
1688       return 0;
1689     unsigned PathLengthToMember =
1690         LV.Designator.Entries.size() - MemPtr.Path.size();
1691     for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1692       const CXXRecordDecl *LVDecl = getAsBaseClass(
1693           LV.Designator.Entries[PathLengthToMember + I]);
1694       const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1695       if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1696         return 0;
1697     }
1698 
1699     // Truncate the lvalue to the appropriate derived class.
1700     if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1701                             PathLengthToMember))
1702       return 0;
1703   } else if (!MemPtr.Path.empty()) {
1704     // Extend the LValue path with the member pointer's path.
1705     LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1706                                   MemPtr.Path.size() + IncludeMember);
1707 
1708     // Walk down to the appropriate base class.
1709     QualType LVType = BO->getLHS()->getType();
1710     if (const PointerType *PT = LVType->getAs<PointerType>())
1711       LVType = PT->getPointeeType();
1712     const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1713     assert(RD && "member pointer access on non-class-type expression");
1714     // The first class in the path is that of the lvalue.
1715     for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1716       const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
1717       HandleLValueDirectBase(Info, BO, LV, RD, Base);
1718       RD = Base;
1719     }
1720     // Finally cast to the class containing the member.
1721     HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
1722   }
1723 
1724   // Add the member. Note that we cannot build bound member functions here.
1725   if (IncludeMember) {
1726     if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1727       HandleLValueMember(Info, BO, LV, FD);
1728     else if (const IndirectFieldDecl *IFD =
1729                dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1730       HandleLValueIndirectMember(Info, BO, LV, IFD);
1731     else
1732       llvm_unreachable("can't construct reference to bound member function");
1733   }
1734 
1735   return MemPtr.getDecl();
1736 }
1737 
1738 /// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1739 /// the provided lvalue, which currently refers to the base object.
1740 static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1741                                     LValue &Result) {
1742   SubobjectDesignator &D = Result.Designator;
1743   if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
1744     return false;
1745 
1746   QualType TargetQT = E->getType();
1747   if (const PointerType *PT = TargetQT->getAs<PointerType>())
1748     TargetQT = PT->getPointeeType();
1749 
1750   // Check this cast lands within the final derived-to-base subobject path.
1751   if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
1752     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1753       << D.MostDerivedType << TargetQT;
1754     return false;
1755   }
1756 
1757   // Check the type of the final cast. We don't need to check the path,
1758   // since a cast can only be formed if the path is unique.
1759   unsigned NewEntriesSize = D.Entries.size() - E->path_size();
1760   const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1761   const CXXRecordDecl *FinalType;
1762   if (NewEntriesSize == D.MostDerivedPathLength)
1763     FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1764   else
1765     FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
1766   if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
1767     Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
1768       << D.MostDerivedType << TargetQT;
1769     return false;
1770   }
1771 
1772   // Truncate the lvalue to the appropriate derived class.
1773   return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
1774 }
1775 
1776 namespace {
1777 enum EvalStmtResult {
1778   /// Evaluation failed.
1779   ESR_Failed,
1780   /// Hit a 'return' statement.
1781   ESR_Returned,
1782   /// Evaluation succeeded.
1783   ESR_Succeeded
1784 };
1785 }
1786 
1787 // Evaluate a statement.
1788 static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
1789                                    const Stmt *S) {
1790   switch (S->getStmtClass()) {
1791   default:
1792     return ESR_Failed;
1793 
1794   case Stmt::NullStmtClass:
1795   case Stmt::DeclStmtClass:
1796     return ESR_Succeeded;
1797 
1798   case Stmt::ReturnStmtClass: {
1799     CCValue CCResult;
1800     const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
1801     if (!Evaluate(CCResult, Info, RetExpr) ||
1802         !CheckConstantExpression(Info, RetExpr, CCResult, Result,
1803                                  CCEK_ReturnValue))
1804       return ESR_Failed;
1805     return ESR_Returned;
1806   }
1807 
1808   case Stmt::CompoundStmtClass: {
1809     const CompoundStmt *CS = cast<CompoundStmt>(S);
1810     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1811            BE = CS->body_end(); BI != BE; ++BI) {
1812       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1813       if (ESR != ESR_Succeeded)
1814         return ESR;
1815     }
1816     return ESR_Succeeded;
1817   }
1818   }
1819 }
1820 
1821 /// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
1822 /// default constructor. If so, we'll fold it whether or not it's marked as
1823 /// constexpr. If it is marked as constexpr, we will never implicitly define it,
1824 /// so we need special handling.
1825 static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
1826                                            const CXXConstructorDecl *CD,
1827                                            bool IsValueInitialization) {
1828   if (!CD->isTrivial() || !CD->isDefaultConstructor())
1829     return false;
1830 
1831   // Value-initialization does not call a trivial default constructor, so such a
1832   // call is a core constant expression whether or not the constructor is
1833   // constexpr.
1834   if (!CD->isConstexpr() && !IsValueInitialization) {
1835     if (Info.getLangOpts().CPlusPlus0x) {
1836       // FIXME: If DiagDecl is an implicitly-declared special member function,
1837       // we should be much more explicit about why it's not constexpr.
1838       Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
1839         << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
1840       Info.Note(CD->getLocation(), diag::note_declared_at);
1841     } else {
1842       Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
1843     }
1844   }
1845   return true;
1846 }
1847 
1848 /// CheckConstexprFunction - Check that a function can be called in a constant
1849 /// expression.
1850 static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
1851                                    const FunctionDecl *Declaration,
1852                                    const FunctionDecl *Definition) {
1853   // Potential constant expressions can contain calls to declared, but not yet
1854   // defined, constexpr functions.
1855   if (Info.CheckingPotentialConstantExpression && !Definition &&
1856       Declaration->isConstexpr())
1857     return false;
1858 
1859   // Can we evaluate this function call?
1860   if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
1861     return true;
1862 
1863   if (Info.getLangOpts().CPlusPlus0x) {
1864     const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
1865     // FIXME: If DiagDecl is an implicitly-declared special member function, we
1866     // should be much more explicit about why it's not constexpr.
1867     Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
1868       << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
1869       << DiagDecl;
1870     Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
1871   } else {
1872     Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
1873   }
1874   return false;
1875 }
1876 
1877 namespace {
1878 typedef SmallVector<CCValue, 8> ArgVector;
1879 }
1880 
1881 /// EvaluateArgs - Evaluate the arguments to a function call.
1882 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1883                          EvalInfo &Info) {
1884   bool Success = true;
1885   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1886        I != E; ++I) {
1887     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
1888       // If we're checking for a potential constant expression, evaluate all
1889       // initializers even if some of them fail.
1890       if (!Info.keepEvaluatingAfterFailure())
1891         return false;
1892       Success = false;
1893     }
1894   }
1895   return Success;
1896 }
1897 
1898 /// Evaluate a function call.
1899 static bool HandleFunctionCall(SourceLocation CallLoc,
1900                                const FunctionDecl *Callee, const LValue *This,
1901                                ArrayRef<const Expr*> Args, const Stmt *Body,
1902                                EvalInfo &Info, APValue &Result) {
1903   ArgVector ArgValues(Args.size());
1904   if (!EvaluateArgs(Args, ArgValues, Info))
1905     return false;
1906 
1907   if (!Info.CheckCallLimit(CallLoc))
1908     return false;
1909 
1910   CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
1911   return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1912 }
1913 
1914 /// Evaluate a constructor call.
1915 static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
1916                                   ArrayRef<const Expr*> Args,
1917                                   const CXXConstructorDecl *Definition,
1918                                   EvalInfo &Info, APValue &Result) {
1919   ArgVector ArgValues(Args.size());
1920   if (!EvaluateArgs(Args, ArgValues, Info))
1921     return false;
1922 
1923   if (!Info.CheckCallLimit(CallLoc))
1924     return false;
1925 
1926   CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
1927 
1928   // If it's a delegating constructor, just delegate.
1929   if (Definition->isDelegatingConstructor()) {
1930     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1931     return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1932   }
1933 
1934   // For a trivial copy or move constructor, perform an APValue copy. This is
1935   // essential for unions, where the operations performed by the constructor
1936   // cannot be represented by ctor-initializers.
1937   const CXXRecordDecl *RD = Definition->getParent();
1938   if (Definition->isDefaulted() &&
1939       ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
1940        (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
1941     LValue RHS;
1942     RHS.setFrom(ArgValues[0]);
1943     CCValue Value;
1944     if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
1945                                         RHS, Value))
1946       return false;
1947     assert((Value.isStruct() || Value.isUnion()) &&
1948            "trivial copy/move from non-class type?");
1949     // Any CCValue of class type must already be a constant expression.
1950     Result = Value;
1951     return true;
1952   }
1953 
1954   // Reserve space for the struct members.
1955   if (!RD->isUnion() && Result.isUninit())
1956     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1957                      std::distance(RD->field_begin(), RD->field_end()));
1958 
1959   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1960 
1961   bool Success = true;
1962   unsigned BasesSeen = 0;
1963 #ifndef NDEBUG
1964   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1965 #endif
1966   for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1967        E = Definition->init_end(); I != E; ++I) {
1968     LValue Subobject = This;
1969     APValue *Value = &Result;
1970 
1971     // Determine the subobject to initialize.
1972     if ((*I)->isBaseInitializer()) {
1973       QualType BaseType((*I)->getBaseClass(), 0);
1974 #ifndef NDEBUG
1975       // Non-virtual base classes are initialized in the order in the class
1976       // definition. We cannot have a virtual base class for a literal type.
1977       assert(!BaseIt->isVirtual() && "virtual base for literal type");
1978       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1979              "base class initializers not in expected order");
1980       ++BaseIt;
1981 #endif
1982       HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
1983                              BaseType->getAsCXXRecordDecl(), &Layout);
1984       Value = &Result.getStructBase(BasesSeen++);
1985     } else if (FieldDecl *FD = (*I)->getMember()) {
1986       HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
1987       if (RD->isUnion()) {
1988         Result = APValue(FD);
1989         Value = &Result.getUnionValue();
1990       } else {
1991         Value = &Result.getStructField(FD->getFieldIndex());
1992       }
1993     } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
1994       // Walk the indirect field decl's chain to find the object to initialize,
1995       // and make sure we've initialized every step along it.
1996       for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1997                                              CE = IFD->chain_end();
1998            C != CE; ++C) {
1999         FieldDecl *FD = cast<FieldDecl>(*C);
2000         CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2001         // Switch the union field if it differs. This happens if we had
2002         // preceding zero-initialization, and we're now initializing a union
2003         // subobject other than the first.
2004         // FIXME: In this case, the values of the other subobjects are
2005         // specified, since zero-initialization sets all padding bits to zero.
2006         if (Value->isUninit() ||
2007             (Value->isUnion() && Value->getUnionField() != FD)) {
2008           if (CD->isUnion())
2009             *Value = APValue(FD);
2010           else
2011             *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2012                              std::distance(CD->field_begin(), CD->field_end()));
2013         }
2014         HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
2015         if (CD->isUnion())
2016           Value = &Value->getUnionValue();
2017         else
2018           Value = &Value->getStructField(FD->getFieldIndex());
2019       }
2020     } else {
2021       llvm_unreachable("unknown base initializer kind");
2022     }
2023 
2024     if (!EvaluateConstantExpression(*Value, Info, Subobject, (*I)->getInit(),
2025                                     (*I)->isBaseInitializer()
2026                                       ? CCEK_Constant : CCEK_MemberInit)) {
2027       // If we're checking for a potential constant expression, evaluate all
2028       // initializers even if some of them fail.
2029       if (!Info.keepEvaluatingAfterFailure())
2030         return false;
2031       Success = false;
2032     }
2033   }
2034 
2035   return Success;
2036 }
2037 
2038 namespace {
2039 class HasSideEffect
2040   : public ConstStmtVisitor<HasSideEffect, bool> {
2041   const ASTContext &Ctx;
2042 public:
2043 
2044   HasSideEffect(const ASTContext &C) : Ctx(C) {}
2045 
2046   // Unhandled nodes conservatively default to having side effects.
2047   bool VisitStmt(const Stmt *S) {
2048     return true;
2049   }
2050 
2051   bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2052   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
2053     return Visit(E->getResultExpr());
2054   }
2055   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2056     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2057       return true;
2058     return false;
2059   }
2060   bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
2061     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2062       return true;
2063     return false;
2064   }
2065   bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
2066     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2067       return true;
2068     return false;
2069   }
2070 
2071   // We don't want to evaluate BlockExprs multiple times, as they generate
2072   // a ton of code.
2073   bool VisitBlockExpr(const BlockExpr *E) { return true; }
2074   bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2075   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
2076     { return Visit(E->getInitializer()); }
2077   bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2078   bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2079   bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2080   bool VisitStringLiteral(const StringLiteral *E) { return false; }
2081   bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2082   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
2083     { return false; }
2084   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
2085     { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2086   bool VisitChooseExpr(const ChooseExpr *E)
2087     { return Visit(E->getChosenSubExpr(Ctx)); }
2088   bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2089   bool VisitBinAssign(const BinaryOperator *E) { return true; }
2090   bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2091   bool VisitBinaryOperator(const BinaryOperator *E)
2092   { return Visit(E->getLHS()) || Visit(E->getRHS()); }
2093   bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2094   bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2095   bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2096   bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2097   bool VisitUnaryDeref(const UnaryOperator *E) {
2098     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
2099       return true;
2100     return Visit(E->getSubExpr());
2101   }
2102   bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
2103 
2104   // Has side effects if any element does.
2105   bool VisitInitListExpr(const InitListExpr *E) {
2106     for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2107       if (Visit(E->getInit(i))) return true;
2108     if (const Expr *filler = E->getArrayFiller())
2109       return Visit(filler);
2110     return false;
2111   }
2112 
2113   bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
2114 };
2115 
2116 class OpaqueValueEvaluation {
2117   EvalInfo &info;
2118   OpaqueValueExpr *opaqueValue;
2119 
2120 public:
2121   OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2122                         Expr *value)
2123     : info(info), opaqueValue(opaqueValue) {
2124 
2125     // If evaluation fails, fail immediately.
2126     if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
2127       this->opaqueValue = 0;
2128       return;
2129     }
2130   }
2131 
2132   bool hasError() const { return opaqueValue == 0; }
2133 
2134   ~OpaqueValueEvaluation() {
2135     // FIXME: This will not work for recursive constexpr functions using opaque
2136     // values. Restore the former value.
2137     if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2138   }
2139 };
2140 
2141 } // end anonymous namespace
2142 
2143 //===----------------------------------------------------------------------===//
2144 // Generic Evaluation
2145 //===----------------------------------------------------------------------===//
2146 namespace {
2147 
2148 // FIXME: RetTy is always bool. Remove it.
2149 template <class Derived, typename RetTy=bool>
2150 class ExprEvaluatorBase
2151   : public ConstStmtVisitor<Derived, RetTy> {
2152 private:
2153   RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
2154     return static_cast<Derived*>(this)->Success(V, E);
2155   }
2156   RetTy DerivedZeroInitialization(const Expr *E) {
2157     return static_cast<Derived*>(this)->ZeroInitialization(E);
2158   }
2159 
2160 protected:
2161   EvalInfo &Info;
2162   typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2163   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2164 
2165   OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
2166     return Info.CCEDiag(E->getExprLoc(), D);
2167   }
2168 
2169   /// Report an evaluation error. This should only be called when an error is
2170   /// first discovered. When propagating an error, just return false.
2171   bool Error(const Expr *E, diag::kind D) {
2172     Info.Diag(E->getExprLoc(), D);
2173     return false;
2174   }
2175   bool Error(const Expr *E) {
2176     return Error(E, diag::note_invalid_subexpr_in_const_expr);
2177   }
2178 
2179   RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2180 
2181 public:
2182   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2183 
2184   RetTy VisitStmt(const Stmt *) {
2185     llvm_unreachable("Expression evaluator should not be called on stmts");
2186   }
2187   RetTy VisitExpr(const Expr *E) {
2188     return Error(E);
2189   }
2190 
2191   RetTy VisitParenExpr(const ParenExpr *E)
2192     { return StmtVisitorTy::Visit(E->getSubExpr()); }
2193   RetTy VisitUnaryExtension(const UnaryOperator *E)
2194     { return StmtVisitorTy::Visit(E->getSubExpr()); }
2195   RetTy VisitUnaryPlus(const UnaryOperator *E)
2196     { return StmtVisitorTy::Visit(E->getSubExpr()); }
2197   RetTy VisitChooseExpr(const ChooseExpr *E)
2198     { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2199   RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2200     { return StmtVisitorTy::Visit(E->getResultExpr()); }
2201   RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2202     { return StmtVisitorTy::Visit(E->getReplacement()); }
2203   RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2204     { return StmtVisitorTy::Visit(E->getExpr()); }
2205   // We cannot create any objects for which cleanups are required, so there is
2206   // nothing to do here; all cleanups must come from unevaluated subexpressions.
2207   RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2208     { return StmtVisitorTy::Visit(E->getSubExpr()); }
2209 
2210   RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2211     CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2212     return static_cast<Derived*>(this)->VisitCastExpr(E);
2213   }
2214   RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2215     CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2216     return static_cast<Derived*>(this)->VisitCastExpr(E);
2217   }
2218 
2219   RetTy VisitBinaryOperator(const BinaryOperator *E) {
2220     switch (E->getOpcode()) {
2221     default:
2222       return Error(E);
2223 
2224     case BO_Comma:
2225       VisitIgnoredValue(E->getLHS());
2226       return StmtVisitorTy::Visit(E->getRHS());
2227 
2228     case BO_PtrMemD:
2229     case BO_PtrMemI: {
2230       LValue Obj;
2231       if (!HandleMemberPointerAccess(Info, E, Obj))
2232         return false;
2233       CCValue Result;
2234       if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
2235         return false;
2236       return DerivedSuccess(Result, E);
2237     }
2238     }
2239   }
2240 
2241   RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
2242     OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2243     if (opaque.hasError())
2244       return false;
2245 
2246     bool cond;
2247     if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
2248       return false;
2249 
2250     return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
2251   }
2252 
2253   RetTy VisitConditionalOperator(const ConditionalOperator *E) {
2254     bool BoolResult;
2255     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
2256       return false;
2257 
2258     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2259     return StmtVisitorTy::Visit(EvalExpr);
2260   }
2261 
2262   RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2263     const CCValue *Value = Info.getOpaqueValue(E);
2264     if (!Value) {
2265       const Expr *Source = E->getSourceExpr();
2266       if (!Source)
2267         return Error(E);
2268       if (Source == E) { // sanity checking.
2269         assert(0 && "OpaqueValueExpr recursively refers to itself");
2270         return Error(E);
2271       }
2272       return StmtVisitorTy::Visit(Source);
2273     }
2274     return DerivedSuccess(*Value, E);
2275   }
2276 
2277   RetTy VisitCallExpr(const CallExpr *E) {
2278     const Expr *Callee = E->getCallee()->IgnoreParens();
2279     QualType CalleeType = Callee->getType();
2280 
2281     const FunctionDecl *FD = 0;
2282     LValue *This = 0, ThisVal;
2283     llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
2284 
2285     // Extract function decl and 'this' pointer from the callee.
2286     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
2287       const ValueDecl *Member = 0;
2288       if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2289         // Explicit bound member calls, such as x.f() or p->g();
2290         if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
2291           return false;
2292         Member = ME->getMemberDecl();
2293         This = &ThisVal;
2294       } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2295         // Indirect bound member calls ('.*' or '->*').
2296         Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2297         if (!Member) return false;
2298         This = &ThisVal;
2299       } else
2300         return Error(Callee);
2301 
2302       FD = dyn_cast<FunctionDecl>(Member);
2303       if (!FD)
2304         return Error(Callee);
2305     } else if (CalleeType->isFunctionPointerType()) {
2306       LValue Call;
2307       if (!EvaluatePointer(Callee, Call, Info))
2308         return false;
2309 
2310       if (!Call.getLValueOffset().isZero())
2311         return Error(Callee);
2312       FD = dyn_cast_or_null<FunctionDecl>(
2313                              Call.getLValueBase().dyn_cast<const ValueDecl*>());
2314       if (!FD)
2315         return Error(Callee);
2316 
2317       // Overloaded operator calls to member functions are represented as normal
2318       // calls with '*this' as the first argument.
2319       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2320       if (MD && !MD->isStatic()) {
2321         // FIXME: When selecting an implicit conversion for an overloaded
2322         // operator delete, we sometimes try to evaluate calls to conversion
2323         // operators without a 'this' parameter!
2324         if (Args.empty())
2325           return Error(E);
2326 
2327         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2328           return false;
2329         This = &ThisVal;
2330         Args = Args.slice(1);
2331       }
2332 
2333       // Don't call function pointers which have been cast to some other type.
2334       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
2335         return Error(E);
2336     } else
2337       return Error(E);
2338 
2339     const FunctionDecl *Definition = 0;
2340     Stmt *Body = FD->getBody(Definition);
2341     APValue Result;
2342 
2343     if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
2344         !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2345                             Info, Result))
2346       return false;
2347 
2348     return DerivedSuccess(CCValue(Info.Ctx, Result, CCValue::GlobalValue()), E);
2349   }
2350 
2351   RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2352     return StmtVisitorTy::Visit(E->getInitializer());
2353   }
2354   RetTy VisitInitListExpr(const InitListExpr *E) {
2355     if (E->getNumInits() == 0)
2356       return DerivedZeroInitialization(E);
2357     if (E->getNumInits() == 1)
2358       return StmtVisitorTy::Visit(E->getInit(0));
2359     return Error(E);
2360   }
2361   RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
2362     return DerivedZeroInitialization(E);
2363   }
2364   RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
2365     return DerivedZeroInitialization(E);
2366   }
2367   RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
2368     return DerivedZeroInitialization(E);
2369   }
2370 
2371   /// A member expression where the object is a prvalue is itself a prvalue.
2372   RetTy VisitMemberExpr(const MemberExpr *E) {
2373     assert(!E->isArrow() && "missing call to bound member function?");
2374 
2375     CCValue Val;
2376     if (!Evaluate(Val, Info, E->getBase()))
2377       return false;
2378 
2379     QualType BaseTy = E->getBase()->getType();
2380 
2381     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
2382     if (!FD) return Error(E);
2383     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2384     assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2385            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2386 
2387     SubobjectDesignator Designator(BaseTy);
2388     Designator.addDeclUnchecked(FD);
2389 
2390     return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
2391            DerivedSuccess(Val, E);
2392   }
2393 
2394   RetTy VisitCastExpr(const CastExpr *E) {
2395     switch (E->getCastKind()) {
2396     default:
2397       break;
2398 
2399     case CK_AtomicToNonAtomic:
2400     case CK_NonAtomicToAtomic:
2401     case CK_NoOp:
2402     case CK_UserDefinedConversion:
2403       return StmtVisitorTy::Visit(E->getSubExpr());
2404 
2405     case CK_LValueToRValue: {
2406       LValue LVal;
2407       if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2408         return false;
2409       CCValue RVal;
2410       if (!HandleLValueToRValueConversion(Info, E, E->getType(), LVal, RVal))
2411         return false;
2412       return DerivedSuccess(RVal, E);
2413     }
2414     }
2415 
2416     return Error(E);
2417   }
2418 
2419   /// Visit a value which is evaluated, but whose value is ignored.
2420   void VisitIgnoredValue(const Expr *E) {
2421     CCValue Scratch;
2422     if (!Evaluate(Scratch, Info, E))
2423       Info.EvalStatus.HasSideEffects = true;
2424   }
2425 };
2426 
2427 }
2428 
2429 //===----------------------------------------------------------------------===//
2430 // Common base class for lvalue and temporary evaluation.
2431 //===----------------------------------------------------------------------===//
2432 namespace {
2433 template<class Derived>
2434 class LValueExprEvaluatorBase
2435   : public ExprEvaluatorBase<Derived, bool> {
2436 protected:
2437   LValue &Result;
2438   typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2439   typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2440 
2441   bool Success(APValue::LValueBase B) {
2442     Result.set(B);
2443     return true;
2444   }
2445 
2446 public:
2447   LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2448     ExprEvaluatorBaseTy(Info), Result(Result) {}
2449 
2450   bool Success(const CCValue &V, const Expr *E) {
2451     Result.setFrom(V);
2452     return true;
2453   }
2454 
2455   bool VisitMemberExpr(const MemberExpr *E) {
2456     // Handle non-static data members.
2457     QualType BaseTy;
2458     if (E->isArrow()) {
2459       if (!EvaluatePointer(E->getBase(), Result, this->Info))
2460         return false;
2461       BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
2462     } else if (E->getBase()->isRValue()) {
2463       assert(E->getBase()->getType()->isRecordType());
2464       if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2465         return false;
2466       BaseTy = E->getBase()->getType();
2467     } else {
2468       if (!this->Visit(E->getBase()))
2469         return false;
2470       BaseTy = E->getBase()->getType();
2471     }
2472 
2473     const ValueDecl *MD = E->getMemberDecl();
2474     if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2475       assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2476              FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2477       (void)BaseTy;
2478       HandleLValueMember(this->Info, E, Result, FD);
2479     } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2480       HandleLValueIndirectMember(this->Info, E, Result, IFD);
2481     } else
2482       return this->Error(E);
2483 
2484     if (MD->getType()->isReferenceType()) {
2485       CCValue RefValue;
2486       if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
2487                                           RefValue))
2488         return false;
2489       return Success(RefValue, E);
2490     }
2491     return true;
2492   }
2493 
2494   bool VisitBinaryOperator(const BinaryOperator *E) {
2495     switch (E->getOpcode()) {
2496     default:
2497       return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2498 
2499     case BO_PtrMemD:
2500     case BO_PtrMemI:
2501       return HandleMemberPointerAccess(this->Info, E, Result);
2502     }
2503   }
2504 
2505   bool VisitCastExpr(const CastExpr *E) {
2506     switch (E->getCastKind()) {
2507     default:
2508       return ExprEvaluatorBaseTy::VisitCastExpr(E);
2509 
2510     case CK_DerivedToBase:
2511     case CK_UncheckedDerivedToBase: {
2512       if (!this->Visit(E->getSubExpr()))
2513         return false;
2514 
2515       // Now figure out the necessary offset to add to the base LV to get from
2516       // the derived class to the base class.
2517       QualType Type = E->getSubExpr()->getType();
2518 
2519       for (CastExpr::path_const_iterator PathI = E->path_begin(),
2520            PathE = E->path_end(); PathI != PathE; ++PathI) {
2521         if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
2522                               *PathI))
2523           return false;
2524         Type = (*PathI)->getType();
2525       }
2526 
2527       return true;
2528     }
2529     }
2530   }
2531 };
2532 }
2533 
2534 //===----------------------------------------------------------------------===//
2535 // LValue Evaluation
2536 //
2537 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2538 // function designators (in C), decl references to void objects (in C), and
2539 // temporaries (if building with -Wno-address-of-temporary).
2540 //
2541 // LValue evaluation produces values comprising a base expression of one of the
2542 // following types:
2543 // - Declarations
2544 //  * VarDecl
2545 //  * FunctionDecl
2546 // - Literals
2547 //  * CompoundLiteralExpr in C
2548 //  * StringLiteral
2549 //  * CXXTypeidExpr
2550 //  * PredefinedExpr
2551 //  * ObjCStringLiteralExpr
2552 //  * ObjCEncodeExpr
2553 //  * AddrLabelExpr
2554 //  * BlockExpr
2555 //  * CallExpr for a MakeStringConstant builtin
2556 // - Locals and temporaries
2557 //  * Any Expr, with a Frame indicating the function in which the temporary was
2558 //    evaluated.
2559 // plus an offset in bytes.
2560 //===----------------------------------------------------------------------===//
2561 namespace {
2562 class LValueExprEvaluator
2563   : public LValueExprEvaluatorBase<LValueExprEvaluator> {
2564 public:
2565   LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2566     LValueExprEvaluatorBaseTy(Info, Result) {}
2567 
2568   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2569 
2570   bool VisitDeclRefExpr(const DeclRefExpr *E);
2571   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
2572   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
2573   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2574   bool VisitMemberExpr(const MemberExpr *E);
2575   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2576   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
2577   bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
2578   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2579   bool VisitUnaryDeref(const UnaryOperator *E);
2580 
2581   bool VisitCastExpr(const CastExpr *E) {
2582     switch (E->getCastKind()) {
2583     default:
2584       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
2585 
2586     case CK_LValueBitCast:
2587       this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2588       if (!Visit(E->getSubExpr()))
2589         return false;
2590       Result.Designator.setInvalid();
2591       return true;
2592 
2593     case CK_BaseToDerived:
2594       if (!Visit(E->getSubExpr()))
2595         return false;
2596       return HandleBaseToDerivedCast(Info, E, Result);
2597     }
2598   }
2599 
2600   // FIXME: Missing: __real__, __imag__
2601 
2602 };
2603 } // end anonymous namespace
2604 
2605 /// Evaluate an expression as an lvalue. This can be legitimately called on
2606 /// expressions which are not glvalues, in a few cases:
2607 ///  * function designators in C,
2608 ///  * "extern void" objects,
2609 ///  * temporaries, if building with -Wno-address-of-temporary.
2610 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
2611   assert((E->isGLValue() || E->getType()->isFunctionType() ||
2612           E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2613          "can't evaluate expression as an lvalue");
2614   return LValueExprEvaluator(Info, Result).Visit(E);
2615 }
2616 
2617 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2618   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2619     return Success(FD);
2620   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
2621     return VisitVarDecl(E, VD);
2622   return Error(E);
2623 }
2624 
2625 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
2626   if (!VD->getType()->isReferenceType()) {
2627     if (isa<ParmVarDecl>(VD)) {
2628       Result.set(VD, Info.CurrentCall);
2629       return true;
2630     }
2631     return Success(VD);
2632   }
2633 
2634   CCValue V;
2635   if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2636     return false;
2637   return Success(V, E);
2638 }
2639 
2640 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2641     const MaterializeTemporaryExpr *E) {
2642   if (E->GetTemporaryExpr()->isRValue()) {
2643     if (E->getType()->isRecordType())
2644       return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2645 
2646     Result.set(E, Info.CurrentCall);
2647     return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
2648                                       Result, E->GetTemporaryExpr());
2649   }
2650 
2651   // Materialization of an lvalue temporary occurs when we need to force a copy
2652   // (for instance, if it's a bitfield).
2653   // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2654   if (!Visit(E->GetTemporaryExpr()))
2655     return false;
2656   if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
2657                                       Info.CurrentCall->Temporaries[E]))
2658     return false;
2659   Result.set(E, Info.CurrentCall);
2660   return true;
2661 }
2662 
2663 bool
2664 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2665   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2666   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2667   // only see this when folding in C, so there's no standard to follow here.
2668   return Success(E);
2669 }
2670 
2671 bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2672   if (E->isTypeOperand())
2673     return Success(E);
2674   CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2675   if (RD && RD->isPolymorphic()) {
2676     Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
2677       << E->getExprOperand()->getType()
2678       << E->getExprOperand()->getSourceRange();
2679     return false;
2680   }
2681   return Success(E);
2682 }
2683 
2684 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
2685   // Handle static data members.
2686   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2687     VisitIgnoredValue(E->getBase());
2688     return VisitVarDecl(E, VD);
2689   }
2690 
2691   // Handle static member functions.
2692   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2693     if (MD->isStatic()) {
2694       VisitIgnoredValue(E->getBase());
2695       return Success(MD);
2696     }
2697   }
2698 
2699   // Handle non-static data members.
2700   return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
2701 }
2702 
2703 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
2704   // FIXME: Deal with vectors as array subscript bases.
2705   if (E->getBase()->getType()->isVectorType())
2706     return Error(E);
2707 
2708   if (!EvaluatePointer(E->getBase(), Result, Info))
2709     return false;
2710 
2711   APSInt Index;
2712   if (!EvaluateInteger(E->getIdx(), Index, Info))
2713     return false;
2714   int64_t IndexValue
2715     = Index.isSigned() ? Index.getSExtValue()
2716                        : static_cast<int64_t>(Index.getZExtValue());
2717 
2718   return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
2719 }
2720 
2721 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
2722   return EvaluatePointer(E->getSubExpr(), Result, Info);
2723 }
2724 
2725 //===----------------------------------------------------------------------===//
2726 // Pointer Evaluation
2727 //===----------------------------------------------------------------------===//
2728 
2729 namespace {
2730 class PointerExprEvaluator
2731   : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
2732   LValue &Result;
2733 
2734   bool Success(const Expr *E) {
2735     Result.set(E);
2736     return true;
2737   }
2738 public:
2739 
2740   PointerExprEvaluator(EvalInfo &info, LValue &Result)
2741     : ExprEvaluatorBaseTy(info), Result(Result) {}
2742 
2743   bool Success(const CCValue &V, const Expr *E) {
2744     Result.setFrom(V);
2745     return true;
2746   }
2747   bool ZeroInitialization(const Expr *E) {
2748     return Success((Expr*)0);
2749   }
2750 
2751   bool VisitBinaryOperator(const BinaryOperator *E);
2752   bool VisitCastExpr(const CastExpr* E);
2753   bool VisitUnaryAddrOf(const UnaryOperator *E);
2754   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
2755       { return Success(E); }
2756   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
2757       { return Success(E); }
2758   bool VisitCallExpr(const CallExpr *E);
2759   bool VisitBlockExpr(const BlockExpr *E) {
2760     if (!E->getBlockDecl()->hasCaptures())
2761       return Success(E);
2762     return Error(E);
2763   }
2764   bool VisitCXXThisExpr(const CXXThisExpr *E) {
2765     if (!Info.CurrentCall->This)
2766       return Error(E);
2767     Result = *Info.CurrentCall->This;
2768     return true;
2769   }
2770 
2771   // FIXME: Missing: @protocol, @selector
2772 };
2773 } // end anonymous namespace
2774 
2775 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
2776   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
2777   return PointerExprEvaluator(Info, Result).Visit(E);
2778 }
2779 
2780 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2781   if (E->getOpcode() != BO_Add &&
2782       E->getOpcode() != BO_Sub)
2783     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2784 
2785   const Expr *PExp = E->getLHS();
2786   const Expr *IExp = E->getRHS();
2787   if (IExp->getType()->isPointerType())
2788     std::swap(PExp, IExp);
2789 
2790   bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
2791   if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
2792     return false;
2793 
2794   llvm::APSInt Offset;
2795   if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
2796     return false;
2797   int64_t AdditionalOffset
2798     = Offset.isSigned() ? Offset.getSExtValue()
2799                         : static_cast<int64_t>(Offset.getZExtValue());
2800   if (E->getOpcode() == BO_Sub)
2801     AdditionalOffset = -AdditionalOffset;
2802 
2803   QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
2804   return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
2805                                      AdditionalOffset);
2806 }
2807 
2808 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
2809   return EvaluateLValue(E->getSubExpr(), Result, Info);
2810 }
2811 
2812 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
2813   const Expr* SubExpr = E->getSubExpr();
2814 
2815   switch (E->getCastKind()) {
2816   default:
2817     break;
2818 
2819   case CK_BitCast:
2820   case CK_CPointerToObjCPointerCast:
2821   case CK_BlockPointerToObjCPointerCast:
2822   case CK_AnyPointerToBlockPointerCast:
2823     if (!Visit(SubExpr))
2824       return false;
2825     // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
2826     // permitted in constant expressions in C++11. Bitcasts from cv void* are
2827     // also static_casts, but we disallow them as a resolution to DR1312.
2828     if (!E->getType()->isVoidPointerType()) {
2829       Result.Designator.setInvalid();
2830       if (SubExpr->getType()->isVoidPointerType())
2831         CCEDiag(E, diag::note_constexpr_invalid_cast)
2832           << 3 << SubExpr->getType();
2833       else
2834         CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2835     }
2836     return true;
2837 
2838   case CK_DerivedToBase:
2839   case CK_UncheckedDerivedToBase: {
2840     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
2841       return false;
2842     if (!Result.Base && Result.Offset.isZero())
2843       return true;
2844 
2845     // Now figure out the necessary offset to add to the base LV to get from
2846     // the derived class to the base class.
2847     QualType Type =
2848         E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
2849 
2850     for (CastExpr::path_const_iterator PathI = E->path_begin(),
2851          PathE = E->path_end(); PathI != PathE; ++PathI) {
2852       if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2853                             *PathI))
2854         return false;
2855       Type = (*PathI)->getType();
2856     }
2857 
2858     return true;
2859   }
2860 
2861   case CK_BaseToDerived:
2862     if (!Visit(E->getSubExpr()))
2863       return false;
2864     if (!Result.Base && Result.Offset.isZero())
2865       return true;
2866     return HandleBaseToDerivedCast(Info, E, Result);
2867 
2868   case CK_NullToPointer:
2869     return ZeroInitialization(E);
2870 
2871   case CK_IntegralToPointer: {
2872     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
2873 
2874     CCValue Value;
2875     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
2876       break;
2877 
2878     if (Value.isInt()) {
2879       unsigned Size = Info.Ctx.getTypeSize(E->getType());
2880       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
2881       Result.Base = (Expr*)0;
2882       Result.Offset = CharUnits::fromQuantity(N);
2883       Result.Frame = 0;
2884       Result.Designator.setInvalid();
2885       return true;
2886     } else {
2887       // Cast is of an lvalue, no need to change value.
2888       Result.setFrom(Value);
2889       return true;
2890     }
2891   }
2892   case CK_ArrayToPointerDecay:
2893     if (SubExpr->isGLValue()) {
2894       if (!EvaluateLValue(SubExpr, Result, Info))
2895         return false;
2896     } else {
2897       Result.set(SubExpr, Info.CurrentCall);
2898       if (!EvaluateConstantExpression(Info.CurrentCall->Temporaries[SubExpr],
2899                                       Info, Result, SubExpr))
2900         return false;
2901     }
2902     // The result is a pointer to the first element of the array.
2903     if (const ConstantArrayType *CAT
2904           = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
2905       Result.addArray(Info, E, CAT);
2906     else
2907       Result.Designator.setInvalid();
2908     return true;
2909 
2910   case CK_FunctionToPointerDecay:
2911     return EvaluateLValue(SubExpr, Result, Info);
2912   }
2913 
2914   return ExprEvaluatorBaseTy::VisitCastExpr(E);
2915 }
2916 
2917 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
2918   if (IsStringLiteralCall(E))
2919     return Success(E);
2920 
2921   return ExprEvaluatorBaseTy::VisitCallExpr(E);
2922 }
2923 
2924 //===----------------------------------------------------------------------===//
2925 // Member Pointer Evaluation
2926 //===----------------------------------------------------------------------===//
2927 
2928 namespace {
2929 class MemberPointerExprEvaluator
2930   : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
2931   MemberPtr &Result;
2932 
2933   bool Success(const ValueDecl *D) {
2934     Result = MemberPtr(D);
2935     return true;
2936   }
2937 public:
2938 
2939   MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
2940     : ExprEvaluatorBaseTy(Info), Result(Result) {}
2941 
2942   bool Success(const CCValue &V, const Expr *E) {
2943     Result.setFrom(V);
2944     return true;
2945   }
2946   bool ZeroInitialization(const Expr *E) {
2947     return Success((const ValueDecl*)0);
2948   }
2949 
2950   bool VisitCastExpr(const CastExpr *E);
2951   bool VisitUnaryAddrOf(const UnaryOperator *E);
2952 };
2953 } // end anonymous namespace
2954 
2955 static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
2956                                   EvalInfo &Info) {
2957   assert(E->isRValue() && E->getType()->isMemberPointerType());
2958   return MemberPointerExprEvaluator(Info, Result).Visit(E);
2959 }
2960 
2961 bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
2962   switch (E->getCastKind()) {
2963   default:
2964     return ExprEvaluatorBaseTy::VisitCastExpr(E);
2965 
2966   case CK_NullToMemberPointer:
2967     return ZeroInitialization(E);
2968 
2969   case CK_BaseToDerivedMemberPointer: {
2970     if (!Visit(E->getSubExpr()))
2971       return false;
2972     if (E->path_empty())
2973       return true;
2974     // Base-to-derived member pointer casts store the path in derived-to-base
2975     // order, so iterate backwards. The CXXBaseSpecifier also provides us with
2976     // the wrong end of the derived->base arc, so stagger the path by one class.
2977     typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
2978     for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
2979          PathI != PathE; ++PathI) {
2980       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2981       const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
2982       if (!Result.castToDerived(Derived))
2983         return Error(E);
2984     }
2985     const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
2986     if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
2987       return Error(E);
2988     return true;
2989   }
2990 
2991   case CK_DerivedToBaseMemberPointer:
2992     if (!Visit(E->getSubExpr()))
2993       return false;
2994     for (CastExpr::path_const_iterator PathI = E->path_begin(),
2995          PathE = E->path_end(); PathI != PathE; ++PathI) {
2996       assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
2997       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
2998       if (!Result.castToBase(Base))
2999         return Error(E);
3000     }
3001     return true;
3002   }
3003 }
3004 
3005 bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3006   // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3007   // member can be formed.
3008   return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3009 }
3010 
3011 //===----------------------------------------------------------------------===//
3012 // Record Evaluation
3013 //===----------------------------------------------------------------------===//
3014 
3015 namespace {
3016   class RecordExprEvaluator
3017   : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3018     const LValue &This;
3019     APValue &Result;
3020   public:
3021 
3022     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3023       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3024 
3025     bool Success(const CCValue &V, const Expr *E) {
3026       return CheckConstantExpression(Info, E, V, Result);
3027     }
3028     bool ZeroInitialization(const Expr *E);
3029 
3030     bool VisitCastExpr(const CastExpr *E);
3031     bool VisitInitListExpr(const InitListExpr *E);
3032     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3033   };
3034 }
3035 
3036 /// Perform zero-initialization on an object of non-union class type.
3037 /// C++11 [dcl.init]p5:
3038 ///  To zero-initialize an object or reference of type T means:
3039 ///    [...]
3040 ///    -- if T is a (possibly cv-qualified) non-union class type,
3041 ///       each non-static data member and each base-class subobject is
3042 ///       zero-initialized
3043 static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3044                                           const RecordDecl *RD,
3045                                           const LValue &This, APValue &Result) {
3046   assert(!RD->isUnion() && "Expected non-union class type");
3047   const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3048   Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3049                    std::distance(RD->field_begin(), RD->field_end()));
3050 
3051   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3052 
3053   if (CD) {
3054     unsigned Index = 0;
3055     for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
3056            End = CD->bases_end(); I != End; ++I, ++Index) {
3057       const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3058       LValue Subobject = This;
3059       HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3060       if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
3061                                          Result.getStructBase(Index)))
3062         return false;
3063     }
3064   }
3065 
3066   for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3067        I != End; ++I) {
3068     // -- if T is a reference type, no initialization is performed.
3069     if ((*I)->getType()->isReferenceType())
3070       continue;
3071 
3072     LValue Subobject = This;
3073     HandleLValueMember(Info, E, Subobject, *I, &Layout);
3074 
3075     ImplicitValueInitExpr VIE((*I)->getType());
3076     if (!EvaluateConstantExpression(
3077           Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3078       return false;
3079   }
3080 
3081   return true;
3082 }
3083 
3084 bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3085   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3086   if (RD->isUnion()) {
3087     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3088     // object's first non-static named data member is zero-initialized
3089     RecordDecl::field_iterator I = RD->field_begin();
3090     if (I == RD->field_end()) {
3091       Result = APValue((const FieldDecl*)0);
3092       return true;
3093     }
3094 
3095     LValue Subobject = This;
3096     HandleLValueMember(Info, E, Subobject, *I);
3097     Result = APValue(*I);
3098     ImplicitValueInitExpr VIE((*I)->getType());
3099     return EvaluateConstantExpression(Result.getUnionValue(), Info,
3100                                       Subobject, &VIE);
3101   }
3102 
3103   return HandleClassZeroInitialization(Info, E, RD, This, Result);
3104 }
3105 
3106 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3107   switch (E->getCastKind()) {
3108   default:
3109     return ExprEvaluatorBaseTy::VisitCastExpr(E);
3110 
3111   case CK_ConstructorConversion:
3112     return Visit(E->getSubExpr());
3113 
3114   case CK_DerivedToBase:
3115   case CK_UncheckedDerivedToBase: {
3116     CCValue DerivedObject;
3117     if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
3118       return false;
3119     if (!DerivedObject.isStruct())
3120       return Error(E->getSubExpr());
3121 
3122     // Derived-to-base rvalue conversion: just slice off the derived part.
3123     APValue *Value = &DerivedObject;
3124     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3125     for (CastExpr::path_const_iterator PathI = E->path_begin(),
3126          PathE = E->path_end(); PathI != PathE; ++PathI) {
3127       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3128       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3129       Value = &Value->getStructBase(getBaseIndex(RD, Base));
3130       RD = Base;
3131     }
3132     Result = *Value;
3133     return true;
3134   }
3135   }
3136 }
3137 
3138 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3139   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3140   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3141 
3142   if (RD->isUnion()) {
3143     const FieldDecl *Field = E->getInitializedFieldInUnion();
3144     Result = APValue(Field);
3145     if (!Field)
3146       return true;
3147 
3148     // If the initializer list for a union does not contain any elements, the
3149     // first element of the union is value-initialized.
3150     ImplicitValueInitExpr VIE(Field->getType());
3151     const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3152 
3153     LValue Subobject = This;
3154     HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
3155     return EvaluateConstantExpression(Result.getUnionValue(), Info,
3156                                       Subobject, InitExpr);
3157   }
3158 
3159   assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3160          "initializer list for class with base classes");
3161   Result = APValue(APValue::UninitStruct(), 0,
3162                    std::distance(RD->field_begin(), RD->field_end()));
3163   unsigned ElementNo = 0;
3164   bool Success = true;
3165   for (RecordDecl::field_iterator Field = RD->field_begin(),
3166        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3167     // Anonymous bit-fields are not considered members of the class for
3168     // purposes of aggregate initialization.
3169     if (Field->isUnnamedBitfield())
3170       continue;
3171 
3172     LValue Subobject = This;
3173 
3174     bool HaveInit = ElementNo < E->getNumInits();
3175 
3176     // FIXME: Diagnostics here should point to the end of the initializer
3177     // list, not the start.
3178     HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3179                        *Field, &Layout);
3180 
3181     // Perform an implicit value-initialization for members beyond the end of
3182     // the initializer list.
3183     ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3184 
3185     if (!EvaluateConstantExpression(
3186           Result.getStructField((*Field)->getFieldIndex()),
3187           Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3188       if (!Info.keepEvaluatingAfterFailure())
3189         return false;
3190       Success = false;
3191     }
3192   }
3193 
3194   return Success;
3195 }
3196 
3197 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3198   const CXXConstructorDecl *FD = E->getConstructor();
3199   bool ZeroInit = E->requiresZeroInitialization();
3200   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3201     // If we've already performed zero-initialization, we're already done.
3202     if (!Result.isUninit())
3203       return true;
3204 
3205     if (ZeroInit)
3206       return ZeroInitialization(E);
3207 
3208     const CXXRecordDecl *RD = FD->getParent();
3209     if (RD->isUnion())
3210       Result = APValue((FieldDecl*)0);
3211     else
3212       Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3213                        std::distance(RD->field_begin(), RD->field_end()));
3214     return true;
3215   }
3216 
3217   const FunctionDecl *Definition = 0;
3218   FD->getBody(Definition);
3219 
3220   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3221     return false;
3222 
3223   // Avoid materializing a temporary for an elidable copy/move constructor.
3224   if (E->isElidable() && !ZeroInit)
3225     if (const MaterializeTemporaryExpr *ME
3226           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3227       return Visit(ME->GetTemporaryExpr());
3228 
3229   if (ZeroInit && !ZeroInitialization(E))
3230     return false;
3231 
3232   llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3233   return HandleConstructorCall(E->getExprLoc(), This, Args,
3234                                cast<CXXConstructorDecl>(Definition), Info,
3235                                Result);
3236 }
3237 
3238 static bool EvaluateRecord(const Expr *E, const LValue &This,
3239                            APValue &Result, EvalInfo &Info) {
3240   assert(E->isRValue() && E->getType()->isRecordType() &&
3241          "can't evaluate expression as a record rvalue");
3242   return RecordExprEvaluator(Info, This, Result).Visit(E);
3243 }
3244 
3245 //===----------------------------------------------------------------------===//
3246 // Temporary Evaluation
3247 //
3248 // Temporaries are represented in the AST as rvalues, but generally behave like
3249 // lvalues. The full-object of which the temporary is a subobject is implicitly
3250 // materialized so that a reference can bind to it.
3251 //===----------------------------------------------------------------------===//
3252 namespace {
3253 class TemporaryExprEvaluator
3254   : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3255 public:
3256   TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3257     LValueExprEvaluatorBaseTy(Info, Result) {}
3258 
3259   /// Visit an expression which constructs the value of this temporary.
3260   bool VisitConstructExpr(const Expr *E) {
3261     Result.set(E, Info.CurrentCall);
3262     return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
3263                                       Result, E);
3264   }
3265 
3266   bool VisitCastExpr(const CastExpr *E) {
3267     switch (E->getCastKind()) {
3268     default:
3269       return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3270 
3271     case CK_ConstructorConversion:
3272       return VisitConstructExpr(E->getSubExpr());
3273     }
3274   }
3275   bool VisitInitListExpr(const InitListExpr *E) {
3276     return VisitConstructExpr(E);
3277   }
3278   bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3279     return VisitConstructExpr(E);
3280   }
3281   bool VisitCallExpr(const CallExpr *E) {
3282     return VisitConstructExpr(E);
3283   }
3284 };
3285 } // end anonymous namespace
3286 
3287 /// Evaluate an expression of record type as a temporary.
3288 static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
3289   assert(E->isRValue() && E->getType()->isRecordType());
3290   return TemporaryExprEvaluator(Info, Result).Visit(E);
3291 }
3292 
3293 //===----------------------------------------------------------------------===//
3294 // Vector Evaluation
3295 //===----------------------------------------------------------------------===//
3296 
3297 namespace {
3298   class VectorExprEvaluator
3299   : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3300     APValue &Result;
3301   public:
3302 
3303     VectorExprEvaluator(EvalInfo &info, APValue &Result)
3304       : ExprEvaluatorBaseTy(info), Result(Result) {}
3305 
3306     bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3307       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3308       // FIXME: remove this APValue copy.
3309       Result = APValue(V.data(), V.size());
3310       return true;
3311     }
3312     bool Success(const CCValue &V, const Expr *E) {
3313       assert(V.isVector());
3314       Result = V;
3315       return true;
3316     }
3317     bool ZeroInitialization(const Expr *E);
3318 
3319     bool VisitUnaryReal(const UnaryOperator *E)
3320       { return Visit(E->getSubExpr()); }
3321     bool VisitCastExpr(const CastExpr* E);
3322     bool VisitInitListExpr(const InitListExpr *E);
3323     bool VisitUnaryImag(const UnaryOperator *E);
3324     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
3325     //                 binary comparisons, binary and/or/xor,
3326     //                 shufflevector, ExtVectorElementExpr
3327   };
3328 } // end anonymous namespace
3329 
3330 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
3331   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
3332   return VectorExprEvaluator(Info, Result).Visit(E);
3333 }
3334 
3335 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3336   const VectorType *VTy = E->getType()->castAs<VectorType>();
3337   unsigned NElts = VTy->getNumElements();
3338 
3339   const Expr *SE = E->getSubExpr();
3340   QualType SETy = SE->getType();
3341 
3342   switch (E->getCastKind()) {
3343   case CK_VectorSplat: {
3344     APValue Val = APValue();
3345     if (SETy->isIntegerType()) {
3346       APSInt IntResult;
3347       if (!EvaluateInteger(SE, IntResult, Info))
3348          return false;
3349       Val = APValue(IntResult);
3350     } else if (SETy->isRealFloatingType()) {
3351        APFloat F(0.0);
3352        if (!EvaluateFloat(SE, F, Info))
3353          return false;
3354        Val = APValue(F);
3355     } else {
3356       return Error(E);
3357     }
3358 
3359     // Splat and create vector APValue.
3360     SmallVector<APValue, 4> Elts(NElts, Val);
3361     return Success(Elts, E);
3362   }
3363   case CK_BitCast: {
3364     // Evaluate the operand into an APInt we can extract from.
3365     llvm::APInt SValInt;
3366     if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3367       return false;
3368     // Extract the elements
3369     QualType EltTy = VTy->getElementType();
3370     unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3371     bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3372     SmallVector<APValue, 4> Elts;
3373     if (EltTy->isRealFloatingType()) {
3374       const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3375       bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3376       unsigned FloatEltSize = EltSize;
3377       if (&Sem == &APFloat::x87DoubleExtended)
3378         FloatEltSize = 80;
3379       for (unsigned i = 0; i < NElts; i++) {
3380         llvm::APInt Elt;
3381         if (BigEndian)
3382           Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3383         else
3384           Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3385         Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3386       }
3387     } else if (EltTy->isIntegerType()) {
3388       for (unsigned i = 0; i < NElts; i++) {
3389         llvm::APInt Elt;
3390         if (BigEndian)
3391           Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3392         else
3393           Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3394         Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3395       }
3396     } else {
3397       return Error(E);
3398     }
3399     return Success(Elts, E);
3400   }
3401   default:
3402     return ExprEvaluatorBaseTy::VisitCastExpr(E);
3403   }
3404 }
3405 
3406 bool
3407 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3408   const VectorType *VT = E->getType()->castAs<VectorType>();
3409   unsigned NumInits = E->getNumInits();
3410   unsigned NumElements = VT->getNumElements();
3411 
3412   QualType EltTy = VT->getElementType();
3413   SmallVector<APValue, 4> Elements;
3414 
3415   // The number of initializers can be less than the number of
3416   // vector elements. For OpenCL, this can be due to nested vector
3417   // initialization. For GCC compatibility, missing trailing elements
3418   // should be initialized with zeroes.
3419   unsigned CountInits = 0, CountElts = 0;
3420   while (CountElts < NumElements) {
3421     // Handle nested vector initialization.
3422     if (CountInits < NumInits
3423         && E->getInit(CountInits)->getType()->isExtVectorType()) {
3424       APValue v;
3425       if (!EvaluateVector(E->getInit(CountInits), v, Info))
3426         return Error(E);
3427       unsigned vlen = v.getVectorLength();
3428       for (unsigned j = 0; j < vlen; j++)
3429         Elements.push_back(v.getVectorElt(j));
3430       CountElts += vlen;
3431     } else if (EltTy->isIntegerType()) {
3432       llvm::APSInt sInt(32);
3433       if (CountInits < NumInits) {
3434         if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3435           return Error(E);
3436       } else // trailing integer zero.
3437         sInt = Info.Ctx.MakeIntValue(0, EltTy);
3438       Elements.push_back(APValue(sInt));
3439       CountElts++;
3440     } else {
3441       llvm::APFloat f(0.0);
3442       if (CountInits < NumInits) {
3443         if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3444           return Error(E);
3445       } else // trailing float zero.
3446         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3447       Elements.push_back(APValue(f));
3448       CountElts++;
3449     }
3450     CountInits++;
3451   }
3452   return Success(Elements, E);
3453 }
3454 
3455 bool
3456 VectorExprEvaluator::ZeroInitialization(const Expr *E) {
3457   const VectorType *VT = E->getType()->getAs<VectorType>();
3458   QualType EltTy = VT->getElementType();
3459   APValue ZeroElement;
3460   if (EltTy->isIntegerType())
3461     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3462   else
3463     ZeroElement =
3464         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3465 
3466   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
3467   return Success(Elements, E);
3468 }
3469 
3470 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3471   VisitIgnoredValue(E->getSubExpr());
3472   return ZeroInitialization(E);
3473 }
3474 
3475 //===----------------------------------------------------------------------===//
3476 // Array Evaluation
3477 //===----------------------------------------------------------------------===//
3478 
3479 namespace {
3480   class ArrayExprEvaluator
3481   : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
3482     const LValue &This;
3483     APValue &Result;
3484   public:
3485 
3486     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3487       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
3488 
3489     bool Success(const APValue &V, const Expr *E) {
3490       assert(V.isArray() && "Expected array type");
3491       Result = V;
3492       return true;
3493     }
3494 
3495     bool ZeroInitialization(const Expr *E) {
3496       const ConstantArrayType *CAT =
3497           Info.Ctx.getAsConstantArrayType(E->getType());
3498       if (!CAT)
3499         return Error(E);
3500 
3501       Result = APValue(APValue::UninitArray(), 0,
3502                        CAT->getSize().getZExtValue());
3503       if (!Result.hasArrayFiller()) return true;
3504 
3505       // Zero-initialize all elements.
3506       LValue Subobject = This;
3507       Subobject.addArray(Info, E, CAT);
3508       ImplicitValueInitExpr VIE(CAT->getElementType());
3509       return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3510                                         Subobject, &VIE);
3511     }
3512 
3513     bool VisitInitListExpr(const InitListExpr *E);
3514     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3515   };
3516 } // end anonymous namespace
3517 
3518 static bool EvaluateArray(const Expr *E, const LValue &This,
3519                           APValue &Result, EvalInfo &Info) {
3520   assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
3521   return ArrayExprEvaluator(Info, This, Result).Visit(E);
3522 }
3523 
3524 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3525   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3526   if (!CAT)
3527     return Error(E);
3528 
3529   // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3530   // an appropriately-typed string literal enclosed in braces.
3531   if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
3532       Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3533     LValue LV;
3534     if (!EvaluateLValue(E->getInit(0), LV, Info))
3535       return false;
3536     uint64_t NumElements = CAT->getSize().getZExtValue();
3537     Result = APValue(APValue::UninitArray(), NumElements, NumElements);
3538 
3539     // Copy the string literal into the array. FIXME: Do this better.
3540     LV.addArray(Info, E, CAT);
3541     for (uint64_t I = 0; I < NumElements; ++I) {
3542       CCValue Char;
3543       if (!HandleLValueToRValueConversion(Info, E->getInit(0),
3544                                           CAT->getElementType(), LV, Char) ||
3545           !CheckConstantExpression(Info, E->getInit(0), Char,
3546                                    Result.getArrayInitializedElt(I)) ||
3547           !HandleLValueArrayAdjustment(Info, E->getInit(0), LV,
3548                                        CAT->getElementType(), 1))
3549         return false;
3550     }
3551     return true;
3552   }
3553 
3554   bool Success = true;
3555 
3556   Result = APValue(APValue::UninitArray(), E->getNumInits(),
3557                    CAT->getSize().getZExtValue());
3558   LValue Subobject = This;
3559   Subobject.addArray(Info, E, CAT);
3560   unsigned Index = 0;
3561   for (InitListExpr::const_iterator I = E->begin(), End = E->end();
3562        I != End; ++I, ++Index) {
3563     if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
3564                                     Info, Subobject, cast<Expr>(*I)) ||
3565         !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3566                                      CAT->getElementType(), 1)) {
3567       if (!Info.keepEvaluatingAfterFailure())
3568         return false;
3569       Success = false;
3570     }
3571   }
3572 
3573   if (!Result.hasArrayFiller()) return Success;
3574   assert(E->hasArrayFiller() && "no array filler for incomplete init list");
3575   // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3576   // but sometimes does:
3577   //   struct S { constexpr S() : p(&p) {} void *p; };
3578   //   S s[10] = {};
3579   return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3580                                     Subobject, E->getArrayFiller()) && Success;
3581 }
3582 
3583 bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3584   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3585   if (!CAT)
3586     return Error(E);
3587 
3588   bool HadZeroInit = !Result.isUninit();
3589   if (!HadZeroInit)
3590     Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3591   if (!Result.hasArrayFiller())
3592     return true;
3593 
3594   const CXXConstructorDecl *FD = E->getConstructor();
3595 
3596   bool ZeroInit = E->requiresZeroInitialization();
3597   if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
3598     if (HadZeroInit)
3599       return true;
3600 
3601     if (ZeroInit) {
3602       LValue Subobject = This;
3603       Subobject.addArray(Info, E, CAT);
3604       ImplicitValueInitExpr VIE(CAT->getElementType());
3605       return EvaluateConstantExpression(Result.getArrayFiller(), Info,
3606                                         Subobject, &VIE);
3607     }
3608 
3609     const CXXRecordDecl *RD = FD->getParent();
3610     if (RD->isUnion())
3611       Result.getArrayFiller() = APValue((FieldDecl*)0);
3612     else
3613       Result.getArrayFiller() =
3614           APValue(APValue::UninitStruct(), RD->getNumBases(),
3615                   std::distance(RD->field_begin(), RD->field_end()));
3616     return true;
3617   }
3618 
3619   const FunctionDecl *Definition = 0;
3620   FD->getBody(Definition);
3621 
3622   if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3623     return false;
3624 
3625   // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3626   // but sometimes does:
3627   //   struct S { constexpr S() : p(&p) {} void *p; };
3628   //   S s[10];
3629   LValue Subobject = This;
3630   Subobject.addArray(Info, E, CAT);
3631 
3632   if (ZeroInit && !HadZeroInit) {
3633     ImplicitValueInitExpr VIE(CAT->getElementType());
3634     if (!EvaluateConstantExpression(Result.getArrayFiller(), Info, Subobject,
3635                                     &VIE))
3636       return false;
3637   }
3638 
3639   llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
3640   return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
3641                                cast<CXXConstructorDecl>(Definition),
3642                                Info, Result.getArrayFiller());
3643 }
3644 
3645 //===----------------------------------------------------------------------===//
3646 // Integer Evaluation
3647 //
3648 // As a GNU extension, we support casting pointers to sufficiently-wide integer
3649 // types and back in constant folding. Integer values are thus represented
3650 // either as an integer-valued APValue, or as an lvalue-valued APValue.
3651 //===----------------------------------------------------------------------===//
3652 
3653 namespace {
3654 class IntExprEvaluator
3655   : public ExprEvaluatorBase<IntExprEvaluator, bool> {
3656   CCValue &Result;
3657 public:
3658   IntExprEvaluator(EvalInfo &info, CCValue &result)
3659     : ExprEvaluatorBaseTy(info), Result(result) {}
3660 
3661   bool Success(const llvm::APSInt &SI, const Expr *E) {
3662     assert(E->getType()->isIntegralOrEnumerationType() &&
3663            "Invalid evaluation result.");
3664     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
3665            "Invalid evaluation result.");
3666     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3667            "Invalid evaluation result.");
3668     Result = CCValue(SI);
3669     return true;
3670   }
3671 
3672   bool Success(const llvm::APInt &I, const Expr *E) {
3673     assert(E->getType()->isIntegralOrEnumerationType() &&
3674            "Invalid evaluation result.");
3675     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
3676            "Invalid evaluation result.");
3677     Result = CCValue(APSInt(I));
3678     Result.getInt().setIsUnsigned(
3679                             E->getType()->isUnsignedIntegerOrEnumerationType());
3680     return true;
3681   }
3682 
3683   bool Success(uint64_t Value, const Expr *E) {
3684     assert(E->getType()->isIntegralOrEnumerationType() &&
3685            "Invalid evaluation result.");
3686     Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
3687     return true;
3688   }
3689 
3690   bool Success(CharUnits Size, const Expr *E) {
3691     return Success(Size.getQuantity(), E);
3692   }
3693 
3694   bool Success(const CCValue &V, const Expr *E) {
3695     if (V.isLValue() || V.isAddrLabelDiff()) {
3696       Result = V;
3697       return true;
3698     }
3699     return Success(V.getInt(), E);
3700   }
3701 
3702   bool ZeroInitialization(const Expr *E) { return Success(0, E); }
3703 
3704   //===--------------------------------------------------------------------===//
3705   //                            Visitor Methods
3706   //===--------------------------------------------------------------------===//
3707 
3708   bool VisitIntegerLiteral(const IntegerLiteral *E) {
3709     return Success(E->getValue(), E);
3710   }
3711   bool VisitCharacterLiteral(const CharacterLiteral *E) {
3712     return Success(E->getValue(), E);
3713   }
3714 
3715   bool CheckReferencedDecl(const Expr *E, const Decl *D);
3716   bool VisitDeclRefExpr(const DeclRefExpr *E) {
3717     if (CheckReferencedDecl(E, E->getDecl()))
3718       return true;
3719 
3720     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
3721   }
3722   bool VisitMemberExpr(const MemberExpr *E) {
3723     if (CheckReferencedDecl(E, E->getMemberDecl())) {
3724       VisitIgnoredValue(E->getBase());
3725       return true;
3726     }
3727 
3728     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
3729   }
3730 
3731   bool VisitCallExpr(const CallExpr *E);
3732   bool VisitBinaryOperator(const BinaryOperator *E);
3733   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
3734   bool VisitUnaryOperator(const UnaryOperator *E);
3735 
3736   bool VisitCastExpr(const CastExpr* E);
3737   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
3738 
3739   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
3740     return Success(E->getValue(), E);
3741   }
3742 
3743   // Note, GNU defines __null as an integer, not a pointer.
3744   bool VisitGNUNullExpr(const GNUNullExpr *E) {
3745     return ZeroInitialization(E);
3746   }
3747 
3748   bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
3749     return Success(E->getValue(), E);
3750   }
3751 
3752   bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
3753     return Success(E->getValue(), E);
3754   }
3755 
3756   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
3757     return Success(E->getValue(), E);
3758   }
3759 
3760   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3761     return Success(E->getValue(), E);
3762   }
3763 
3764   bool VisitUnaryReal(const UnaryOperator *E);
3765   bool VisitUnaryImag(const UnaryOperator *E);
3766 
3767   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
3768   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
3769 
3770 private:
3771   CharUnits GetAlignOfExpr(const Expr *E);
3772   CharUnits GetAlignOfType(QualType T);
3773   static QualType GetObjectType(APValue::LValueBase B);
3774   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
3775   // FIXME: Missing: array subscript of vector, member of vector
3776 };
3777 } // end anonymous namespace
3778 
3779 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
3780 /// produce either the integer value or a pointer.
3781 ///
3782 /// GCC has a heinous extension which folds casts between pointer types and
3783 /// pointer-sized integral types. We support this by allowing the evaluation of
3784 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
3785 /// Some simple arithmetic on such values is supported (they are treated much
3786 /// like char*).
3787 static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
3788                                     EvalInfo &Info) {
3789   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
3790   return IntExprEvaluator(Info, Result).Visit(E);
3791 }
3792 
3793 static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
3794   CCValue Val;
3795   if (!EvaluateIntegerOrLValue(E, Val, Info))
3796     return false;
3797   if (!Val.isInt()) {
3798     // FIXME: It would be better to produce the diagnostic for casting
3799     //        a pointer to an integer.
3800     Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
3801     return false;
3802   }
3803   Result = Val.getInt();
3804   return true;
3805 }
3806 
3807 /// Check whether the given declaration can be directly converted to an integral
3808 /// rvalue. If not, no diagnostic is produced; there are other things we can
3809 /// try.
3810 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
3811   // Enums are integer constant exprs.
3812   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
3813     // Check for signedness/width mismatches between E type and ECD value.
3814     bool SameSign = (ECD->getInitVal().isSigned()
3815                      == E->getType()->isSignedIntegerOrEnumerationType());
3816     bool SameWidth = (ECD->getInitVal().getBitWidth()
3817                       == Info.Ctx.getIntWidth(E->getType()));
3818     if (SameSign && SameWidth)
3819       return Success(ECD->getInitVal(), E);
3820     else {
3821       // Get rid of mismatch (otherwise Success assertions will fail)
3822       // by computing a new value matching the type of E.
3823       llvm::APSInt Val = ECD->getInitVal();
3824       if (!SameSign)
3825         Val.setIsSigned(!ECD->getInitVal().isSigned());
3826       if (!SameWidth)
3827         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
3828       return Success(Val, E);
3829     }
3830   }
3831   return false;
3832 }
3833 
3834 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
3835 /// as GCC.
3836 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
3837   // The following enum mimics the values returned by GCC.
3838   // FIXME: Does GCC differ between lvalue and rvalue references here?
3839   enum gcc_type_class {
3840     no_type_class = -1,
3841     void_type_class, integer_type_class, char_type_class,
3842     enumeral_type_class, boolean_type_class,
3843     pointer_type_class, reference_type_class, offset_type_class,
3844     real_type_class, complex_type_class,
3845     function_type_class, method_type_class,
3846     record_type_class, union_type_class,
3847     array_type_class, string_type_class,
3848     lang_type_class
3849   };
3850 
3851   // If no argument was supplied, default to "no_type_class". This isn't
3852   // ideal, however it is what gcc does.
3853   if (E->getNumArgs() == 0)
3854     return no_type_class;
3855 
3856   QualType ArgTy = E->getArg(0)->getType();
3857   if (ArgTy->isVoidType())
3858     return void_type_class;
3859   else if (ArgTy->isEnumeralType())
3860     return enumeral_type_class;
3861   else if (ArgTy->isBooleanType())
3862     return boolean_type_class;
3863   else if (ArgTy->isCharType())
3864     return string_type_class; // gcc doesn't appear to use char_type_class
3865   else if (ArgTy->isIntegerType())
3866     return integer_type_class;
3867   else if (ArgTy->isPointerType())
3868     return pointer_type_class;
3869   else if (ArgTy->isReferenceType())
3870     return reference_type_class;
3871   else if (ArgTy->isRealType())
3872     return real_type_class;
3873   else if (ArgTy->isComplexType())
3874     return complex_type_class;
3875   else if (ArgTy->isFunctionType())
3876     return function_type_class;
3877   else if (ArgTy->isStructureOrClassType())
3878     return record_type_class;
3879   else if (ArgTy->isUnionType())
3880     return union_type_class;
3881   else if (ArgTy->isArrayType())
3882     return array_type_class;
3883   else if (ArgTy->isUnionType())
3884     return union_type_class;
3885   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
3886     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
3887 }
3888 
3889 /// EvaluateBuiltinConstantPForLValue - Determine the result of
3890 /// __builtin_constant_p when applied to the given lvalue.
3891 ///
3892 /// An lvalue is only "constant" if it is a pointer or reference to the first
3893 /// character of a string literal.
3894 template<typename LValue>
3895 static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
3896   const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
3897   return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
3898 }
3899 
3900 /// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
3901 /// GCC as we can manage.
3902 static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
3903   QualType ArgType = Arg->getType();
3904 
3905   // __builtin_constant_p always has one operand. The rules which gcc follows
3906   // are not precisely documented, but are as follows:
3907   //
3908   //  - If the operand is of integral, floating, complex or enumeration type,
3909   //    and can be folded to a known value of that type, it returns 1.
3910   //  - If the operand and can be folded to a pointer to the first character
3911   //    of a string literal (or such a pointer cast to an integral type), it
3912   //    returns 1.
3913   //
3914   // Otherwise, it returns 0.
3915   //
3916   // FIXME: GCC also intends to return 1 for literals of aggregate types, but
3917   // its support for this does not currently work.
3918   if (ArgType->isIntegralOrEnumerationType()) {
3919     Expr::EvalResult Result;
3920     if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
3921       return false;
3922 
3923     APValue &V = Result.Val;
3924     if (V.getKind() == APValue::Int)
3925       return true;
3926 
3927     return EvaluateBuiltinConstantPForLValue(V);
3928   } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
3929     return Arg->isEvaluatable(Ctx);
3930   } else if (ArgType->isPointerType() || Arg->isGLValue()) {
3931     LValue LV;
3932     Expr::EvalStatus Status;
3933     EvalInfo Info(Ctx, Status);
3934     if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
3935                           : EvaluatePointer(Arg, LV, Info)) &&
3936         !Status.HasSideEffects)
3937       return EvaluateBuiltinConstantPForLValue(LV);
3938   }
3939 
3940   // Anything else isn't considered to be sufficiently constant.
3941   return false;
3942 }
3943 
3944 /// Retrieves the "underlying object type" of the given expression,
3945 /// as used by __builtin_object_size.
3946 QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
3947   if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
3948     if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3949       return VD->getType();
3950   } else if (const Expr *E = B.get<const Expr*>()) {
3951     if (isa<CompoundLiteralExpr>(E))
3952       return E->getType();
3953   }
3954 
3955   return QualType();
3956 }
3957 
3958 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
3959   // TODO: Perhaps we should let LLVM lower this?
3960   LValue Base;
3961   if (!EvaluatePointer(E->getArg(0), Base, Info))
3962     return false;
3963 
3964   // If we can prove the base is null, lower to zero now.
3965   if (!Base.getLValueBase()) return Success(0, E);
3966 
3967   QualType T = GetObjectType(Base.getLValueBase());
3968   if (T.isNull() ||
3969       T->isIncompleteType() ||
3970       T->isFunctionType() ||
3971       T->isVariablyModifiedType() ||
3972       T->isDependentType())
3973     return Error(E);
3974 
3975   CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
3976   CharUnits Offset = Base.getLValueOffset();
3977 
3978   if (!Offset.isNegative() && Offset <= Size)
3979     Size -= Offset;
3980   else
3981     Size = CharUnits::Zero();
3982   return Success(Size, E);
3983 }
3984 
3985 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
3986   switch (E->isBuiltinCall()) {
3987   default:
3988     return ExprEvaluatorBaseTy::VisitCallExpr(E);
3989 
3990   case Builtin::BI__builtin_object_size: {
3991     if (TryEvaluateBuiltinObjectSize(E))
3992       return true;
3993 
3994     // If evaluating the argument has side-effects we can't determine
3995     // the size of the object and lower it to unknown now.
3996     if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
3997       if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
3998         return Success(-1ULL, E);
3999       return Success(0, E);
4000     }
4001 
4002     return Error(E);
4003   }
4004 
4005   case Builtin::BI__builtin_classify_type:
4006     return Success(EvaluateBuiltinClassifyType(E), E);
4007 
4008   case Builtin::BI__builtin_constant_p:
4009     return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
4010 
4011   case Builtin::BI__builtin_eh_return_data_regno: {
4012     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
4013     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
4014     return Success(Operand, E);
4015   }
4016 
4017   case Builtin::BI__builtin_expect:
4018     return Visit(E->getArg(0));
4019 
4020   case Builtin::BIstrlen:
4021     // A call to strlen is not a constant expression.
4022     if (Info.getLangOpts().CPlusPlus0x)
4023       Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4024         << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4025     else
4026       Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4027     // Fall through.
4028   case Builtin::BI__builtin_strlen:
4029     // As an extension, we support strlen() and __builtin_strlen() as constant
4030     // expressions when the argument is a string literal.
4031     if (const StringLiteral *S
4032                = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4033       // The string literal may have embedded null characters. Find the first
4034       // one and truncate there.
4035       StringRef Str = S->getString();
4036       StringRef::size_type Pos = Str.find(0);
4037       if (Pos != StringRef::npos)
4038         Str = Str.substr(0, Pos);
4039 
4040       return Success(Str.size(), E);
4041     }
4042 
4043     return Error(E);
4044 
4045   case Builtin::BI__atomic_is_lock_free: {
4046     APSInt SizeVal;
4047     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4048       return false;
4049 
4050     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4051     // of two less than the maximum inline atomic width, we know it is
4052     // lock-free.  If the size isn't a power of two, or greater than the
4053     // maximum alignment where we promote atomics, we know it is not lock-free
4054     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
4055     // the answer can only be determined at runtime; for example, 16-byte
4056     // atomics have lock-free implementations on some, but not all,
4057     // x86-64 processors.
4058 
4059     // Check power-of-two.
4060     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4061     if (!Size.isPowerOfTwo())
4062 #if 0
4063       // FIXME: Suppress this folding until the ABI for the promotion width
4064       // settles.
4065       return Success(0, E);
4066 #else
4067       return Error(E);
4068 #endif
4069 
4070 #if 0
4071     // Check against promotion width.
4072     // FIXME: Suppress this folding until the ABI for the promotion width
4073     // settles.
4074     unsigned PromoteWidthBits =
4075         Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4076     if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4077       return Success(0, E);
4078 #endif
4079 
4080     // Check against inlining width.
4081     unsigned InlineWidthBits =
4082         Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4083     if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4084       return Success(1, E);
4085 
4086     return Error(E);
4087   }
4088   }
4089 }
4090 
4091 static bool HasSameBase(const LValue &A, const LValue &B) {
4092   if (!A.getLValueBase())
4093     return !B.getLValueBase();
4094   if (!B.getLValueBase())
4095     return false;
4096 
4097   if (A.getLValueBase().getOpaqueValue() !=
4098       B.getLValueBase().getOpaqueValue()) {
4099     const Decl *ADecl = GetLValueBaseDecl(A);
4100     if (!ADecl)
4101       return false;
4102     const Decl *BDecl = GetLValueBaseDecl(B);
4103     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
4104       return false;
4105   }
4106 
4107   return IsGlobalLValue(A.getLValueBase()) ||
4108          A.getLValueFrame() == B.getLValueFrame();
4109 }
4110 
4111 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4112   if (E->isAssignmentOp())
4113     return Error(E);
4114 
4115   if (E->getOpcode() == BO_Comma) {
4116     VisitIgnoredValue(E->getLHS());
4117     return Visit(E->getRHS());
4118   }
4119 
4120   if (E->isLogicalOp()) {
4121     // These need to be handled specially because the operands aren't
4122     // necessarily integral
4123     bool lhsResult, rhsResult;
4124 
4125     if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4126       // We were able to evaluate the LHS, see if we can get away with not
4127       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4128       if (lhsResult == (E->getOpcode() == BO_LOr))
4129         return Success(lhsResult, E);
4130 
4131       if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4132         if (E->getOpcode() == BO_LOr)
4133           return Success(lhsResult || rhsResult, E);
4134         else
4135           return Success(lhsResult && rhsResult, E);
4136       }
4137     } else {
4138       // FIXME: If both evaluations fail, we should produce the diagnostic from
4139       // the LHS. If the LHS is non-constant and the RHS is unevaluatable, it's
4140       // less clear how to diagnose this.
4141       if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4142         // We can't evaluate the LHS; however, sometimes the result
4143         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4144         if (rhsResult == (E->getOpcode() == BO_LOr)) {
4145           // Since we weren't able to evaluate the left hand side, it
4146           // must have had side effects.
4147           Info.EvalStatus.HasSideEffects = true;
4148 
4149           return Success(rhsResult, E);
4150         }
4151       }
4152     }
4153 
4154     return false;
4155   }
4156 
4157   QualType LHSTy = E->getLHS()->getType();
4158   QualType RHSTy = E->getRHS()->getType();
4159 
4160   if (LHSTy->isAnyComplexType()) {
4161     assert(RHSTy->isAnyComplexType() && "Invalid comparison");
4162     ComplexValue LHS, RHS;
4163 
4164     bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4165     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4166       return false;
4167 
4168     if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
4169       return false;
4170 
4171     if (LHS.isComplexFloat()) {
4172       APFloat::cmpResult CR_r =
4173         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
4174       APFloat::cmpResult CR_i =
4175         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4176 
4177       if (E->getOpcode() == BO_EQ)
4178         return Success((CR_r == APFloat::cmpEqual &&
4179                         CR_i == APFloat::cmpEqual), E);
4180       else {
4181         assert(E->getOpcode() == BO_NE &&
4182                "Invalid complex comparison.");
4183         return Success(((CR_r == APFloat::cmpGreaterThan ||
4184                          CR_r == APFloat::cmpLessThan ||
4185                          CR_r == APFloat::cmpUnordered) ||
4186                         (CR_i == APFloat::cmpGreaterThan ||
4187                          CR_i == APFloat::cmpLessThan ||
4188                          CR_i == APFloat::cmpUnordered)), E);
4189       }
4190     } else {
4191       if (E->getOpcode() == BO_EQ)
4192         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4193                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4194       else {
4195         assert(E->getOpcode() == BO_NE &&
4196                "Invalid compex comparison.");
4197         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4198                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4199       }
4200     }
4201   }
4202 
4203   if (LHSTy->isRealFloatingType() &&
4204       RHSTy->isRealFloatingType()) {
4205     APFloat RHS(0.0), LHS(0.0);
4206 
4207     bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4208     if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4209       return false;
4210 
4211     if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
4212       return false;
4213 
4214     APFloat::cmpResult CR = LHS.compare(RHS);
4215 
4216     switch (E->getOpcode()) {
4217     default:
4218       llvm_unreachable("Invalid binary operator!");
4219     case BO_LT:
4220       return Success(CR == APFloat::cmpLessThan, E);
4221     case BO_GT:
4222       return Success(CR == APFloat::cmpGreaterThan, E);
4223     case BO_LE:
4224       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
4225     case BO_GE:
4226       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
4227                      E);
4228     case BO_EQ:
4229       return Success(CR == APFloat::cmpEqual, E);
4230     case BO_NE:
4231       return Success(CR == APFloat::cmpGreaterThan
4232                      || CR == APFloat::cmpLessThan
4233                      || CR == APFloat::cmpUnordered, E);
4234     }
4235   }
4236 
4237   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
4238     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
4239       LValue LHSValue, RHSValue;
4240 
4241       bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4242       if (!LHSOK && Info.keepEvaluatingAfterFailure())
4243         return false;
4244 
4245       if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4246         return false;
4247 
4248       // Reject differing bases from the normal codepath; we special-case
4249       // comparisons to null.
4250       if (!HasSameBase(LHSValue, RHSValue)) {
4251         if (E->getOpcode() == BO_Sub) {
4252           // Handle &&A - &&B.
4253           if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4254             return false;
4255           const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4256           const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4257           if (!LHSExpr || !RHSExpr)
4258             return false;
4259           const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4260           const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4261           if (!LHSAddrExpr || !RHSAddrExpr)
4262             return false;
4263           // Make sure both labels come from the same function.
4264           if (LHSAddrExpr->getLabel()->getDeclContext() !=
4265               RHSAddrExpr->getLabel()->getDeclContext())
4266             return false;
4267           Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4268           return true;
4269         }
4270         // Inequalities and subtractions between unrelated pointers have
4271         // unspecified or undefined behavior.
4272         if (!E->isEqualityOp())
4273           return Error(E);
4274         // A constant address may compare equal to the address of a symbol.
4275         // The one exception is that address of an object cannot compare equal
4276         // to a null pointer constant.
4277         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4278             (!RHSValue.Base && !RHSValue.Offset.isZero()))
4279           return Error(E);
4280         // It's implementation-defined whether distinct literals will have
4281         // distinct addresses. In clang, we do not guarantee the addresses are
4282         // distinct. However, we do know that the address of a literal will be
4283         // non-null.
4284         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4285             LHSValue.Base && RHSValue.Base)
4286           return Error(E);
4287         // We can't tell whether weak symbols will end up pointing to the same
4288         // object.
4289         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
4290           return Error(E);
4291         // Pointers with different bases cannot represent the same object.
4292         // (Note that clang defaults to -fmerge-all-constants, which can
4293         // lead to inconsistent results for comparisons involving the address
4294         // of a constant; this generally doesn't matter in practice.)
4295         return Success(E->getOpcode() == BO_NE, E);
4296       }
4297 
4298       // FIXME: Implement the C++11 restrictions:
4299       //  - Pointer subtractions must be on elements of the same array.
4300       //  - Pointer comparisons must be between members with the same access.
4301 
4302       if (E->getOpcode() == BO_Sub) {
4303         QualType Type = E->getLHS()->getType();
4304         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
4305 
4306         CharUnits ElementSize;
4307         if (!HandleSizeof(Info, ElementType, ElementSize))
4308           return false;
4309 
4310         CharUnits Diff = LHSValue.getLValueOffset() -
4311                              RHSValue.getLValueOffset();
4312         return Success(Diff / ElementSize, E);
4313       }
4314 
4315       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4316       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4317       switch (E->getOpcode()) {
4318       default: llvm_unreachable("missing comparison operator");
4319       case BO_LT: return Success(LHSOffset < RHSOffset, E);
4320       case BO_GT: return Success(LHSOffset > RHSOffset, E);
4321       case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4322       case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4323       case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4324       case BO_NE: return Success(LHSOffset != RHSOffset, E);
4325       }
4326     }
4327   }
4328   if (!LHSTy->isIntegralOrEnumerationType() ||
4329       !RHSTy->isIntegralOrEnumerationType()) {
4330     // We can't continue from here for non-integral types.
4331     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4332   }
4333 
4334   // The LHS of a constant expr is always evaluated and needed.
4335   CCValue LHSVal;
4336 
4337   bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4338   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4339     return false;
4340 
4341   if (!Visit(E->getRHS()) || !LHSOK)
4342     return false;
4343 
4344   CCValue &RHSVal = Result;
4345 
4346   // Handle cases like (unsigned long)&a + 4.
4347   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4348     CharUnits AdditionalOffset = CharUnits::fromQuantity(
4349                                      RHSVal.getInt().getZExtValue());
4350     if (E->getOpcode() == BO_Add)
4351       LHSVal.getLValueOffset() += AdditionalOffset;
4352     else
4353       LHSVal.getLValueOffset() -= AdditionalOffset;
4354     Result = LHSVal;
4355     return true;
4356   }
4357 
4358   // Handle cases like 4 + (unsigned long)&a
4359   if (E->getOpcode() == BO_Add &&
4360         RHSVal.isLValue() && LHSVal.isInt()) {
4361     RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4362                                     LHSVal.getInt().getZExtValue());
4363     // Note that RHSVal is Result.
4364     return true;
4365   }
4366 
4367   if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4368     // Handle (intptr_t)&&A - (intptr_t)&&B.
4369     if (!LHSVal.getLValueOffset().isZero() ||
4370         !RHSVal.getLValueOffset().isZero())
4371       return false;
4372     const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4373     const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4374     if (!LHSExpr || !RHSExpr)
4375       return false;
4376     const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4377     const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4378     if (!LHSAddrExpr || !RHSAddrExpr)
4379       return false;
4380     // Make sure both labels come from the same function.
4381     if (LHSAddrExpr->getLabel()->getDeclContext() !=
4382         RHSAddrExpr->getLabel()->getDeclContext())
4383       return false;
4384     Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4385     return true;
4386   }
4387 
4388   // All the following cases expect both operands to be an integer
4389   if (!LHSVal.isInt() || !RHSVal.isInt())
4390     return Error(E);
4391 
4392   APSInt &LHS = LHSVal.getInt();
4393   APSInt &RHS = RHSVal.getInt();
4394 
4395   switch (E->getOpcode()) {
4396   default:
4397     return Error(E);
4398   case BO_Mul: return Success(LHS * RHS, E);
4399   case BO_Add: return Success(LHS + RHS, E);
4400   case BO_Sub: return Success(LHS - RHS, E);
4401   case BO_And: return Success(LHS & RHS, E);
4402   case BO_Xor: return Success(LHS ^ RHS, E);
4403   case BO_Or:  return Success(LHS | RHS, E);
4404   case BO_Div:
4405     if (RHS == 0)
4406       return Error(E, diag::note_expr_divide_by_zero);
4407     return Success(LHS / RHS, E);
4408   case BO_Rem:
4409     if (RHS == 0)
4410       return Error(E, diag::note_expr_divide_by_zero);
4411     return Success(LHS % RHS, E);
4412   case BO_Shl: {
4413     // During constant-folding, a negative shift is an opposite shift.
4414     if (RHS.isSigned() && RHS.isNegative()) {
4415       RHS = -RHS;
4416       goto shift_right;
4417     }
4418 
4419   shift_left:
4420     unsigned SA
4421       = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4422     return Success(LHS << SA, E);
4423   }
4424   case BO_Shr: {
4425     // During constant-folding, a negative shift is an opposite shift.
4426     if (RHS.isSigned() && RHS.isNegative()) {
4427       RHS = -RHS;
4428       goto shift_left;
4429     }
4430 
4431   shift_right:
4432     unsigned SA =
4433       (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4434     return Success(LHS >> SA, E);
4435   }
4436 
4437   case BO_LT: return Success(LHS < RHS, E);
4438   case BO_GT: return Success(LHS > RHS, E);
4439   case BO_LE: return Success(LHS <= RHS, E);
4440   case BO_GE: return Success(LHS >= RHS, E);
4441   case BO_EQ: return Success(LHS == RHS, E);
4442   case BO_NE: return Success(LHS != RHS, E);
4443   }
4444 }
4445 
4446 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
4447   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4448   //   the result is the size of the referenced type."
4449   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4450   //   result shall be the alignment of the referenced type."
4451   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4452     T = Ref->getPointeeType();
4453 
4454   // __alignof is defined to return the preferred alignment.
4455   return Info.Ctx.toCharUnitsFromBits(
4456     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
4457 }
4458 
4459 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
4460   E = E->IgnoreParens();
4461 
4462   // alignof decl is always accepted, even if it doesn't make sense: we default
4463   // to 1 in those cases.
4464   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4465     return Info.Ctx.getDeclAlign(DRE->getDecl(),
4466                                  /*RefAsPointee*/true);
4467 
4468   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
4469     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4470                                  /*RefAsPointee*/true);
4471 
4472   return GetAlignOfType(E->getType());
4473 }
4474 
4475 
4476 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4477 /// a result as the expression's type.
4478 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4479                                     const UnaryExprOrTypeTraitExpr *E) {
4480   switch(E->getKind()) {
4481   case UETT_AlignOf: {
4482     if (E->isArgumentType())
4483       return Success(GetAlignOfType(E->getArgumentType()), E);
4484     else
4485       return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
4486   }
4487 
4488   case UETT_VecStep: {
4489     QualType Ty = E->getTypeOfArgument();
4490 
4491     if (Ty->isVectorType()) {
4492       unsigned n = Ty->getAs<VectorType>()->getNumElements();
4493 
4494       // The vec_step built-in functions that take a 3-component
4495       // vector return 4. (OpenCL 1.1 spec 6.11.12)
4496       if (n == 3)
4497         n = 4;
4498 
4499       return Success(n, E);
4500     } else
4501       return Success(1, E);
4502   }
4503 
4504   case UETT_SizeOf: {
4505     QualType SrcTy = E->getTypeOfArgument();
4506     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4507     //   the result is the size of the referenced type."
4508     // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4509     //   result shall be the alignment of the referenced type."
4510     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4511       SrcTy = Ref->getPointeeType();
4512 
4513     CharUnits Sizeof;
4514     if (!HandleSizeof(Info, SrcTy, Sizeof))
4515       return false;
4516     return Success(Sizeof, E);
4517   }
4518   }
4519 
4520   llvm_unreachable("unknown expr/type trait");
4521 }
4522 
4523 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
4524   CharUnits Result;
4525   unsigned n = OOE->getNumComponents();
4526   if (n == 0)
4527     return Error(OOE);
4528   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
4529   for (unsigned i = 0; i != n; ++i) {
4530     OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
4531     switch (ON.getKind()) {
4532     case OffsetOfExpr::OffsetOfNode::Array: {
4533       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
4534       APSInt IdxResult;
4535       if (!EvaluateInteger(Idx, IdxResult, Info))
4536         return false;
4537       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
4538       if (!AT)
4539         return Error(OOE);
4540       CurrentType = AT->getElementType();
4541       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
4542       Result += IdxResult.getSExtValue() * ElementSize;
4543         break;
4544     }
4545 
4546     case OffsetOfExpr::OffsetOfNode::Field: {
4547       FieldDecl *MemberDecl = ON.getField();
4548       const RecordType *RT = CurrentType->getAs<RecordType>();
4549       if (!RT)
4550         return Error(OOE);
4551       RecordDecl *RD = RT->getDecl();
4552       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4553       unsigned i = MemberDecl->getFieldIndex();
4554       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
4555       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
4556       CurrentType = MemberDecl->getType().getNonReferenceType();
4557       break;
4558     }
4559 
4560     case OffsetOfExpr::OffsetOfNode::Identifier:
4561       llvm_unreachable("dependent __builtin_offsetof");
4562 
4563     case OffsetOfExpr::OffsetOfNode::Base: {
4564       CXXBaseSpecifier *BaseSpec = ON.getBase();
4565       if (BaseSpec->isVirtual())
4566         return Error(OOE);
4567 
4568       // Find the layout of the class whose base we are looking into.
4569       const RecordType *RT = CurrentType->getAs<RecordType>();
4570       if (!RT)
4571         return Error(OOE);
4572       RecordDecl *RD = RT->getDecl();
4573       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
4574 
4575       // Find the base class itself.
4576       CurrentType = BaseSpec->getType();
4577       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
4578       if (!BaseRT)
4579         return Error(OOE);
4580 
4581       // Add the offset to the base.
4582       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
4583       break;
4584     }
4585     }
4586   }
4587   return Success(Result, OOE);
4588 }
4589 
4590 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4591   switch (E->getOpcode()) {
4592   default:
4593     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
4594     // See C99 6.6p3.
4595     return Error(E);
4596   case UO_Extension:
4597     // FIXME: Should extension allow i-c-e extension expressions in its scope?
4598     // If so, we could clear the diagnostic ID.
4599     return Visit(E->getSubExpr());
4600   case UO_Plus:
4601     // The result is just the value.
4602     return Visit(E->getSubExpr());
4603   case UO_Minus: {
4604     if (!Visit(E->getSubExpr()))
4605       return false;
4606     if (!Result.isInt()) return Error(E);
4607     return Success(-Result.getInt(), E);
4608   }
4609   case UO_Not: {
4610     if (!Visit(E->getSubExpr()))
4611       return false;
4612     if (!Result.isInt()) return Error(E);
4613     return Success(~Result.getInt(), E);
4614   }
4615   case UO_LNot: {
4616     bool bres;
4617     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
4618       return false;
4619     return Success(!bres, E);
4620   }
4621   }
4622 }
4623 
4624 /// HandleCast - This is used to evaluate implicit or explicit casts where the
4625 /// result type is integer.
4626 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
4627   const Expr *SubExpr = E->getSubExpr();
4628   QualType DestType = E->getType();
4629   QualType SrcType = SubExpr->getType();
4630 
4631   switch (E->getCastKind()) {
4632   case CK_BaseToDerived:
4633   case CK_DerivedToBase:
4634   case CK_UncheckedDerivedToBase:
4635   case CK_Dynamic:
4636   case CK_ToUnion:
4637   case CK_ArrayToPointerDecay:
4638   case CK_FunctionToPointerDecay:
4639   case CK_NullToPointer:
4640   case CK_NullToMemberPointer:
4641   case CK_BaseToDerivedMemberPointer:
4642   case CK_DerivedToBaseMemberPointer:
4643   case CK_ConstructorConversion:
4644   case CK_IntegralToPointer:
4645   case CK_ToVoid:
4646   case CK_VectorSplat:
4647   case CK_IntegralToFloating:
4648   case CK_FloatingCast:
4649   case CK_CPointerToObjCPointerCast:
4650   case CK_BlockPointerToObjCPointerCast:
4651   case CK_AnyPointerToBlockPointerCast:
4652   case CK_ObjCObjectLValueCast:
4653   case CK_FloatingRealToComplex:
4654   case CK_FloatingComplexToReal:
4655   case CK_FloatingComplexCast:
4656   case CK_FloatingComplexToIntegralComplex:
4657   case CK_IntegralRealToComplex:
4658   case CK_IntegralComplexCast:
4659   case CK_IntegralComplexToFloatingComplex:
4660     llvm_unreachable("invalid cast kind for integral value");
4661 
4662   case CK_BitCast:
4663   case CK_Dependent:
4664   case CK_LValueBitCast:
4665   case CK_ARCProduceObject:
4666   case CK_ARCConsumeObject:
4667   case CK_ARCReclaimReturnedObject:
4668   case CK_ARCExtendBlockObject:
4669     return Error(E);
4670 
4671   case CK_UserDefinedConversion:
4672   case CK_LValueToRValue:
4673   case CK_AtomicToNonAtomic:
4674   case CK_NonAtomicToAtomic:
4675   case CK_NoOp:
4676     return ExprEvaluatorBaseTy::VisitCastExpr(E);
4677 
4678   case CK_MemberPointerToBoolean:
4679   case CK_PointerToBoolean:
4680   case CK_IntegralToBoolean:
4681   case CK_FloatingToBoolean:
4682   case CK_FloatingComplexToBoolean:
4683   case CK_IntegralComplexToBoolean: {
4684     bool BoolResult;
4685     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
4686       return false;
4687     return Success(BoolResult, E);
4688   }
4689 
4690   case CK_IntegralCast: {
4691     if (!Visit(SubExpr))
4692       return false;
4693 
4694     if (!Result.isInt()) {
4695       // Allow casts of address-of-label differences if they are no-ops
4696       // or narrowing.  (The narrowing case isn't actually guaranteed to
4697       // be constant-evaluatable except in some narrow cases which are hard
4698       // to detect here.  We let it through on the assumption the user knows
4699       // what they are doing.)
4700       if (Result.isAddrLabelDiff())
4701         return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
4702       // Only allow casts of lvalues if they are lossless.
4703       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
4704     }
4705 
4706     return Success(HandleIntToIntCast(DestType, SrcType,
4707                                       Result.getInt(), Info.Ctx), E);
4708   }
4709 
4710   case CK_PointerToIntegral: {
4711     CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4712 
4713     LValue LV;
4714     if (!EvaluatePointer(SubExpr, LV, Info))
4715       return false;
4716 
4717     if (LV.getLValueBase()) {
4718       // Only allow based lvalue casts if they are lossless.
4719       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
4720         return Error(E);
4721 
4722       LV.Designator.setInvalid();
4723       LV.moveInto(Result);
4724       return true;
4725     }
4726 
4727     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
4728                                          SrcType);
4729     return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
4730   }
4731 
4732   case CK_IntegralComplexToReal: {
4733     ComplexValue C;
4734     if (!EvaluateComplex(SubExpr, C, Info))
4735       return false;
4736     return Success(C.getComplexIntReal(), E);
4737   }
4738 
4739   case CK_FloatingToIntegral: {
4740     APFloat F(0.0);
4741     if (!EvaluateFloat(SubExpr, F, Info))
4742       return false;
4743 
4744     APSInt Value;
4745     if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
4746       return false;
4747     return Success(Value, E);
4748   }
4749   }
4750 
4751   llvm_unreachable("unknown cast resulting in integral value");
4752 }
4753 
4754 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4755   if (E->getSubExpr()->getType()->isAnyComplexType()) {
4756     ComplexValue LV;
4757     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4758       return false;
4759     if (!LV.isComplexInt())
4760       return Error(E);
4761     return Success(LV.getComplexIntReal(), E);
4762   }
4763 
4764   return Visit(E->getSubExpr());
4765 }
4766 
4767 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4768   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
4769     ComplexValue LV;
4770     if (!EvaluateComplex(E->getSubExpr(), LV, Info))
4771       return false;
4772     if (!LV.isComplexInt())
4773       return Error(E);
4774     return Success(LV.getComplexIntImag(), E);
4775   }
4776 
4777   VisitIgnoredValue(E->getSubExpr());
4778   return Success(0, E);
4779 }
4780 
4781 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
4782   return Success(E->getPackLength(), E);
4783 }
4784 
4785 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
4786   return Success(E->getValue(), E);
4787 }
4788 
4789 //===----------------------------------------------------------------------===//
4790 // Float Evaluation
4791 //===----------------------------------------------------------------------===//
4792 
4793 namespace {
4794 class FloatExprEvaluator
4795   : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
4796   APFloat &Result;
4797 public:
4798   FloatExprEvaluator(EvalInfo &info, APFloat &result)
4799     : ExprEvaluatorBaseTy(info), Result(result) {}
4800 
4801   bool Success(const CCValue &V, const Expr *e) {
4802     Result = V.getFloat();
4803     return true;
4804   }
4805 
4806   bool ZeroInitialization(const Expr *E) {
4807     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
4808     return true;
4809   }
4810 
4811   bool VisitCallExpr(const CallExpr *E);
4812 
4813   bool VisitUnaryOperator(const UnaryOperator *E);
4814   bool VisitBinaryOperator(const BinaryOperator *E);
4815   bool VisitFloatingLiteral(const FloatingLiteral *E);
4816   bool VisitCastExpr(const CastExpr *E);
4817 
4818   bool VisitUnaryReal(const UnaryOperator *E);
4819   bool VisitUnaryImag(const UnaryOperator *E);
4820 
4821   // FIXME: Missing: array subscript of vector, member of vector
4822 };
4823 } // end anonymous namespace
4824 
4825 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
4826   assert(E->isRValue() && E->getType()->isRealFloatingType());
4827   return FloatExprEvaluator(Info, Result).Visit(E);
4828 }
4829 
4830 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
4831                                   QualType ResultTy,
4832                                   const Expr *Arg,
4833                                   bool SNaN,
4834                                   llvm::APFloat &Result) {
4835   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
4836   if (!S) return false;
4837 
4838   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
4839 
4840   llvm::APInt fill;
4841 
4842   // Treat empty strings as if they were zero.
4843   if (S->getString().empty())
4844     fill = llvm::APInt(32, 0);
4845   else if (S->getString().getAsInteger(0, fill))
4846     return false;
4847 
4848   if (SNaN)
4849     Result = llvm::APFloat::getSNaN(Sem, false, &fill);
4850   else
4851     Result = llvm::APFloat::getQNaN(Sem, false, &fill);
4852   return true;
4853 }
4854 
4855 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
4856   switch (E->isBuiltinCall()) {
4857   default:
4858     return ExprEvaluatorBaseTy::VisitCallExpr(E);
4859 
4860   case Builtin::BI__builtin_huge_val:
4861   case Builtin::BI__builtin_huge_valf:
4862   case Builtin::BI__builtin_huge_vall:
4863   case Builtin::BI__builtin_inf:
4864   case Builtin::BI__builtin_inff:
4865   case Builtin::BI__builtin_infl: {
4866     const llvm::fltSemantics &Sem =
4867       Info.Ctx.getFloatTypeSemantics(E->getType());
4868     Result = llvm::APFloat::getInf(Sem);
4869     return true;
4870   }
4871 
4872   case Builtin::BI__builtin_nans:
4873   case Builtin::BI__builtin_nansf:
4874   case Builtin::BI__builtin_nansl:
4875     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4876                                true, Result))
4877       return Error(E);
4878     return true;
4879 
4880   case Builtin::BI__builtin_nan:
4881   case Builtin::BI__builtin_nanf:
4882   case Builtin::BI__builtin_nanl:
4883     // If this is __builtin_nan() turn this into a nan, otherwise we
4884     // can't constant fold it.
4885     if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
4886                                false, Result))
4887       return Error(E);
4888     return true;
4889 
4890   case Builtin::BI__builtin_fabs:
4891   case Builtin::BI__builtin_fabsf:
4892   case Builtin::BI__builtin_fabsl:
4893     if (!EvaluateFloat(E->getArg(0), Result, Info))
4894       return false;
4895 
4896     if (Result.isNegative())
4897       Result.changeSign();
4898     return true;
4899 
4900   case Builtin::BI__builtin_copysign:
4901   case Builtin::BI__builtin_copysignf:
4902   case Builtin::BI__builtin_copysignl: {
4903     APFloat RHS(0.);
4904     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
4905         !EvaluateFloat(E->getArg(1), RHS, Info))
4906       return false;
4907     Result.copySign(RHS);
4908     return true;
4909   }
4910   }
4911 }
4912 
4913 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4914   if (E->getSubExpr()->getType()->isAnyComplexType()) {
4915     ComplexValue CV;
4916     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4917       return false;
4918     Result = CV.FloatReal;
4919     return true;
4920   }
4921 
4922   return Visit(E->getSubExpr());
4923 }
4924 
4925 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4926   if (E->getSubExpr()->getType()->isAnyComplexType()) {
4927     ComplexValue CV;
4928     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
4929       return false;
4930     Result = CV.FloatImag;
4931     return true;
4932   }
4933 
4934   VisitIgnoredValue(E->getSubExpr());
4935   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
4936   Result = llvm::APFloat::getZero(Sem);
4937   return true;
4938 }
4939 
4940 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
4941   switch (E->getOpcode()) {
4942   default: return Error(E);
4943   case UO_Plus:
4944     return EvaluateFloat(E->getSubExpr(), Result, Info);
4945   case UO_Minus:
4946     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
4947       return false;
4948     Result.changeSign();
4949     return true;
4950   }
4951 }
4952 
4953 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4954   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
4955     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4956 
4957   APFloat RHS(0.0);
4958   bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
4959   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
4960     return false;
4961   if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
4962     return false;
4963 
4964   switch (E->getOpcode()) {
4965   default: return Error(E);
4966   case BO_Mul:
4967     Result.multiply(RHS, APFloat::rmNearestTiesToEven);
4968     return true;
4969   case BO_Add:
4970     Result.add(RHS, APFloat::rmNearestTiesToEven);
4971     return true;
4972   case BO_Sub:
4973     Result.subtract(RHS, APFloat::rmNearestTiesToEven);
4974     return true;
4975   case BO_Div:
4976     Result.divide(RHS, APFloat::rmNearestTiesToEven);
4977     return true;
4978   }
4979 }
4980 
4981 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
4982   Result = E->getValue();
4983   return true;
4984 }
4985 
4986 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
4987   const Expr* SubExpr = E->getSubExpr();
4988 
4989   switch (E->getCastKind()) {
4990   default:
4991     return ExprEvaluatorBaseTy::VisitCastExpr(E);
4992 
4993   case CK_IntegralToFloating: {
4994     APSInt IntResult;
4995     return EvaluateInteger(SubExpr, IntResult, Info) &&
4996            HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
4997                                 E->getType(), Result);
4998   }
4999 
5000   case CK_FloatingCast: {
5001     if (!Visit(SubExpr))
5002       return false;
5003     return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5004                                   Result);
5005   }
5006 
5007   case CK_FloatingComplexToReal: {
5008     ComplexValue V;
5009     if (!EvaluateComplex(SubExpr, V, Info))
5010       return false;
5011     Result = V.getComplexFloatReal();
5012     return true;
5013   }
5014   }
5015 }
5016 
5017 //===----------------------------------------------------------------------===//
5018 // Complex Evaluation (for float and integer)
5019 //===----------------------------------------------------------------------===//
5020 
5021 namespace {
5022 class ComplexExprEvaluator
5023   : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
5024   ComplexValue &Result;
5025 
5026 public:
5027   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
5028     : ExprEvaluatorBaseTy(info), Result(Result) {}
5029 
5030   bool Success(const CCValue &V, const Expr *e) {
5031     Result.setFrom(V);
5032     return true;
5033   }
5034 
5035   bool ZeroInitialization(const Expr *E);
5036 
5037   //===--------------------------------------------------------------------===//
5038   //                            Visitor Methods
5039   //===--------------------------------------------------------------------===//
5040 
5041   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
5042   bool VisitCastExpr(const CastExpr *E);
5043   bool VisitBinaryOperator(const BinaryOperator *E);
5044   bool VisitUnaryOperator(const UnaryOperator *E);
5045   bool VisitInitListExpr(const InitListExpr *E);
5046 };
5047 } // end anonymous namespace
5048 
5049 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5050                             EvalInfo &Info) {
5051   assert(E->isRValue() && E->getType()->isAnyComplexType());
5052   return ComplexExprEvaluator(Info, Result).Visit(E);
5053 }
5054 
5055 bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
5056   QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
5057   if (ElemTy->isRealFloatingType()) {
5058     Result.makeComplexFloat();
5059     APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5060     Result.FloatReal = Zero;
5061     Result.FloatImag = Zero;
5062   } else {
5063     Result.makeComplexInt();
5064     APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5065     Result.IntReal = Zero;
5066     Result.IntImag = Zero;
5067   }
5068   return true;
5069 }
5070 
5071 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5072   const Expr* SubExpr = E->getSubExpr();
5073 
5074   if (SubExpr->getType()->isRealFloatingType()) {
5075     Result.makeComplexFloat();
5076     APFloat &Imag = Result.FloatImag;
5077     if (!EvaluateFloat(SubExpr, Imag, Info))
5078       return false;
5079 
5080     Result.FloatReal = APFloat(Imag.getSemantics());
5081     return true;
5082   } else {
5083     assert(SubExpr->getType()->isIntegerType() &&
5084            "Unexpected imaginary literal.");
5085 
5086     Result.makeComplexInt();
5087     APSInt &Imag = Result.IntImag;
5088     if (!EvaluateInteger(SubExpr, Imag, Info))
5089       return false;
5090 
5091     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5092     return true;
5093   }
5094 }
5095 
5096 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
5097 
5098   switch (E->getCastKind()) {
5099   case CK_BitCast:
5100   case CK_BaseToDerived:
5101   case CK_DerivedToBase:
5102   case CK_UncheckedDerivedToBase:
5103   case CK_Dynamic:
5104   case CK_ToUnion:
5105   case CK_ArrayToPointerDecay:
5106   case CK_FunctionToPointerDecay:
5107   case CK_NullToPointer:
5108   case CK_NullToMemberPointer:
5109   case CK_BaseToDerivedMemberPointer:
5110   case CK_DerivedToBaseMemberPointer:
5111   case CK_MemberPointerToBoolean:
5112   case CK_ConstructorConversion:
5113   case CK_IntegralToPointer:
5114   case CK_PointerToIntegral:
5115   case CK_PointerToBoolean:
5116   case CK_ToVoid:
5117   case CK_VectorSplat:
5118   case CK_IntegralCast:
5119   case CK_IntegralToBoolean:
5120   case CK_IntegralToFloating:
5121   case CK_FloatingToIntegral:
5122   case CK_FloatingToBoolean:
5123   case CK_FloatingCast:
5124   case CK_CPointerToObjCPointerCast:
5125   case CK_BlockPointerToObjCPointerCast:
5126   case CK_AnyPointerToBlockPointerCast:
5127   case CK_ObjCObjectLValueCast:
5128   case CK_FloatingComplexToReal:
5129   case CK_FloatingComplexToBoolean:
5130   case CK_IntegralComplexToReal:
5131   case CK_IntegralComplexToBoolean:
5132   case CK_ARCProduceObject:
5133   case CK_ARCConsumeObject:
5134   case CK_ARCReclaimReturnedObject:
5135   case CK_ARCExtendBlockObject:
5136     llvm_unreachable("invalid cast kind for complex value");
5137 
5138   case CK_LValueToRValue:
5139   case CK_AtomicToNonAtomic:
5140   case CK_NonAtomicToAtomic:
5141   case CK_NoOp:
5142     return ExprEvaluatorBaseTy::VisitCastExpr(E);
5143 
5144   case CK_Dependent:
5145   case CK_LValueBitCast:
5146   case CK_UserDefinedConversion:
5147     return Error(E);
5148 
5149   case CK_FloatingRealToComplex: {
5150     APFloat &Real = Result.FloatReal;
5151     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
5152       return false;
5153 
5154     Result.makeComplexFloat();
5155     Result.FloatImag = APFloat(Real.getSemantics());
5156     return true;
5157   }
5158 
5159   case CK_FloatingComplexCast: {
5160     if (!Visit(E->getSubExpr()))
5161       return false;
5162 
5163     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5164     QualType From
5165       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5166 
5167     return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5168            HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
5169   }
5170 
5171   case CK_FloatingComplexToIntegralComplex: {
5172     if (!Visit(E->getSubExpr()))
5173       return false;
5174 
5175     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5176     QualType From
5177       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5178     Result.makeComplexInt();
5179     return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5180                                 To, Result.IntReal) &&
5181            HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5182                                 To, Result.IntImag);
5183   }
5184 
5185   case CK_IntegralRealToComplex: {
5186     APSInt &Real = Result.IntReal;
5187     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5188       return false;
5189 
5190     Result.makeComplexInt();
5191     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5192     return true;
5193   }
5194 
5195   case CK_IntegralComplexCast: {
5196     if (!Visit(E->getSubExpr()))
5197       return false;
5198 
5199     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5200     QualType From
5201       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5202 
5203     Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
5204     Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
5205     return true;
5206   }
5207 
5208   case CK_IntegralComplexToFloatingComplex: {
5209     if (!Visit(E->getSubExpr()))
5210       return false;
5211 
5212     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5213     QualType From
5214       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5215     Result.makeComplexFloat();
5216     return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5217                                 To, Result.FloatReal) &&
5218            HandleIntToFloatCast(Info, E, From, Result.IntImag,
5219                                 To, Result.FloatImag);
5220   }
5221   }
5222 
5223   llvm_unreachable("unknown cast resulting in complex value");
5224 }
5225 
5226 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
5227   if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5228     return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5229 
5230   bool LHSOK = Visit(E->getLHS());
5231   if (!LHSOK && !Info.keepEvaluatingAfterFailure())
5232     return false;
5233 
5234   ComplexValue RHS;
5235   if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
5236     return false;
5237 
5238   assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5239          "Invalid operands to binary operator.");
5240   switch (E->getOpcode()) {
5241   default: return Error(E);
5242   case BO_Add:
5243     if (Result.isComplexFloat()) {
5244       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5245                                        APFloat::rmNearestTiesToEven);
5246       Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5247                                        APFloat::rmNearestTiesToEven);
5248     } else {
5249       Result.getComplexIntReal() += RHS.getComplexIntReal();
5250       Result.getComplexIntImag() += RHS.getComplexIntImag();
5251     }
5252     break;
5253   case BO_Sub:
5254     if (Result.isComplexFloat()) {
5255       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5256                                             APFloat::rmNearestTiesToEven);
5257       Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5258                                             APFloat::rmNearestTiesToEven);
5259     } else {
5260       Result.getComplexIntReal() -= RHS.getComplexIntReal();
5261       Result.getComplexIntImag() -= RHS.getComplexIntImag();
5262     }
5263     break;
5264   case BO_Mul:
5265     if (Result.isComplexFloat()) {
5266       ComplexValue LHS = Result;
5267       APFloat &LHS_r = LHS.getComplexFloatReal();
5268       APFloat &LHS_i = LHS.getComplexFloatImag();
5269       APFloat &RHS_r = RHS.getComplexFloatReal();
5270       APFloat &RHS_i = RHS.getComplexFloatImag();
5271 
5272       APFloat Tmp = LHS_r;
5273       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5274       Result.getComplexFloatReal() = Tmp;
5275       Tmp = LHS_i;
5276       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5277       Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5278 
5279       Tmp = LHS_r;
5280       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5281       Result.getComplexFloatImag() = Tmp;
5282       Tmp = LHS_i;
5283       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5284       Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5285     } else {
5286       ComplexValue LHS = Result;
5287       Result.getComplexIntReal() =
5288         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5289          LHS.getComplexIntImag() * RHS.getComplexIntImag());
5290       Result.getComplexIntImag() =
5291         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5292          LHS.getComplexIntImag() * RHS.getComplexIntReal());
5293     }
5294     break;
5295   case BO_Div:
5296     if (Result.isComplexFloat()) {
5297       ComplexValue LHS = Result;
5298       APFloat &LHS_r = LHS.getComplexFloatReal();
5299       APFloat &LHS_i = LHS.getComplexFloatImag();
5300       APFloat &RHS_r = RHS.getComplexFloatReal();
5301       APFloat &RHS_i = RHS.getComplexFloatImag();
5302       APFloat &Res_r = Result.getComplexFloatReal();
5303       APFloat &Res_i = Result.getComplexFloatImag();
5304 
5305       APFloat Den = RHS_r;
5306       Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5307       APFloat Tmp = RHS_i;
5308       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5309       Den.add(Tmp, APFloat::rmNearestTiesToEven);
5310 
5311       Res_r = LHS_r;
5312       Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5313       Tmp = LHS_i;
5314       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5315       Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5316       Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5317 
5318       Res_i = LHS_i;
5319       Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5320       Tmp = LHS_r;
5321       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5322       Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5323       Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5324     } else {
5325       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5326         return Error(E, diag::note_expr_divide_by_zero);
5327 
5328       ComplexValue LHS = Result;
5329       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5330         RHS.getComplexIntImag() * RHS.getComplexIntImag();
5331       Result.getComplexIntReal() =
5332         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5333          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5334       Result.getComplexIntImag() =
5335         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5336          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5337     }
5338     break;
5339   }
5340 
5341   return true;
5342 }
5343 
5344 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5345   // Get the operand value into 'Result'.
5346   if (!Visit(E->getSubExpr()))
5347     return false;
5348 
5349   switch (E->getOpcode()) {
5350   default:
5351     return Error(E);
5352   case UO_Extension:
5353     return true;
5354   case UO_Plus:
5355     // The result is always just the subexpr.
5356     return true;
5357   case UO_Minus:
5358     if (Result.isComplexFloat()) {
5359       Result.getComplexFloatReal().changeSign();
5360       Result.getComplexFloatImag().changeSign();
5361     }
5362     else {
5363       Result.getComplexIntReal() = -Result.getComplexIntReal();
5364       Result.getComplexIntImag() = -Result.getComplexIntImag();
5365     }
5366     return true;
5367   case UO_Not:
5368     if (Result.isComplexFloat())
5369       Result.getComplexFloatImag().changeSign();
5370     else
5371       Result.getComplexIntImag() = -Result.getComplexIntImag();
5372     return true;
5373   }
5374 }
5375 
5376 bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5377   if (E->getNumInits() == 2) {
5378     if (E->getType()->isComplexType()) {
5379       Result.makeComplexFloat();
5380       if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5381         return false;
5382       if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5383         return false;
5384     } else {
5385       Result.makeComplexInt();
5386       if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5387         return false;
5388       if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5389         return false;
5390     }
5391     return true;
5392   }
5393   return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5394 }
5395 
5396 //===----------------------------------------------------------------------===//
5397 // Void expression evaluation, primarily for a cast to void on the LHS of a
5398 // comma operator
5399 //===----------------------------------------------------------------------===//
5400 
5401 namespace {
5402 class VoidExprEvaluator
5403   : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5404 public:
5405   VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5406 
5407   bool Success(const CCValue &V, const Expr *e) { return true; }
5408 
5409   bool VisitCastExpr(const CastExpr *E) {
5410     switch (E->getCastKind()) {
5411     default:
5412       return ExprEvaluatorBaseTy::VisitCastExpr(E);
5413     case CK_ToVoid:
5414       VisitIgnoredValue(E->getSubExpr());
5415       return true;
5416     }
5417   }
5418 };
5419 } // end anonymous namespace
5420 
5421 static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5422   assert(E->isRValue() && E->getType()->isVoidType());
5423   return VoidExprEvaluator(Info).Visit(E);
5424 }
5425 
5426 //===----------------------------------------------------------------------===//
5427 // Top level Expr::EvaluateAsRValue method.
5428 //===----------------------------------------------------------------------===//
5429 
5430 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
5431   // In C, function designators are not lvalues, but we evaluate them as if they
5432   // are.
5433   if (E->isGLValue() || E->getType()->isFunctionType()) {
5434     LValue LV;
5435     if (!EvaluateLValue(E, LV, Info))
5436       return false;
5437     LV.moveInto(Result);
5438   } else if (E->getType()->isVectorType()) {
5439     if (!EvaluateVector(E, Result, Info))
5440       return false;
5441   } else if (E->getType()->isIntegralOrEnumerationType()) {
5442     if (!IntExprEvaluator(Info, Result).Visit(E))
5443       return false;
5444   } else if (E->getType()->hasPointerRepresentation()) {
5445     LValue LV;
5446     if (!EvaluatePointer(E, LV, Info))
5447       return false;
5448     LV.moveInto(Result);
5449   } else if (E->getType()->isRealFloatingType()) {
5450     llvm::APFloat F(0.0);
5451     if (!EvaluateFloat(E, F, Info))
5452       return false;
5453     Result = CCValue(F);
5454   } else if (E->getType()->isAnyComplexType()) {
5455     ComplexValue C;
5456     if (!EvaluateComplex(E, C, Info))
5457       return false;
5458     C.moveInto(Result);
5459   } else if (E->getType()->isMemberPointerType()) {
5460     MemberPtr P;
5461     if (!EvaluateMemberPointer(E, P, Info))
5462       return false;
5463     P.moveInto(Result);
5464     return true;
5465   } else if (E->getType()->isArrayType()) {
5466     LValue LV;
5467     LV.set(E, Info.CurrentCall);
5468     if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
5469       return false;
5470     Result = Info.CurrentCall->Temporaries[E];
5471   } else if (E->getType()->isRecordType()) {
5472     LValue LV;
5473     LV.set(E, Info.CurrentCall);
5474     if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5475       return false;
5476     Result = Info.CurrentCall->Temporaries[E];
5477   } else if (E->getType()->isVoidType()) {
5478     if (Info.getLangOpts().CPlusPlus0x)
5479       Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
5480         << E->getType();
5481     else
5482       Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
5483     if (!EvaluateVoid(E, Info))
5484       return false;
5485   } else if (Info.getLangOpts().CPlusPlus0x) {
5486     Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
5487     return false;
5488   } else {
5489     Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
5490     return false;
5491   }
5492 
5493   return true;
5494 }
5495 
5496 /// EvaluateConstantExpression - Evaluate an expression as a constant expression
5497 /// in-place in an APValue. In some cases, the in-place evaluation is essential,
5498 /// since later initializers for an object can indirectly refer to subobjects
5499 /// which were initialized earlier.
5500 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
5501                                        const LValue &This, const Expr *E,
5502                                        CheckConstantExpressionKind CCEK) {
5503   if (!CheckLiteralType(Info, E))
5504     return false;
5505 
5506   if (E->isRValue()) {
5507     // Evaluate arrays and record types in-place, so that later initializers can
5508     // refer to earlier-initialized members of the object.
5509     if (E->getType()->isArrayType())
5510       return EvaluateArray(E, This, Result, Info);
5511     else if (E->getType()->isRecordType())
5512       return EvaluateRecord(E, This, Result, Info);
5513   }
5514 
5515   // For any other type, in-place evaluation is unimportant.
5516   CCValue CoreConstResult;
5517   return Evaluate(CoreConstResult, Info, E) &&
5518          CheckConstantExpression(Info, E, CoreConstResult, Result, CCEK);
5519 }
5520 
5521 /// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
5522 /// lvalue-to-rvalue cast if it is an lvalue.
5523 static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
5524   if (!CheckLiteralType(Info, E))
5525     return false;
5526 
5527   CCValue Value;
5528   if (!::Evaluate(Value, Info, E))
5529     return false;
5530 
5531   if (E->isGLValue()) {
5532     LValue LV;
5533     LV.setFrom(Value);
5534     if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
5535       return false;
5536   }
5537 
5538   // Check this core constant expression is a constant expression, and if so,
5539   // convert it to one.
5540   return CheckConstantExpression(Info, E, Value, Result);
5541 }
5542 
5543 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
5544 /// any crazy technique (that has nothing to do with language standards) that
5545 /// we want to.  If this function returns true, it returns the folded constant
5546 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
5547 /// will be applied to the result.
5548 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
5549   // Fast-path evaluations of integer literals, since we sometimes see files
5550   // containing vast quantities of these.
5551   if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
5552     Result.Val = APValue(APSInt(L->getValue(),
5553                                 L->getType()->isUnsignedIntegerType()));
5554     return true;
5555   }
5556 
5557   // FIXME: Evaluating values of large array and record types can cause
5558   // performance problems. Only do so in C++11 for now.
5559   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5560       !Ctx.getLangOptions().CPlusPlus0x)
5561     return false;
5562 
5563   EvalInfo Info(Ctx, Result);
5564   return ::EvaluateAsRValue(Info, this, Result.Val);
5565 }
5566 
5567 bool Expr::EvaluateAsBooleanCondition(bool &Result,
5568                                       const ASTContext &Ctx) const {
5569   EvalResult Scratch;
5570   return EvaluateAsRValue(Scratch, Ctx) &&
5571          HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
5572                                         Scratch.Val, CCValue::GlobalValue()),
5573                                 Result);
5574 }
5575 
5576 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
5577                          SideEffectsKind AllowSideEffects) const {
5578   if (!getType()->isIntegralOrEnumerationType())
5579     return false;
5580 
5581   EvalResult ExprResult;
5582   if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
5583       (!AllowSideEffects && ExprResult.HasSideEffects))
5584     return false;
5585 
5586   Result = ExprResult.Val.getInt();
5587   return true;
5588 }
5589 
5590 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
5591   EvalInfo Info(Ctx, Result);
5592 
5593   LValue LV;
5594   return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
5595          CheckLValueConstantExpression(Info, this, LV, Result.Val,
5596                                        CCEK_Constant);
5597 }
5598 
5599 bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
5600                                  const VarDecl *VD,
5601                       llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
5602   // FIXME: Evaluating initializers for large array and record types can cause
5603   // performance problems. Only do so in C++11 for now.
5604   if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
5605       !Ctx.getLangOptions().CPlusPlus0x)
5606     return false;
5607 
5608   Expr::EvalStatus EStatus;
5609   EStatus.Diag = &Notes;
5610 
5611   EvalInfo InitInfo(Ctx, EStatus);
5612   InitInfo.setEvaluatingDecl(VD, Value);
5613 
5614   if (!CheckLiteralType(InitInfo, this))
5615     return false;
5616 
5617   LValue LVal;
5618   LVal.set(VD);
5619 
5620   // C++11 [basic.start.init]p2:
5621   //  Variables with static storage duration or thread storage duration shall be
5622   //  zero-initialized before any other initialization takes place.
5623   // This behavior is not present in C.
5624   if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
5625       !VD->getType()->isReferenceType()) {
5626     ImplicitValueInitExpr VIE(VD->getType());
5627     if (!EvaluateConstantExpression(Value, InitInfo, LVal, &VIE))
5628       return false;
5629   }
5630 
5631   return EvaluateConstantExpression(Value, InitInfo, LVal, this) &&
5632          !EStatus.HasSideEffects;
5633 }
5634 
5635 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
5636 /// constant folded, but discard the result.
5637 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
5638   EvalResult Result;
5639   return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
5640 }
5641 
5642 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
5643   return HasSideEffect(Ctx).Visit(this);
5644 }
5645 
5646 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
5647   EvalResult EvalResult;
5648   bool Result = EvaluateAsRValue(EvalResult, Ctx);
5649   (void)Result;
5650   assert(Result && "Could not evaluate expression");
5651   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
5652 
5653   return EvalResult.Val.getInt();
5654 }
5655 
5656  bool Expr::EvalResult::isGlobalLValue() const {
5657    assert(Val.isLValue());
5658    return IsGlobalLValue(Val.getLValueBase());
5659  }
5660 
5661 
5662 /// isIntegerConstantExpr - this recursive routine will test if an expression is
5663 /// an integer constant expression.
5664 
5665 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
5666 /// comma, etc
5667 ///
5668 /// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
5669 /// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
5670 /// cast+dereference.
5671 
5672 // CheckICE - This function does the fundamental ICE checking: the returned
5673 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
5674 // Note that to reduce code duplication, this helper does no evaluation
5675 // itself; the caller checks whether the expression is evaluatable, and
5676 // in the rare cases where CheckICE actually cares about the evaluated
5677 // value, it calls into Evalute.
5678 //
5679 // Meanings of Val:
5680 // 0: This expression is an ICE.
5681 // 1: This expression is not an ICE, but if it isn't evaluated, it's
5682 //    a legal subexpression for an ICE. This return value is used to handle
5683 //    the comma operator in C99 mode.
5684 // 2: This expression is not an ICE, and is not a legal subexpression for one.
5685 
5686 namespace {
5687 
5688 struct ICEDiag {
5689   unsigned Val;
5690   SourceLocation Loc;
5691 
5692   public:
5693   ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
5694   ICEDiag() : Val(0) {}
5695 };
5696 
5697 }
5698 
5699 static ICEDiag NoDiag() { return ICEDiag(); }
5700 
5701 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
5702   Expr::EvalResult EVResult;
5703   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
5704       !EVResult.Val.isInt()) {
5705     return ICEDiag(2, E->getLocStart());
5706   }
5707   return NoDiag();
5708 }
5709 
5710 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
5711   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
5712   if (!E->getType()->isIntegralOrEnumerationType()) {
5713     return ICEDiag(2, E->getLocStart());
5714   }
5715 
5716   switch (E->getStmtClass()) {
5717 #define ABSTRACT_STMT(Node)
5718 #define STMT(Node, Base) case Expr::Node##Class:
5719 #define EXPR(Node, Base)
5720 #include "clang/AST/StmtNodes.inc"
5721   case Expr::PredefinedExprClass:
5722   case Expr::FloatingLiteralClass:
5723   case Expr::ImaginaryLiteralClass:
5724   case Expr::StringLiteralClass:
5725   case Expr::ArraySubscriptExprClass:
5726   case Expr::MemberExprClass:
5727   case Expr::CompoundAssignOperatorClass:
5728   case Expr::CompoundLiteralExprClass:
5729   case Expr::ExtVectorElementExprClass:
5730   case Expr::DesignatedInitExprClass:
5731   case Expr::ImplicitValueInitExprClass:
5732   case Expr::ParenListExprClass:
5733   case Expr::VAArgExprClass:
5734   case Expr::AddrLabelExprClass:
5735   case Expr::StmtExprClass:
5736   case Expr::CXXMemberCallExprClass:
5737   case Expr::CUDAKernelCallExprClass:
5738   case Expr::CXXDynamicCastExprClass:
5739   case Expr::CXXTypeidExprClass:
5740   case Expr::CXXUuidofExprClass:
5741   case Expr::CXXNullPtrLiteralExprClass:
5742   case Expr::CXXThisExprClass:
5743   case Expr::CXXThrowExprClass:
5744   case Expr::CXXNewExprClass:
5745   case Expr::CXXDeleteExprClass:
5746   case Expr::CXXPseudoDestructorExprClass:
5747   case Expr::UnresolvedLookupExprClass:
5748   case Expr::DependentScopeDeclRefExprClass:
5749   case Expr::CXXConstructExprClass:
5750   case Expr::CXXBindTemporaryExprClass:
5751   case Expr::ExprWithCleanupsClass:
5752   case Expr::CXXTemporaryObjectExprClass:
5753   case Expr::CXXUnresolvedConstructExprClass:
5754   case Expr::CXXDependentScopeMemberExprClass:
5755   case Expr::UnresolvedMemberExprClass:
5756   case Expr::ObjCStringLiteralClass:
5757   case Expr::ObjCEncodeExprClass:
5758   case Expr::ObjCMessageExprClass:
5759   case Expr::ObjCSelectorExprClass:
5760   case Expr::ObjCProtocolExprClass:
5761   case Expr::ObjCIvarRefExprClass:
5762   case Expr::ObjCPropertyRefExprClass:
5763   case Expr::ObjCIsaExprClass:
5764   case Expr::ShuffleVectorExprClass:
5765   case Expr::BlockExprClass:
5766   case Expr::BlockDeclRefExprClass:
5767   case Expr::NoStmtClass:
5768   case Expr::OpaqueValueExprClass:
5769   case Expr::PackExpansionExprClass:
5770   case Expr::SubstNonTypeTemplateParmPackExprClass:
5771   case Expr::AsTypeExprClass:
5772   case Expr::ObjCIndirectCopyRestoreExprClass:
5773   case Expr::MaterializeTemporaryExprClass:
5774   case Expr::PseudoObjectExprClass:
5775   case Expr::AtomicExprClass:
5776   case Expr::InitListExprClass:
5777     return ICEDiag(2, E->getLocStart());
5778 
5779   case Expr::SizeOfPackExprClass:
5780   case Expr::GNUNullExprClass:
5781     // GCC considers the GNU __null value to be an integral constant expression.
5782     return NoDiag();
5783 
5784   case Expr::SubstNonTypeTemplateParmExprClass:
5785     return
5786       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
5787 
5788   case Expr::ParenExprClass:
5789     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
5790   case Expr::GenericSelectionExprClass:
5791     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
5792   case Expr::IntegerLiteralClass:
5793   case Expr::CharacterLiteralClass:
5794   case Expr::CXXBoolLiteralExprClass:
5795   case Expr::CXXScalarValueInitExprClass:
5796   case Expr::UnaryTypeTraitExprClass:
5797   case Expr::BinaryTypeTraitExprClass:
5798   case Expr::ArrayTypeTraitExprClass:
5799   case Expr::ExpressionTraitExprClass:
5800   case Expr::CXXNoexceptExprClass:
5801     return NoDiag();
5802   case Expr::CallExprClass:
5803   case Expr::CXXOperatorCallExprClass: {
5804     // C99 6.6/3 allows function calls within unevaluated subexpressions of
5805     // constant expressions, but they can never be ICEs because an ICE cannot
5806     // contain an operand of (pointer to) function type.
5807     const CallExpr *CE = cast<CallExpr>(E);
5808     if (CE->isBuiltinCall())
5809       return CheckEvalInICE(E, Ctx);
5810     return ICEDiag(2, E->getLocStart());
5811   }
5812   case Expr::DeclRefExprClass:
5813     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
5814       return NoDiag();
5815     if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
5816       const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
5817 
5818       // Parameter variables are never constants.  Without this check,
5819       // getAnyInitializer() can find a default argument, which leads
5820       // to chaos.
5821       if (isa<ParmVarDecl>(D))
5822         return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5823 
5824       // C++ 7.1.5.1p2
5825       //   A variable of non-volatile const-qualified integral or enumeration
5826       //   type initialized by an ICE can be used in ICEs.
5827       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
5828         if (!Dcl->getType()->isIntegralOrEnumerationType())
5829           return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5830 
5831         const VarDecl *VD;
5832         // Look for a declaration of this variable that has an initializer, and
5833         // check whether it is an ICE.
5834         if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
5835           return NoDiag();
5836         else
5837           return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
5838       }
5839     }
5840     return ICEDiag(2, E->getLocStart());
5841   case Expr::UnaryOperatorClass: {
5842     const UnaryOperator *Exp = cast<UnaryOperator>(E);
5843     switch (Exp->getOpcode()) {
5844     case UO_PostInc:
5845     case UO_PostDec:
5846     case UO_PreInc:
5847     case UO_PreDec:
5848     case UO_AddrOf:
5849     case UO_Deref:
5850       // C99 6.6/3 allows increment and decrement within unevaluated
5851       // subexpressions of constant expressions, but they can never be ICEs
5852       // because an ICE cannot contain an lvalue operand.
5853       return ICEDiag(2, E->getLocStart());
5854     case UO_Extension:
5855     case UO_LNot:
5856     case UO_Plus:
5857     case UO_Minus:
5858     case UO_Not:
5859     case UO_Real:
5860     case UO_Imag:
5861       return CheckICE(Exp->getSubExpr(), Ctx);
5862     }
5863 
5864     // OffsetOf falls through here.
5865   }
5866   case Expr::OffsetOfExprClass: {
5867       // Note that per C99, offsetof must be an ICE. And AFAIK, using
5868       // EvaluateAsRValue matches the proposed gcc behavior for cases like
5869       // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
5870       // compliance: we should warn earlier for offsetof expressions with
5871       // array subscripts that aren't ICEs, and if the array subscripts
5872       // are ICEs, the value of the offsetof must be an integer constant.
5873       return CheckEvalInICE(E, Ctx);
5874   }
5875   case Expr::UnaryExprOrTypeTraitExprClass: {
5876     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
5877     if ((Exp->getKind() ==  UETT_SizeOf) &&
5878         Exp->getTypeOfArgument()->isVariableArrayType())
5879       return ICEDiag(2, E->getLocStart());
5880     return NoDiag();
5881   }
5882   case Expr::BinaryOperatorClass: {
5883     const BinaryOperator *Exp = cast<BinaryOperator>(E);
5884     switch (Exp->getOpcode()) {
5885     case BO_PtrMemD:
5886     case BO_PtrMemI:
5887     case BO_Assign:
5888     case BO_MulAssign:
5889     case BO_DivAssign:
5890     case BO_RemAssign:
5891     case BO_AddAssign:
5892     case BO_SubAssign:
5893     case BO_ShlAssign:
5894     case BO_ShrAssign:
5895     case BO_AndAssign:
5896     case BO_XorAssign:
5897     case BO_OrAssign:
5898       // C99 6.6/3 allows assignments within unevaluated subexpressions of
5899       // constant expressions, but they can never be ICEs because an ICE cannot
5900       // contain an lvalue operand.
5901       return ICEDiag(2, E->getLocStart());
5902 
5903     case BO_Mul:
5904     case BO_Div:
5905     case BO_Rem:
5906     case BO_Add:
5907     case BO_Sub:
5908     case BO_Shl:
5909     case BO_Shr:
5910     case BO_LT:
5911     case BO_GT:
5912     case BO_LE:
5913     case BO_GE:
5914     case BO_EQ:
5915     case BO_NE:
5916     case BO_And:
5917     case BO_Xor:
5918     case BO_Or:
5919     case BO_Comma: {
5920       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5921       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5922       if (Exp->getOpcode() == BO_Div ||
5923           Exp->getOpcode() == BO_Rem) {
5924         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
5925         // we don't evaluate one.
5926         if (LHSResult.Val == 0 && RHSResult.Val == 0) {
5927           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
5928           if (REval == 0)
5929             return ICEDiag(1, E->getLocStart());
5930           if (REval.isSigned() && REval.isAllOnesValue()) {
5931             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
5932             if (LEval.isMinSignedValue())
5933               return ICEDiag(1, E->getLocStart());
5934           }
5935         }
5936       }
5937       if (Exp->getOpcode() == BO_Comma) {
5938         if (Ctx.getLangOptions().C99) {
5939           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
5940           // if it isn't evaluated.
5941           if (LHSResult.Val == 0 && RHSResult.Val == 0)
5942             return ICEDiag(1, E->getLocStart());
5943         } else {
5944           // In both C89 and C++, commas in ICEs are illegal.
5945           return ICEDiag(2, E->getLocStart());
5946         }
5947       }
5948       if (LHSResult.Val >= RHSResult.Val)
5949         return LHSResult;
5950       return RHSResult;
5951     }
5952     case BO_LAnd:
5953     case BO_LOr: {
5954       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
5955       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
5956       if (LHSResult.Val == 0 && RHSResult.Val == 1) {
5957         // Rare case where the RHS has a comma "side-effect"; we need
5958         // to actually check the condition to see whether the side
5959         // with the comma is evaluated.
5960         if ((Exp->getOpcode() == BO_LAnd) !=
5961             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
5962           return RHSResult;
5963         return NoDiag();
5964       }
5965 
5966       if (LHSResult.Val >= RHSResult.Val)
5967         return LHSResult;
5968       return RHSResult;
5969     }
5970     }
5971   }
5972   case Expr::ImplicitCastExprClass:
5973   case Expr::CStyleCastExprClass:
5974   case Expr::CXXFunctionalCastExprClass:
5975   case Expr::CXXStaticCastExprClass:
5976   case Expr::CXXReinterpretCastExprClass:
5977   case Expr::CXXConstCastExprClass:
5978   case Expr::ObjCBridgedCastExprClass: {
5979     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
5980     if (isa<ExplicitCastExpr>(E)) {
5981       if (const FloatingLiteral *FL
5982             = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
5983         unsigned DestWidth = Ctx.getIntWidth(E->getType());
5984         bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
5985         APSInt IgnoredVal(DestWidth, !DestSigned);
5986         bool Ignored;
5987         // If the value does not fit in the destination type, the behavior is
5988         // undefined, so we are not required to treat it as a constant
5989         // expression.
5990         if (FL->getValue().convertToInteger(IgnoredVal,
5991                                             llvm::APFloat::rmTowardZero,
5992                                             &Ignored) & APFloat::opInvalidOp)
5993           return ICEDiag(2, E->getLocStart());
5994         return NoDiag();
5995       }
5996     }
5997     switch (cast<CastExpr>(E)->getCastKind()) {
5998     case CK_LValueToRValue:
5999     case CK_AtomicToNonAtomic:
6000     case CK_NonAtomicToAtomic:
6001     case CK_NoOp:
6002     case CK_IntegralToBoolean:
6003     case CK_IntegralCast:
6004       return CheckICE(SubExpr, Ctx);
6005     default:
6006       return ICEDiag(2, E->getLocStart());
6007     }
6008   }
6009   case Expr::BinaryConditionalOperatorClass: {
6010     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6011     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6012     if (CommonResult.Val == 2) return CommonResult;
6013     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6014     if (FalseResult.Val == 2) return FalseResult;
6015     if (CommonResult.Val == 1) return CommonResult;
6016     if (FalseResult.Val == 1 &&
6017         Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
6018     return FalseResult;
6019   }
6020   case Expr::ConditionalOperatorClass: {
6021     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6022     // If the condition (ignoring parens) is a __builtin_constant_p call,
6023     // then only the true side is actually considered in an integer constant
6024     // expression, and it is fully evaluated.  This is an important GNU
6025     // extension.  See GCC PR38377 for discussion.
6026     if (const CallExpr *CallCE
6027         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
6028       if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6029         return CheckEvalInICE(E, Ctx);
6030     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
6031     if (CondResult.Val == 2)
6032       return CondResult;
6033 
6034     ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6035     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6036 
6037     if (TrueResult.Val == 2)
6038       return TrueResult;
6039     if (FalseResult.Val == 2)
6040       return FalseResult;
6041     if (CondResult.Val == 1)
6042       return CondResult;
6043     if (TrueResult.Val == 0 && FalseResult.Val == 0)
6044       return NoDiag();
6045     // Rare case where the diagnostics depend on which side is evaluated
6046     // Note that if we get here, CondResult is 0, and at least one of
6047     // TrueResult and FalseResult is non-zero.
6048     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
6049       return FalseResult;
6050     }
6051     return TrueResult;
6052   }
6053   case Expr::CXXDefaultArgExprClass:
6054     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6055   case Expr::ChooseExprClass: {
6056     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6057   }
6058   }
6059 
6060   llvm_unreachable("Invalid StmtClass!");
6061 }
6062 
6063 /// Evaluate an expression as a C++11 integral constant expression.
6064 static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6065                                                     const Expr *E,
6066                                                     llvm::APSInt *Value,
6067                                                     SourceLocation *Loc) {
6068   if (!E->getType()->isIntegralOrEnumerationType()) {
6069     if (Loc) *Loc = E->getExprLoc();
6070     return false;
6071   }
6072 
6073   APValue Result;
6074   if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
6075     return false;
6076 
6077   assert(Result.isInt() && "pointer cast to int is not an ICE");
6078   if (Value) *Value = Result.getInt();
6079   return true;
6080 }
6081 
6082 bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
6083   if (Ctx.getLangOptions().CPlusPlus0x)
6084     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6085 
6086   ICEDiag d = CheckICE(this, Ctx);
6087   if (d.Val != 0) {
6088     if (Loc) *Loc = d.Loc;
6089     return false;
6090   }
6091   return true;
6092 }
6093 
6094 bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6095                                  SourceLocation *Loc, bool isEvaluated) const {
6096   if (Ctx.getLangOptions().CPlusPlus0x)
6097     return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6098 
6099   if (!isIntegerConstantExpr(Ctx, Loc))
6100     return false;
6101   if (!EvaluateAsInt(Value, Ctx))
6102     llvm_unreachable("ICE cannot be evaluated!");
6103   return true;
6104 }
6105 
6106 bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6107                                SourceLocation *Loc) const {
6108   // We support this checking in C++98 mode in order to diagnose compatibility
6109   // issues.
6110   assert(Ctx.getLangOptions().CPlusPlus);
6111 
6112   Expr::EvalStatus Status;
6113   llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6114   Status.Diag = &Diags;
6115   EvalInfo Info(Ctx, Status);
6116 
6117   APValue Scratch;
6118   bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6119 
6120   if (!Diags.empty()) {
6121     IsConstExpr = false;
6122     if (Loc) *Loc = Diags[0].first;
6123   } else if (!IsConstExpr) {
6124     // FIXME: This shouldn't happen.
6125     if (Loc) *Loc = getExprLoc();
6126   }
6127 
6128   return IsConstExpr;
6129 }
6130 
6131 bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6132                                    llvm::SmallVectorImpl<
6133                                      PartialDiagnosticAt> &Diags) {
6134   // FIXME: It would be useful to check constexpr function templates, but at the
6135   // moment the constant expression evaluator cannot cope with the non-rigorous
6136   // ASTs which we build for dependent expressions.
6137   if (FD->isDependentContext())
6138     return true;
6139 
6140   Expr::EvalStatus Status;
6141   Status.Diag = &Diags;
6142 
6143   EvalInfo Info(FD->getASTContext(), Status);
6144   Info.CheckingPotentialConstantExpression = true;
6145 
6146   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6147   const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6148 
6149   // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6150   // is a temporary being used as the 'this' pointer.
6151   LValue This;
6152   ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
6153   This.set(&VIE, Info.CurrentCall);
6154 
6155   APValue Scratch;
6156   ArrayRef<const Expr*> Args;
6157 
6158   SourceLocation Loc = FD->getLocation();
6159 
6160   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
6161     HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
6162   } else
6163     HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6164                        Args, FD->getBody(), Info, Scratch);
6165 
6166   return Diags.empty();
6167 }
6168