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