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 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/AST/StmtVisitor.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/ASTDiagnostic.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/Basic/Builtins.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "llvm/ADT/SmallString.h"
25 #include <cstring>
26 
27 using namespace clang;
28 using llvm::APSInt;
29 using llvm::APFloat;
30 
31 /// EvalInfo - This is a private struct used by the evaluator to capture
32 /// information about a subexpression as it is folded.  It retains information
33 /// about the AST context, but also maintains information about the folded
34 /// expression.
35 ///
36 /// If an expression could be evaluated, it is still possible it is not a C
37 /// "integer constant expression" or constant expression.  If not, this struct
38 /// captures information about how and why not.
39 ///
40 /// One bit of information passed *into* the request for constant folding
41 /// indicates whether the subexpression is "evaluated" or not according to C
42 /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
43 /// evaluate the expression regardless of what the RHS is, but C only allows
44 /// certain things in certain situations.
45 namespace {
46   struct LValue;
47   struct CallStackFrame;
48   struct EvalInfo;
49 
50   /// Get an LValue path entry, which is known to not be an array index, as a
51   /// field declaration.
52   const FieldDecl *getAsField(APValue::LValuePathEntry E) {
53     APValue::BaseOrMemberType Value;
54     Value.setFromOpaqueValue(E.BaseOrMember);
55     return dyn_cast<FieldDecl>(Value.getPointer());
56   }
57   /// Get an LValue path entry, which is known to not be an array index, as a
58   /// base class declaration.
59   const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
60     APValue::BaseOrMemberType Value;
61     Value.setFromOpaqueValue(E.BaseOrMember);
62     return dyn_cast<CXXRecordDecl>(Value.getPointer());
63   }
64   /// Determine whether this LValue path entry for a base class names a virtual
65   /// base class.
66   bool isVirtualBaseClass(APValue::LValuePathEntry E) {
67     APValue::BaseOrMemberType Value;
68     Value.setFromOpaqueValue(E.BaseOrMember);
69     return Value.getInt();
70   }
71 
72   /// Determine whether the described subobject is an array element.
73   static bool SubobjectIsArrayElement(QualType Base,
74                                       ArrayRef<APValue::LValuePathEntry> Path) {
75     bool IsArrayElement = false;
76     const Type *T = Base.getTypePtr();
77     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
78       IsArrayElement = T && T->isArrayType();
79       if (IsArrayElement)
80         T = T->getBaseElementTypeUnsafe();
81       else if (const FieldDecl *FD = getAsField(Path[I]))
82         T = FD->getType().getTypePtr();
83       else
84         // Path[I] describes a base class.
85         T = 0;
86     }
87     return IsArrayElement;
88   }
89 
90   /// A path from a glvalue to a subobject of that glvalue.
91   struct SubobjectDesignator {
92     /// True if the subobject was named in a manner not supported by C++11. Such
93     /// lvalues can still be folded, but they are not core constant expressions
94     /// and we cannot perform lvalue-to-rvalue conversions on them.
95     bool Invalid : 1;
96 
97     /// Whether this designates an array element.
98     bool ArrayElement : 1;
99 
100     /// Whether this designates 'one past the end' of the current subobject.
101     bool OnePastTheEnd : 1;
102 
103     typedef APValue::LValuePathEntry PathEntry;
104 
105     /// The entries on the path from the glvalue to the designated subobject.
106     SmallVector<PathEntry, 8> Entries;
107 
108     SubobjectDesignator() :
109       Invalid(false), ArrayElement(false), OnePastTheEnd(false) {}
110 
111     SubobjectDesignator(const APValue &V) :
112       Invalid(!V.isLValue() || !V.hasLValuePath()), ArrayElement(false),
113       OnePastTheEnd(false) {
114       if (!Invalid) {
115         ArrayRef<PathEntry> VEntries = V.getLValuePath();
116         Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
117         if (V.getLValueBase())
118           ArrayElement = SubobjectIsArrayElement(V.getLValueBase()->getType(),
119                                                  V.getLValuePath());
120         else
121           assert(V.getLValuePath().empty() &&"Null pointer with nonempty path");
122       }
123     }
124 
125     void setInvalid() {
126       Invalid = true;
127       Entries.clear();
128     }
129     /// Update this designator to refer to the given element within this array.
130     void addIndex(uint64_t N) {
131       if (Invalid) return;
132       if (OnePastTheEnd) {
133         setInvalid();
134         return;
135       }
136       PathEntry Entry;
137       Entry.ArrayIndex = N;
138       Entries.push_back(Entry);
139       ArrayElement = true;
140     }
141     /// Update this designator to refer to the given base or member of this
142     /// object.
143     void addDecl(const Decl *D, bool Virtual = false) {
144       if (Invalid) return;
145       if (OnePastTheEnd) {
146         setInvalid();
147         return;
148       }
149       PathEntry Entry;
150       APValue::BaseOrMemberType Value(D, Virtual);
151       Entry.BaseOrMember = Value.getOpaqueValue();
152       Entries.push_back(Entry);
153       ArrayElement = false;
154     }
155     /// Add N to the address of this subobject.
156     void adjustIndex(uint64_t N) {
157       if (Invalid) return;
158       if (ArrayElement) {
159         // FIXME: Make sure the index stays within bounds, or one past the end.
160         Entries.back().ArrayIndex += N;
161         return;
162       }
163       if (OnePastTheEnd && N == (uint64_t)-1)
164         OnePastTheEnd = false;
165       else if (!OnePastTheEnd && N == 1)
166         OnePastTheEnd = true;
167       else if (N != 0)
168         setInvalid();
169     }
170   };
171 
172   /// A core constant value. This can be the value of any constant expression,
173   /// or a pointer or reference to a non-static object or function parameter.
174   class CCValue : public APValue {
175     typedef llvm::APSInt APSInt;
176     typedef llvm::APFloat APFloat;
177     /// If the value is a reference or pointer into a parameter or temporary,
178     /// this is the corresponding call stack frame.
179     CallStackFrame *CallFrame;
180     /// If the value is a reference or pointer, this is a description of how the
181     /// subobject was specified.
182     SubobjectDesignator Designator;
183   public:
184     struct GlobalValue {};
185 
186     CCValue() {}
187     explicit CCValue(const APSInt &I) : APValue(I) {}
188     explicit CCValue(const APFloat &F) : APValue(F) {}
189     CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
190     CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
191     CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
192     CCValue(const CCValue &V) : APValue(V), CallFrame(V.CallFrame) {}
193     CCValue(const Expr *B, const CharUnits &O, CallStackFrame *F,
194             const SubobjectDesignator &D) :
195       APValue(B, O, APValue::NoLValuePath()), CallFrame(F), Designator(D) {}
196     CCValue(const APValue &V, GlobalValue) :
197       APValue(V), CallFrame(0), Designator(V) {}
198 
199     CallStackFrame *getLValueFrame() const {
200       assert(getKind() == LValue);
201       return CallFrame;
202     }
203     SubobjectDesignator &getLValueDesignator() {
204       assert(getKind() == LValue);
205       return Designator;
206     }
207     const SubobjectDesignator &getLValueDesignator() const {
208       return const_cast<CCValue*>(this)->getLValueDesignator();
209     }
210   };
211 
212   /// A stack frame in the constexpr call stack.
213   struct CallStackFrame {
214     EvalInfo &Info;
215 
216     /// Parent - The caller of this stack frame.
217     CallStackFrame *Caller;
218 
219     /// This - The binding for the this pointer in this call, if any.
220     const LValue *This;
221 
222     /// ParmBindings - Parameter bindings for this function call, indexed by
223     /// parameters' function scope indices.
224     const CCValue *Arguments;
225 
226     typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
227     typedef MapTy::const_iterator temp_iterator;
228     /// Temporaries - Temporary lvalues materialized within this stack frame.
229     MapTy Temporaries;
230 
231     CallStackFrame(EvalInfo &Info, const LValue *This,
232                    const CCValue *Arguments);
233     ~CallStackFrame();
234   };
235 
236   struct EvalInfo {
237     const ASTContext &Ctx;
238 
239     /// EvalStatus - Contains information about the evaluation.
240     Expr::EvalStatus &EvalStatus;
241 
242     /// CurrentCall - The top of the constexpr call stack.
243     CallStackFrame *CurrentCall;
244 
245     /// NumCalls - The number of calls we've evaluated so far.
246     unsigned NumCalls;
247 
248     /// CallStackDepth - The number of calls in the call stack right now.
249     unsigned CallStackDepth;
250 
251     typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
252     /// OpaqueValues - Values used as the common expression in a
253     /// BinaryConditionalOperator.
254     MapTy OpaqueValues;
255 
256     /// BottomFrame - The frame in which evaluation started. This must be
257     /// initialized last.
258     CallStackFrame BottomFrame;
259 
260     /// EvaluatingDecl - This is the declaration whose initializer is being
261     /// evaluated, if any.
262     const VarDecl *EvaluatingDecl;
263 
264     /// EvaluatingDeclValue - This is the value being constructed for the
265     /// declaration whose initializer is being evaluated, if any.
266     APValue *EvaluatingDeclValue;
267 
268 
269     EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
270       : Ctx(C), EvalStatus(S), CurrentCall(0), NumCalls(0), CallStackDepth(0),
271         BottomFrame(*this, 0, 0), EvaluatingDecl(0), EvaluatingDeclValue(0) {}
272 
273     const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
274       MapTy::const_iterator i = OpaqueValues.find(e);
275       if (i == OpaqueValues.end()) return 0;
276       return &i->second;
277     }
278 
279     void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
280       EvaluatingDecl = VD;
281       EvaluatingDeclValue = &Value;
282     }
283 
284     const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
285   };
286 
287   CallStackFrame::CallStackFrame(EvalInfo &Info, const LValue *This,
288                                  const CCValue *Arguments)
289       : Info(Info), Caller(Info.CurrentCall), This(This), Arguments(Arguments) {
290     Info.CurrentCall = this;
291     ++Info.CallStackDepth;
292   }
293 
294   CallStackFrame::~CallStackFrame() {
295     assert(Info.CurrentCall == this && "calls retired out of order");
296     --Info.CallStackDepth;
297     Info.CurrentCall = Caller;
298   }
299 
300   struct ComplexValue {
301   private:
302     bool IsInt;
303 
304   public:
305     APSInt IntReal, IntImag;
306     APFloat FloatReal, FloatImag;
307 
308     ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
309 
310     void makeComplexFloat() { IsInt = false; }
311     bool isComplexFloat() const { return !IsInt; }
312     APFloat &getComplexFloatReal() { return FloatReal; }
313     APFloat &getComplexFloatImag() { return FloatImag; }
314 
315     void makeComplexInt() { IsInt = true; }
316     bool isComplexInt() const { return IsInt; }
317     APSInt &getComplexIntReal() { return IntReal; }
318     APSInt &getComplexIntImag() { return IntImag; }
319 
320     void moveInto(CCValue &v) const {
321       if (isComplexFloat())
322         v = CCValue(FloatReal, FloatImag);
323       else
324         v = CCValue(IntReal, IntImag);
325     }
326     void setFrom(const CCValue &v) {
327       assert(v.isComplexFloat() || v.isComplexInt());
328       if (v.isComplexFloat()) {
329         makeComplexFloat();
330         FloatReal = v.getComplexFloatReal();
331         FloatImag = v.getComplexFloatImag();
332       } else {
333         makeComplexInt();
334         IntReal = v.getComplexIntReal();
335         IntImag = v.getComplexIntImag();
336       }
337     }
338   };
339 
340   struct LValue {
341     const Expr *Base;
342     CharUnits Offset;
343     CallStackFrame *Frame;
344     SubobjectDesignator Designator;
345 
346     const Expr *getLValueBase() const { return Base; }
347     CharUnits &getLValueOffset() { return Offset; }
348     const CharUnits &getLValueOffset() const { return Offset; }
349     CallStackFrame *getLValueFrame() const { return Frame; }
350     SubobjectDesignator &getLValueDesignator() { return Designator; }
351     const SubobjectDesignator &getLValueDesignator() const { return Designator;}
352 
353     void moveInto(CCValue &V) const {
354       V = CCValue(Base, Offset, Frame, Designator);
355     }
356     void setFrom(const CCValue &V) {
357       assert(V.isLValue());
358       Base = V.getLValueBase();
359       Offset = V.getLValueOffset();
360       Frame = V.getLValueFrame();
361       Designator = V.getLValueDesignator();
362     }
363 
364     void setExpr(const Expr *E, CallStackFrame *F = 0) {
365       Base = E;
366       Offset = CharUnits::Zero();
367       Frame = F;
368       Designator = SubobjectDesignator();
369     }
370   };
371 }
372 
373 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
374 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
375                                        const LValue &This, const Expr *E);
376 static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
377 static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
378 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
379 static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
380                                     EvalInfo &Info);
381 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
382 static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
383 
384 //===----------------------------------------------------------------------===//
385 // Misc utilities
386 //===----------------------------------------------------------------------===//
387 
388 /// Should this call expression be treated as a string literal?
389 static bool IsStringLiteralCall(const CallExpr *E) {
390   unsigned Builtin = E->isBuiltinCall();
391   return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
392           Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
393 }
394 
395 static bool IsGlobalLValue(const Expr* E) {
396   // C++11 [expr.const]p3 An address constant expression is a prvalue core
397   // constant expression of pointer type that evaluates to...
398 
399   // ... a null pointer value, or a prvalue core constant expression of type
400   // std::nullptr_t.
401   if (!E) return true;
402 
403   switch (E->getStmtClass()) {
404   default:
405     return false;
406   case Expr::DeclRefExprClass: {
407     const DeclRefExpr *DRE = cast<DeclRefExpr>(E);
408     // ... the address of an object with static storage duration,
409     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
410       return VD->hasGlobalStorage();
411     // ... to the address of a function,
412     if (isa<FunctionDecl>(DRE->getDecl()))
413       return true;
414     return false;
415   }
416   case Expr::CompoundLiteralExprClass:
417     return cast<CompoundLiteralExpr>(E)->isFileScope();
418   // A string literal has static storage duration.
419   case Expr::StringLiteralClass:
420   case Expr::PredefinedExprClass:
421   case Expr::ObjCStringLiteralClass:
422   case Expr::ObjCEncodeExprClass:
423     return true;
424   case Expr::CallExprClass:
425     return IsStringLiteralCall(cast<CallExpr>(E));
426   // For GCC compatibility, &&label has static storage duration.
427   case Expr::AddrLabelExprClass:
428     return true;
429   // A Block literal expression may be used as the initialization value for
430   // Block variables at global or local static scope.
431   case Expr::BlockExprClass:
432     return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
433   }
434 }
435 
436 /// Check that this reference or pointer core constant expression is a valid
437 /// value for a constant expression. Type T should be either LValue or CCValue.
438 template<typename T>
439 static bool CheckLValueConstantExpression(const T &LVal, APValue &Value) {
440   if (!IsGlobalLValue(LVal.getLValueBase()))
441     return false;
442 
443   const SubobjectDesignator &Designator = LVal.getLValueDesignator();
444   // A constant expression must refer to an object or be a null pointer.
445   if (Designator.Invalid || Designator.OnePastTheEnd ||
446       (!LVal.getLValueBase() && !Designator.Entries.empty())) {
447     // FIXME: Check for out-of-bounds array indices.
448     // FIXME: This is not a constant expression.
449     Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
450                     APValue::NoLValuePath());
451     return true;
452   }
453 
454   // FIXME: Null references are not constant expressions.
455 
456   Value = APValue(LVal.getLValueBase(), LVal.getLValueOffset(),
457                   Designator.Entries);
458   return true;
459 }
460 
461 /// Check that this core constant expression value is a valid value for a
462 /// constant expression, and if it is, produce the corresponding constant value.
463 static bool CheckConstantExpression(const CCValue &CCValue, APValue &Value) {
464   if (!CCValue.isLValue()) {
465     Value = CCValue;
466     return true;
467   }
468   return CheckLValueConstantExpression(CCValue, Value);
469 }
470 
471 const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
472   if (!LVal.Base)
473     return 0;
474 
475   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVal.Base))
476     return DRE->getDecl();
477 
478   // FIXME: Static data members accessed via a MemberExpr are represented as
479   // that MemberExpr. We should use the Decl directly instead.
480   if (const MemberExpr *ME = dyn_cast<MemberExpr>(LVal.Base)) {
481     assert(!isa<FieldDecl>(ME->getMemberDecl()) && "shouldn't see fields here");
482     return ME->getMemberDecl();
483   }
484 
485   return 0;
486 }
487 
488 static bool IsLiteralLValue(const LValue &Value) {
489   return Value.Base &&
490          !isa<DeclRefExpr>(Value.Base) &&
491          !isa<MemberExpr>(Value.Base) &&
492          !isa<MaterializeTemporaryExpr>(Value.Base);
493 }
494 
495 static bool IsWeakDecl(const ValueDecl *Decl) {
496   return Decl->hasAttr<WeakAttr>() ||
497          Decl->hasAttr<WeakRefAttr>() ||
498          Decl->isWeakImported();
499 }
500 
501 static bool IsWeakLValue(const LValue &Value) {
502   const ValueDecl *Decl = GetLValueBaseDecl(Value);
503   return Decl && IsWeakDecl(Decl);
504 }
505 
506 static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
507   const Expr* Base = Value.Base;
508 
509   // A null base expression indicates a null pointer.  These are always
510   // evaluatable, and they are false unless the offset is zero.
511   if (!Base) {
512     Result = !Value.Offset.isZero();
513     return true;
514   }
515 
516   // Require the base expression to be a global l-value.
517   // FIXME: C++11 requires such conversions. Remove this check.
518   if (!IsGlobalLValue(Base)) return false;
519 
520   // We have a non-null base expression.  These are generally known to
521   // be true, but if it'a decl-ref to a weak symbol it can be null at
522   // runtime.
523   Result = true;
524   return !IsWeakLValue(Value);
525 }
526 
527 static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
528   switch (Val.getKind()) {
529   case APValue::Uninitialized:
530     return false;
531   case APValue::Int:
532     Result = Val.getInt().getBoolValue();
533     return true;
534   case APValue::Float:
535     Result = !Val.getFloat().isZero();
536     return true;
537   case APValue::ComplexInt:
538     Result = Val.getComplexIntReal().getBoolValue() ||
539              Val.getComplexIntImag().getBoolValue();
540     return true;
541   case APValue::ComplexFloat:
542     Result = !Val.getComplexFloatReal().isZero() ||
543              !Val.getComplexFloatImag().isZero();
544     return true;
545   case APValue::LValue: {
546     LValue PointerResult;
547     PointerResult.setFrom(Val);
548     return EvalPointerValueAsBool(PointerResult, Result);
549   }
550   case APValue::Vector:
551   case APValue::Array:
552   case APValue::Struct:
553   case APValue::Union:
554     return false;
555   }
556 
557   llvm_unreachable("unknown APValue kind");
558 }
559 
560 static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
561                                        EvalInfo &Info) {
562   assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
563   CCValue Val;
564   if (!Evaluate(Val, Info, E))
565     return false;
566   return HandleConversionToBool(Val, Result);
567 }
568 
569 static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
570                                    APFloat &Value, const ASTContext &Ctx) {
571   unsigned DestWidth = Ctx.getIntWidth(DestType);
572   // Determine whether we are converting to unsigned or signed.
573   bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
574 
575   // FIXME: Warning for overflow.
576   APSInt Result(DestWidth, !DestSigned);
577   bool ignored;
578   (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
579   return Result;
580 }
581 
582 static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
583                                       APFloat &Value, const ASTContext &Ctx) {
584   bool ignored;
585   APFloat Result = Value;
586   Result.convert(Ctx.getFloatTypeSemantics(DestType),
587                  APFloat::rmNearestTiesToEven, &ignored);
588   return Result;
589 }
590 
591 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
592                                  APSInt &Value, const ASTContext &Ctx) {
593   unsigned DestWidth = Ctx.getIntWidth(DestType);
594   APSInt Result = Value;
595   // Figure out if this is a truncate, extend or noop cast.
596   // If the input is signed, do a sign extend, noop, or truncate.
597   Result = Result.extOrTrunc(DestWidth);
598   Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
599   return Result;
600 }
601 
602 static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
603                                     APSInt &Value, const ASTContext &Ctx) {
604 
605   APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
606   Result.convertFromAPInt(Value, Value.isSigned(),
607                           APFloat::rmNearestTiesToEven);
608   return Result;
609 }
610 
611 /// If the given LValue refers to a base subobject of some object, find the most
612 /// derived object and the corresponding complete record type. This is necessary
613 /// in order to find the offset of a virtual base class.
614 static bool ExtractMostDerivedObject(EvalInfo &Info, LValue &Result,
615                                      const CXXRecordDecl *&MostDerivedType) {
616   SubobjectDesignator &D = Result.Designator;
617   if (D.Invalid || !Result.Base)
618     return false;
619 
620   const Type *T = Result.Base->getType().getTypePtr();
621 
622   // Find path prefix which leads to the most-derived subobject.
623   unsigned MostDerivedPathLength = 0;
624   MostDerivedType = T->getAsCXXRecordDecl();
625   bool MostDerivedIsArrayElement = false;
626 
627   for (unsigned I = 0, N = D.Entries.size(); I != N; ++I) {
628     bool IsArray = T && T->isArrayType();
629     if (IsArray)
630       T = T->getBaseElementTypeUnsafe();
631     else if (const FieldDecl *FD = getAsField(D.Entries[I]))
632       T = FD->getType().getTypePtr();
633     else
634       T = 0;
635 
636     if (T) {
637       MostDerivedType = T->getAsCXXRecordDecl();
638       MostDerivedPathLength = I + 1;
639       MostDerivedIsArrayElement = IsArray;
640     }
641   }
642 
643   if (!MostDerivedType)
644     return false;
645 
646   // (B*)&d + 1 has no most-derived object.
647   if (D.OnePastTheEnd && MostDerivedPathLength != D.Entries.size())
648     return false;
649 
650   // Remove the trailing base class path entries and their offsets.
651   const RecordDecl *RD = MostDerivedType;
652   for (unsigned I = MostDerivedPathLength, N = D.Entries.size(); I != N; ++I) {
653     const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
654     const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
655     if (isVirtualBaseClass(D.Entries[I])) {
656       assert(I == MostDerivedPathLength &&
657              "virtual base class must be immediately after most-derived class");
658       Result.Offset -= Layout.getVBaseClassOffset(Base);
659     } else
660       Result.Offset -= Layout.getBaseClassOffset(Base);
661     RD = Base;
662   }
663   D.Entries.resize(MostDerivedPathLength);
664   D.ArrayElement = MostDerivedIsArrayElement;
665   return true;
666 }
667 
668 static void HandleLValueDirectBase(EvalInfo &Info, LValue &Obj,
669                                    const CXXRecordDecl *Derived,
670                                    const CXXRecordDecl *Base,
671                                    const ASTRecordLayout *RL = 0) {
672   if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
673   Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
674   Obj.Designator.addDecl(Base, /*Virtual*/ false);
675 }
676 
677 static bool HandleLValueBase(EvalInfo &Info, LValue &Obj,
678                              const CXXRecordDecl *DerivedDecl,
679                              const CXXBaseSpecifier *Base) {
680   const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
681 
682   if (!Base->isVirtual()) {
683     HandleLValueDirectBase(Info, Obj, DerivedDecl, BaseDecl);
684     return true;
685   }
686 
687   // Extract most-derived object and corresponding type.
688   if (!ExtractMostDerivedObject(Info, Obj, DerivedDecl))
689     return false;
690 
691   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
692   Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
693   Obj.Designator.addDecl(BaseDecl, /*Virtual*/ true);
694   return true;
695 }
696 
697 /// Update LVal to refer to the given field, which must be a member of the type
698 /// currently described by LVal.
699 static void HandleLValueMember(EvalInfo &Info, LValue &LVal,
700                                const FieldDecl *FD,
701                                const ASTRecordLayout *RL = 0) {
702   if (!RL)
703     RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
704 
705   unsigned I = FD->getFieldIndex();
706   LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
707   LVal.Designator.addDecl(FD);
708 }
709 
710 /// Get the size of the given type in char units.
711 static bool HandleSizeof(EvalInfo &Info, QualType Type, CharUnits &Size) {
712   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
713   // extension.
714   if (Type->isVoidType() || Type->isFunctionType()) {
715     Size = CharUnits::One();
716     return true;
717   }
718 
719   if (!Type->isConstantSizeType()) {
720     // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
721     return false;
722   }
723 
724   Size = Info.Ctx.getTypeSizeInChars(Type);
725   return true;
726 }
727 
728 /// Update a pointer value to model pointer arithmetic.
729 /// \param Info - Information about the ongoing evaluation.
730 /// \param LVal - The pointer value to be updated.
731 /// \param EltTy - The pointee type represented by LVal.
732 /// \param Adjustment - The adjustment, in objects of type EltTy, to add.
733 static bool HandleLValueArrayAdjustment(EvalInfo &Info, LValue &LVal,
734                                         QualType EltTy, int64_t Adjustment) {
735   CharUnits SizeOfPointee;
736   if (!HandleSizeof(Info, EltTy, SizeOfPointee))
737     return false;
738 
739   // Compute the new offset in the appropriate width.
740   LVal.Offset += Adjustment * SizeOfPointee;
741   LVal.Designator.adjustIndex(Adjustment);
742   return true;
743 }
744 
745 /// Try to evaluate the initializer for a variable declaration.
746 static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,const VarDecl *VD,
747                                 CallStackFrame *Frame, CCValue &Result) {
748   // If this is a parameter to an active constexpr function call, perform
749   // argument substitution.
750   if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
751     if (!Frame || !Frame->Arguments)
752       return false;
753     Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
754     return true;
755   }
756 
757   // If we're currently evaluating the initializer of this declaration, use that
758   // in-flight value.
759   if (Info.EvaluatingDecl == VD) {
760     Result = CCValue(*Info.EvaluatingDeclValue, CCValue::GlobalValue());
761     return !Result.isUninit();
762   }
763 
764   // Never evaluate the initializer of a weak variable. We can't be sure that
765   // this is the definition which will be used.
766   if (IsWeakDecl(VD))
767     return false;
768 
769   const Expr *Init = VD->getAnyInitializer();
770   if (!Init || Init->isValueDependent())
771     return false;
772 
773   if (APValue *V = VD->getEvaluatedValue()) {
774     Result = CCValue(*V, CCValue::GlobalValue());
775     return !Result.isUninit();
776   }
777 
778   if (VD->isEvaluatingValue())
779     return false;
780 
781   VD->setEvaluatingValue();
782 
783   Expr::EvalStatus EStatus;
784   EvalInfo InitInfo(Info.Ctx, EStatus);
785   APValue EvalResult;
786   InitInfo.setEvaluatingDecl(VD, EvalResult);
787   LValue LVal;
788   LVal.setExpr(E);
789   // FIXME: The caller will need to know whether the value was a constant
790   // expression. If not, we should propagate up a diagnostic.
791   if (!EvaluateConstantExpression(EvalResult, InitInfo, LVal, Init)) {
792     // FIXME: If the evaluation failure was not permanent (for instance, if we
793     // hit a variable with no declaration yet, or a constexpr function with no
794     // definition yet), the standard is unclear as to how we should behave.
795     //
796     // Either the initializer should be evaluated when the variable is defined,
797     // or a failed evaluation of the initializer should be reattempted each time
798     // it is used.
799     VD->setEvaluatedValue(APValue());
800     return false;
801   }
802 
803   VD->setEvaluatedValue(EvalResult);
804   Result = CCValue(EvalResult, CCValue::GlobalValue());
805   return true;
806 }
807 
808 static bool IsConstNonVolatile(QualType T) {
809   Qualifiers Quals = T.getQualifiers();
810   return Quals.hasConst() && !Quals.hasVolatile();
811 }
812 
813 /// Get the base index of the given base class within an APValue representing
814 /// the given derived class.
815 static unsigned getBaseIndex(const CXXRecordDecl *Derived,
816                              const CXXRecordDecl *Base) {
817   Base = Base->getCanonicalDecl();
818   unsigned Index = 0;
819   for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
820          E = Derived->bases_end(); I != E; ++I, ++Index) {
821     if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
822       return Index;
823   }
824 
825   llvm_unreachable("base class missing from derived class's bases list");
826 }
827 
828 /// Extract the designated sub-object of an rvalue.
829 static bool ExtractSubobject(EvalInfo &Info, CCValue &Obj, QualType ObjType,
830                              const SubobjectDesignator &Sub, QualType SubType) {
831   if (Sub.Invalid || Sub.OnePastTheEnd)
832     return false;
833   if (Sub.Entries.empty())
834     return true;
835 
836   assert(!Obj.isLValue() && "extracting subobject of lvalue");
837   const APValue *O = &Obj;
838   // Walk the designator's path to find the subobject.
839   for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
840     if (ObjType->isArrayType()) {
841       // Next subobject is an array element.
842       const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
843       if (!CAT)
844         return false;
845       uint64_t Index = Sub.Entries[I].ArrayIndex;
846       if (CAT->getSize().ule(Index))
847         return false;
848       if (O->getArrayInitializedElts() > Index)
849         O = &O->getArrayInitializedElt(Index);
850       else
851         O = &O->getArrayFiller();
852       ObjType = CAT->getElementType();
853     } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
854       // Next subobject is a class, struct or union field.
855       RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
856       if (RD->isUnion()) {
857         const FieldDecl *UnionField = O->getUnionField();
858         if (!UnionField ||
859             UnionField->getCanonicalDecl() != Field->getCanonicalDecl())
860           return false;
861         O = &O->getUnionValue();
862       } else
863         O = &O->getStructField(Field->getFieldIndex());
864       ObjType = Field->getType();
865     } else {
866       // Next subobject is a base class.
867       const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
868       const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
869       O = &O->getStructBase(getBaseIndex(Derived, Base));
870       ObjType = Info.Ctx.getRecordType(Base);
871     }
872 
873     if (O->isUninit())
874       return false;
875   }
876 
877   Obj = CCValue(*O, CCValue::GlobalValue());
878   return true;
879 }
880 
881 /// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
882 /// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
883 /// for looking up the glvalue referred to by an entity of reference type.
884 ///
885 /// \param Info - Information about the ongoing evaluation.
886 /// \param Type - The type we expect this conversion to produce.
887 /// \param LVal - The glvalue on which we are attempting to perform this action.
888 /// \param RVal - The produced value will be placed here.
889 static bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
890                                            const LValue &LVal, CCValue &RVal) {
891   const Expr *Base = LVal.Base;
892   CallStackFrame *Frame = LVal.Frame;
893 
894   // FIXME: Indirection through a null pointer deserves a diagnostic.
895   if (!Base)
896     return false;
897 
898   if (const ValueDecl *D = GetLValueBaseDecl(LVal)) {
899     // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
900     // In C++11, constexpr, non-volatile variables initialized with constant
901     // expressions are constant expressions too. Inside constexpr functions,
902     // parameters are constant expressions even if they're non-const.
903     // In C, such things can also be folded, although they are not ICEs.
904     //
905     // FIXME: volatile-qualified ParmVarDecls need special handling. A literal
906     // interpretation of C++11 suggests that volatile parameters are OK if
907     // they're never read (there's no prohibition against constructing volatile
908     // objects in constant expressions), but lvalue-to-rvalue conversions on
909     // them are not permitted.
910     const VarDecl *VD = dyn_cast<VarDecl>(D);
911     QualType VT = VD->getType();
912     if (!VD || VD->isInvalidDecl())
913       return false;
914     if (!isa<ParmVarDecl>(VD)) {
915       if (!IsConstNonVolatile(VT))
916         return false;
917       // FIXME: Allow folding of values of any literal type in all languages.
918       if (!VT->isIntegralOrEnumerationType() && !VT->isRealFloatingType() &&
919           !VD->isConstexpr())
920         return false;
921     }
922     if (!EvaluateVarDeclInit(Info, LVal.Base, VD, Frame, RVal))
923       return false;
924 
925     if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
926       return ExtractSubobject(Info, RVal, VT, LVal.Designator, Type);
927 
928     // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
929     // conversion. This happens when the declaration and the lvalue should be
930     // considered synonymous, for instance when initializing an array of char
931     // from a string literal. Continue as if the initializer lvalue was the
932     // value we were originally given.
933     assert(RVal.getLValueOffset().isZero() &&
934            "offset for lvalue init of non-reference");
935     Base = RVal.getLValueBase();
936     Frame = RVal.getLValueFrame();
937   }
938 
939   // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
940   if (const StringLiteral *S = dyn_cast<StringLiteral>(Base)) {
941     const SubobjectDesignator &Designator = LVal.Designator;
942     if (Designator.Invalid || Designator.Entries.size() != 1)
943       return false;
944 
945     assert(Type->isIntegerType() && "string element not integer type");
946     uint64_t Index = Designator.Entries[0].ArrayIndex;
947     if (Index > S->getLength())
948       return false;
949     APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
950                  Type->isUnsignedIntegerType());
951     if (Index < S->getLength())
952       Value = S->getCodeUnit(Index);
953     RVal = CCValue(Value);
954     return true;
955   }
956 
957   if (Frame) {
958     // If this is a temporary expression with a nontrivial initializer, grab the
959     // value from the relevant stack frame.
960     RVal = Frame->Temporaries[Base];
961   } else if (const CompoundLiteralExpr *CLE
962              = dyn_cast<CompoundLiteralExpr>(Base)) {
963     // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
964     // initializer until now for such expressions. Such an expression can't be
965     // an ICE in C, so this only matters for fold.
966     assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
967     if (!Evaluate(RVal, Info, CLE->getInitializer()))
968       return false;
969   } else
970     return false;
971 
972   return ExtractSubobject(Info, RVal, Base->getType(), LVal.Designator, Type);
973 }
974 
975 /// Build an lvalue for the object argument of a member function call.
976 static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
977                                    LValue &This) {
978   if (Object->getType()->isPointerType())
979     return EvaluatePointer(Object, This, Info);
980 
981   if (Object->isGLValue())
982     return EvaluateLValue(Object, This, Info);
983 
984   // Implicitly promote a prvalue *this object to a glvalue.
985   This.setExpr(Object, Info.CurrentCall);
986   return EvaluateConstantExpression(Info.CurrentCall->Temporaries[Object], Info,
987                                     This, Object);
988 }
989 
990 namespace {
991 enum EvalStmtResult {
992   /// Evaluation failed.
993   ESR_Failed,
994   /// Hit a 'return' statement.
995   ESR_Returned,
996   /// Evaluation succeeded.
997   ESR_Succeeded
998 };
999 }
1000 
1001 // Evaluate a statement.
1002 static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
1003                                    const Stmt *S) {
1004   switch (S->getStmtClass()) {
1005   default:
1006     return ESR_Failed;
1007 
1008   case Stmt::NullStmtClass:
1009   case Stmt::DeclStmtClass:
1010     return ESR_Succeeded;
1011 
1012   case Stmt::ReturnStmtClass:
1013     if (Evaluate(Result, Info, cast<ReturnStmt>(S)->getRetValue()))
1014       return ESR_Returned;
1015     return ESR_Failed;
1016 
1017   case Stmt::CompoundStmtClass: {
1018     const CompoundStmt *CS = cast<CompoundStmt>(S);
1019     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1020            BE = CS->body_end(); BI != BE; ++BI) {
1021       EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
1022       if (ESR != ESR_Succeeded)
1023         return ESR;
1024     }
1025     return ESR_Succeeded;
1026   }
1027   }
1028 }
1029 
1030 namespace {
1031 typedef SmallVector<CCValue, 8> ArgVector;
1032 }
1033 
1034 /// EvaluateArgs - Evaluate the arguments to a function call.
1035 static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
1036                          EvalInfo &Info) {
1037   for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
1038        I != E; ++I)
1039     if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
1040       return false;
1041   return true;
1042 }
1043 
1044 /// Evaluate a function call.
1045 static bool HandleFunctionCall(const LValue *This, ArrayRef<const Expr*> Args,
1046                                const Stmt *Body, EvalInfo &Info,
1047                                CCValue &Result) {
1048   // FIXME: Implement a proper call limit, along with a command-line flag.
1049   if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1050     return false;
1051 
1052   ArgVector ArgValues(Args.size());
1053   if (!EvaluateArgs(Args, ArgValues, Info))
1054     return false;
1055 
1056   CallStackFrame Frame(Info, This, ArgValues.data());
1057   return EvaluateStmt(Result, Info, Body) == ESR_Returned;
1058 }
1059 
1060 /// Evaluate a constructor call.
1061 static bool HandleConstructorCall(const LValue &This,
1062                                   ArrayRef<const Expr*> Args,
1063                                   const CXXConstructorDecl *Definition,
1064                                   EvalInfo &Info,
1065                                   APValue &Result) {
1066   if (Info.NumCalls >= 1000000 || Info.CallStackDepth >= 512)
1067     return false;
1068 
1069   ArgVector ArgValues(Args.size());
1070   if (!EvaluateArgs(Args, ArgValues, Info))
1071     return false;
1072 
1073   CallStackFrame Frame(Info, &This, ArgValues.data());
1074 
1075   // If it's a delegating constructor, just delegate.
1076   if (Definition->isDelegatingConstructor()) {
1077     CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
1078     return EvaluateConstantExpression(Result, Info, This, (*I)->getInit());
1079   }
1080 
1081   // Reserve space for the struct members.
1082   const CXXRecordDecl *RD = Definition->getParent();
1083   if (!RD->isUnion())
1084     Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
1085                      std::distance(RD->field_begin(), RD->field_end()));
1086 
1087   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1088 
1089   unsigned BasesSeen = 0;
1090 #ifndef NDEBUG
1091   CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
1092 #endif
1093   for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
1094        E = Definition->init_end(); I != E; ++I) {
1095     if ((*I)->isBaseInitializer()) {
1096       QualType BaseType((*I)->getBaseClass(), 0);
1097 #ifndef NDEBUG
1098       // Non-virtual base classes are initialized in the order in the class
1099       // definition. We cannot have a virtual base class for a literal type.
1100       assert(!BaseIt->isVirtual() && "virtual base for literal type");
1101       assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
1102              "base class initializers not in expected order");
1103       ++BaseIt;
1104 #endif
1105       LValue Subobject = This;
1106       HandleLValueDirectBase(Info, Subobject, RD,
1107                              BaseType->getAsCXXRecordDecl(), &Layout);
1108       if (!EvaluateConstantExpression(Result.getStructBase(BasesSeen++), Info,
1109                                       Subobject, (*I)->getInit()))
1110         return false;
1111     } else if (FieldDecl *FD = (*I)->getMember()) {
1112       LValue Subobject = This;
1113       HandleLValueMember(Info, Subobject, FD, &Layout);
1114       if (RD->isUnion()) {
1115         Result = APValue(FD);
1116         if (!EvaluateConstantExpression(Result.getUnionValue(), Info,
1117                                         Subobject, (*I)->getInit()))
1118           return false;
1119       } else if (!EvaluateConstantExpression(
1120                    Result.getStructField(FD->getFieldIndex()),
1121                    Info, Subobject, (*I)->getInit()))
1122         return false;
1123     } else {
1124       // FIXME: handle indirect field initializers
1125       return false;
1126     }
1127   }
1128 
1129   return true;
1130 }
1131 
1132 namespace {
1133 class HasSideEffect
1134   : public ConstStmtVisitor<HasSideEffect, bool> {
1135   const ASTContext &Ctx;
1136 public:
1137 
1138   HasSideEffect(const ASTContext &C) : Ctx(C) {}
1139 
1140   // Unhandled nodes conservatively default to having side effects.
1141   bool VisitStmt(const Stmt *S) {
1142     return true;
1143   }
1144 
1145   bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
1146   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
1147     return Visit(E->getResultExpr());
1148   }
1149   bool VisitDeclRefExpr(const DeclRefExpr *E) {
1150     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
1151       return true;
1152     return false;
1153   }
1154   bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
1155     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
1156       return true;
1157     return false;
1158   }
1159   bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
1160     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
1161       return true;
1162     return false;
1163   }
1164 
1165   // We don't want to evaluate BlockExprs multiple times, as they generate
1166   // a ton of code.
1167   bool VisitBlockExpr(const BlockExpr *E) { return true; }
1168   bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
1169   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
1170     { return Visit(E->getInitializer()); }
1171   bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
1172   bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
1173   bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
1174   bool VisitStringLiteral(const StringLiteral *E) { return false; }
1175   bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
1176   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
1177     { return false; }
1178   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
1179     { return Visit(E->getLHS()) || Visit(E->getRHS()); }
1180   bool VisitChooseExpr(const ChooseExpr *E)
1181     { return Visit(E->getChosenSubExpr(Ctx)); }
1182   bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
1183   bool VisitBinAssign(const BinaryOperator *E) { return true; }
1184   bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
1185   bool VisitBinaryOperator(const BinaryOperator *E)
1186   { return Visit(E->getLHS()) || Visit(E->getRHS()); }
1187   bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
1188   bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
1189   bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
1190   bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
1191   bool VisitUnaryDeref(const UnaryOperator *E) {
1192     if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
1193       return true;
1194     return Visit(E->getSubExpr());
1195   }
1196   bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
1197 
1198   // Has side effects if any element does.
1199   bool VisitInitListExpr(const InitListExpr *E) {
1200     for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
1201       if (Visit(E->getInit(i))) return true;
1202     if (const Expr *filler = E->getArrayFiller())
1203       return Visit(filler);
1204     return false;
1205   }
1206 
1207   bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
1208 };
1209 
1210 class OpaqueValueEvaluation {
1211   EvalInfo &info;
1212   OpaqueValueExpr *opaqueValue;
1213 
1214 public:
1215   OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
1216                         Expr *value)
1217     : info(info), opaqueValue(opaqueValue) {
1218 
1219     // If evaluation fails, fail immediately.
1220     if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
1221       this->opaqueValue = 0;
1222       return;
1223     }
1224   }
1225 
1226   bool hasError() const { return opaqueValue == 0; }
1227 
1228   ~OpaqueValueEvaluation() {
1229     // FIXME: This will not work for recursive constexpr functions using opaque
1230     // values. Restore the former value.
1231     if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
1232   }
1233 };
1234 
1235 } // end anonymous namespace
1236 
1237 //===----------------------------------------------------------------------===//
1238 // Generic Evaluation
1239 //===----------------------------------------------------------------------===//
1240 namespace {
1241 
1242 template <class Derived, typename RetTy=void>
1243 class ExprEvaluatorBase
1244   : public ConstStmtVisitor<Derived, RetTy> {
1245 private:
1246   RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
1247     return static_cast<Derived*>(this)->Success(V, E);
1248   }
1249   RetTy DerivedError(const Expr *E) {
1250     return static_cast<Derived*>(this)->Error(E);
1251   }
1252   RetTy DerivedValueInitialization(const Expr *E) {
1253     return static_cast<Derived*>(this)->ValueInitialization(E);
1254   }
1255 
1256 protected:
1257   EvalInfo &Info;
1258   typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
1259   typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
1260 
1261   RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
1262 
1263 public:
1264   ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
1265 
1266   RetTy VisitStmt(const Stmt *) {
1267     llvm_unreachable("Expression evaluator should not be called on stmts");
1268   }
1269   RetTy VisitExpr(const Expr *E) {
1270     return DerivedError(E);
1271   }
1272 
1273   RetTy VisitParenExpr(const ParenExpr *E)
1274     { return StmtVisitorTy::Visit(E->getSubExpr()); }
1275   RetTy VisitUnaryExtension(const UnaryOperator *E)
1276     { return StmtVisitorTy::Visit(E->getSubExpr()); }
1277   RetTy VisitUnaryPlus(const UnaryOperator *E)
1278     { return StmtVisitorTy::Visit(E->getSubExpr()); }
1279   RetTy VisitChooseExpr(const ChooseExpr *E)
1280     { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
1281   RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
1282     { return StmtVisitorTy::Visit(E->getResultExpr()); }
1283   RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
1284     { return StmtVisitorTy::Visit(E->getReplacement()); }
1285   RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
1286     { return StmtVisitorTy::Visit(E->getExpr()); }
1287 
1288   RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
1289     OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
1290     if (opaque.hasError())
1291       return DerivedError(E);
1292 
1293     bool cond;
1294     if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
1295       return DerivedError(E);
1296 
1297     return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
1298   }
1299 
1300   RetTy VisitConditionalOperator(const ConditionalOperator *E) {
1301     bool BoolResult;
1302     if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
1303       return DerivedError(E);
1304 
1305     Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
1306     return StmtVisitorTy::Visit(EvalExpr);
1307   }
1308 
1309   RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
1310     const CCValue *Value = Info.getOpaqueValue(E);
1311     if (!Value)
1312       return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
1313                                  : DerivedError(E));
1314     return DerivedSuccess(*Value, E);
1315   }
1316 
1317   RetTy VisitCallExpr(const CallExpr *E) {
1318     const Expr *Callee = E->getCallee();
1319     QualType CalleeType = Callee->getType();
1320 
1321     const FunctionDecl *FD = 0;
1322     LValue *This = 0, ThisVal;
1323     llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
1324 
1325     // Extract function decl and 'this' pointer from the callee.
1326     if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
1327       // Explicit bound member calls, such as x.f() or p->g();
1328       // FIXME: Handle a BinaryOperator callee ('.*' or '->*').
1329       const MemberExpr *ME = dyn_cast<MemberExpr>(Callee->IgnoreParens());
1330       if (!ME)
1331         return DerivedError(Callee);
1332       if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
1333         return DerivedError(ME->getBase());
1334       This = &ThisVal;
1335       FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
1336       if (!FD)
1337         return DerivedError(ME);
1338     } else if (CalleeType->isFunctionPointerType()) {
1339       CCValue Call;
1340       if (!Evaluate(Call, Info, Callee) || !Call.isLValue() ||
1341           !Call.getLValueBase() || !Call.getLValueOffset().isZero())
1342         return DerivedError(Callee);
1343 
1344       const Expr *Base = Call.getLValueBase();
1345 
1346       if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
1347         FD = dyn_cast<FunctionDecl>(DRE->getDecl());
1348       else if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
1349         FD = dyn_cast<FunctionDecl>(ME->getMemberDecl());
1350       if (!FD)
1351         return DerivedError(Callee);
1352 
1353       // Overloaded operator calls to member functions are represented as normal
1354       // calls with '*this' as the first argument.
1355       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1356       if (MD && !MD->isStatic()) {
1357         if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
1358           return false;
1359         This = &ThisVal;
1360         Args = Args.slice(1);
1361       }
1362 
1363       // Don't call function pointers which have been cast to some other type.
1364       if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
1365         return DerivedError(E);
1366     } else
1367       return DerivedError(E);
1368 
1369     const FunctionDecl *Definition;
1370     Stmt *Body = FD->getBody(Definition);
1371     CCValue CCResult;
1372     APValue Result;
1373 
1374     if (Body && Definition->isConstexpr() && !Definition->isInvalidDecl() &&
1375         HandleFunctionCall(This, Args, Body, Info, CCResult) &&
1376         CheckConstantExpression(CCResult, Result))
1377       return DerivedSuccess(CCValue(Result, CCValue::GlobalValue()), E);
1378 
1379     return DerivedError(E);
1380   }
1381 
1382   RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1383     return StmtVisitorTy::Visit(E->getInitializer());
1384   }
1385   RetTy VisitInitListExpr(const InitListExpr *E) {
1386     if (Info.getLangOpts().CPlusPlus0x) {
1387       if (E->getNumInits() == 0)
1388         return DerivedValueInitialization(E);
1389       if (E->getNumInits() == 1)
1390         return StmtVisitorTy::Visit(E->getInit(0));
1391     }
1392     return DerivedError(E);
1393   }
1394   RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1395     return DerivedValueInitialization(E);
1396   }
1397   RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
1398     return DerivedValueInitialization(E);
1399   }
1400 
1401   /// A member expression where the object is a prvalue is itself a prvalue.
1402   RetTy VisitMemberExpr(const MemberExpr *E) {
1403     assert(!E->isArrow() && "missing call to bound member function?");
1404 
1405     CCValue Val;
1406     if (!Evaluate(Val, Info, E->getBase()))
1407       return false;
1408 
1409     QualType BaseTy = E->getBase()->getType();
1410 
1411     const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1412     if (!FD) return false;
1413     assert(!FD->getType()->isReferenceType() && "prvalue reference?");
1414     assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1415            FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1416 
1417     SubobjectDesignator Designator;
1418     Designator.addDecl(FD);
1419 
1420     return ExtractSubobject(Info, Val, BaseTy, Designator, E->getType()) &&
1421            DerivedSuccess(Val, E);
1422   }
1423 
1424   RetTy VisitCastExpr(const CastExpr *E) {
1425     switch (E->getCastKind()) {
1426     default:
1427       break;
1428 
1429     case CK_NoOp:
1430       return StmtVisitorTy::Visit(E->getSubExpr());
1431 
1432     case CK_LValueToRValue: {
1433       LValue LVal;
1434       if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
1435         CCValue RVal;
1436         if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
1437           return DerivedSuccess(RVal, E);
1438       }
1439       break;
1440     }
1441     }
1442 
1443     return DerivedError(E);
1444   }
1445 
1446   /// Visit a value which is evaluated, but whose value is ignored.
1447   void VisitIgnoredValue(const Expr *E) {
1448     CCValue Scratch;
1449     if (!Evaluate(Scratch, Info, E))
1450       Info.EvalStatus.HasSideEffects = true;
1451   }
1452 };
1453 
1454 }
1455 
1456 //===----------------------------------------------------------------------===//
1457 // LValue Evaluation
1458 //
1459 // This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
1460 // function designators (in C), decl references to void objects (in C), and
1461 // temporaries (if building with -Wno-address-of-temporary).
1462 //
1463 // LValue evaluation produces values comprising a base expression of one of the
1464 // following types:
1465 //  * DeclRefExpr
1466 //  * MemberExpr for a static member
1467 //  * CompoundLiteralExpr in C
1468 //  * StringLiteral
1469 //  * PredefinedExpr
1470 //  * ObjCStringLiteralExpr
1471 //  * ObjCEncodeExpr
1472 //  * AddrLabelExpr
1473 //  * BlockExpr
1474 //  * CallExpr for a MakeStringConstant builtin
1475 // plus an offset in bytes. It can also produce lvalues referring to locals. In
1476 // that case, the Frame will point to a stack frame, and the Expr is used as a
1477 // key to find the relevant temporary's value.
1478 //===----------------------------------------------------------------------===//
1479 namespace {
1480 class LValueExprEvaluator
1481   : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
1482   LValue &Result;
1483   const Decl *PrevDecl;
1484 
1485   bool Success(const Expr *E) {
1486     Result.setExpr(E);
1487     return true;
1488   }
1489 public:
1490 
1491   LValueExprEvaluator(EvalInfo &info, LValue &Result) :
1492     ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
1493 
1494   bool Success(const CCValue &V, const Expr *E) {
1495     Result.setFrom(V);
1496     return true;
1497   }
1498   bool Error(const Expr *E) {
1499     return false;
1500   }
1501 
1502   bool VisitVarDecl(const Expr *E, const VarDecl *VD);
1503 
1504   bool VisitDeclRefExpr(const DeclRefExpr *E);
1505   bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
1506   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
1507   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
1508   bool VisitMemberExpr(const MemberExpr *E);
1509   bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
1510   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
1511   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
1512   bool VisitUnaryDeref(const UnaryOperator *E);
1513 
1514   bool VisitCastExpr(const CastExpr *E) {
1515     switch (E->getCastKind()) {
1516     default:
1517       return ExprEvaluatorBaseTy::VisitCastExpr(E);
1518 
1519     case CK_LValueBitCast:
1520       if (!Visit(E->getSubExpr()))
1521         return false;
1522       Result.Designator.setInvalid();
1523       return true;
1524 
1525     case CK_DerivedToBase:
1526     case CK_UncheckedDerivedToBase: {
1527       if (!Visit(E->getSubExpr()))
1528         return false;
1529 
1530       // Now figure out the necessary offset to add to the base LV to get from
1531       // the derived class to the base class.
1532       QualType Type = E->getSubExpr()->getType();
1533 
1534       for (CastExpr::path_const_iterator PathI = E->path_begin(),
1535            PathE = E->path_end(); PathI != PathE; ++PathI) {
1536         if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
1537           return false;
1538         Type = (*PathI)->getType();
1539       }
1540 
1541       return true;
1542     }
1543     }
1544   }
1545 
1546   // FIXME: Missing: __real__, __imag__
1547 
1548 };
1549 } // end anonymous namespace
1550 
1551 /// Evaluate an expression as an lvalue. This can be legitimately called on
1552 /// expressions which are not glvalues, in a few cases:
1553 ///  * function designators in C,
1554 ///  * "extern void" objects,
1555 ///  * temporaries, if building with -Wno-address-of-temporary.
1556 static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
1557   assert((E->isGLValue() || E->getType()->isFunctionType() ||
1558           E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
1559          "can't evaluate expression as an lvalue");
1560   return LValueExprEvaluator(Info, Result).Visit(E);
1561 }
1562 
1563 bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1564   if (isa<FunctionDecl>(E->getDecl()))
1565     return Success(E);
1566   if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
1567     return VisitVarDecl(E, VD);
1568   return Error(E);
1569 }
1570 
1571 bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
1572   if (!VD->getType()->isReferenceType()) {
1573     if (isa<ParmVarDecl>(VD)) {
1574       Result.setExpr(E, Info.CurrentCall);
1575       return true;
1576     }
1577     return Success(E);
1578   }
1579 
1580   CCValue V;
1581   if (EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
1582     return Success(V, E);
1583 
1584   return Error(E);
1585 }
1586 
1587 bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
1588     const MaterializeTemporaryExpr *E) {
1589   Result.setExpr(E, Info.CurrentCall);
1590   return EvaluateConstantExpression(Info.CurrentCall->Temporaries[E], Info,
1591                                     Result, E->GetTemporaryExpr());
1592 }
1593 
1594 bool
1595 LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
1596   assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1597   // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
1598   // only see this when folding in C, so there's no standard to follow here.
1599   return Success(E);
1600 }
1601 
1602 bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
1603   // Handle static data members.
1604   if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
1605     VisitIgnoredValue(E->getBase());
1606     return VisitVarDecl(E, VD);
1607   }
1608 
1609   // Handle static member functions.
1610   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
1611     if (MD->isStatic()) {
1612       VisitIgnoredValue(E->getBase());
1613       return Success(E);
1614     }
1615   }
1616 
1617   // Handle non-static data members.
1618   QualType BaseTy;
1619   if (E->isArrow()) {
1620     if (!EvaluatePointer(E->getBase(), Result, Info))
1621       return false;
1622     BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
1623   } else {
1624     if (!Visit(E->getBase()))
1625       return false;
1626     BaseTy = E->getBase()->getType();
1627   }
1628 
1629   const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
1630   if (!FD) return false;
1631   assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
1632          FD->getParent()->getCanonicalDecl() && "record / field mismatch");
1633   (void)BaseTy;
1634 
1635   HandleLValueMember(Info, Result, FD);
1636 
1637   if (FD->getType()->isReferenceType()) {
1638     CCValue RefValue;
1639     if (!HandleLValueToRValueConversion(Info, FD->getType(), Result, RefValue))
1640       return false;
1641     return Success(RefValue, E);
1642   }
1643   return true;
1644 }
1645 
1646 bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1647   // FIXME: Deal with vectors as array subscript bases.
1648   if (E->getBase()->getType()->isVectorType())
1649     return false;
1650 
1651   if (!EvaluatePointer(E->getBase(), Result, Info))
1652     return false;
1653 
1654   APSInt Index;
1655   if (!EvaluateInteger(E->getIdx(), Index, Info))
1656     return false;
1657   int64_t IndexValue
1658     = Index.isSigned() ? Index.getSExtValue()
1659                        : static_cast<int64_t>(Index.getZExtValue());
1660 
1661   return HandleLValueArrayAdjustment(Info, Result, E->getType(), IndexValue);
1662 }
1663 
1664 bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
1665   return EvaluatePointer(E->getSubExpr(), Result, Info);
1666 }
1667 
1668 //===----------------------------------------------------------------------===//
1669 // Pointer Evaluation
1670 //===----------------------------------------------------------------------===//
1671 
1672 namespace {
1673 class PointerExprEvaluator
1674   : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
1675   LValue &Result;
1676 
1677   bool Success(const Expr *E) {
1678     Result.setExpr(E);
1679     return true;
1680   }
1681 public:
1682 
1683   PointerExprEvaluator(EvalInfo &info, LValue &Result)
1684     : ExprEvaluatorBaseTy(info), Result(Result) {}
1685 
1686   bool Success(const CCValue &V, const Expr *E) {
1687     Result.setFrom(V);
1688     return true;
1689   }
1690   bool Error(const Stmt *S) {
1691     return false;
1692   }
1693   bool ValueInitialization(const Expr *E) {
1694     return Success((Expr*)0);
1695   }
1696 
1697   bool VisitBinaryOperator(const BinaryOperator *E);
1698   bool VisitCastExpr(const CastExpr* E);
1699   bool VisitUnaryAddrOf(const UnaryOperator *E);
1700   bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
1701       { return Success(E); }
1702   bool VisitAddrLabelExpr(const AddrLabelExpr *E)
1703       { return Success(E); }
1704   bool VisitCallExpr(const CallExpr *E);
1705   bool VisitBlockExpr(const BlockExpr *E) {
1706     if (!E->getBlockDecl()->hasCaptures())
1707       return Success(E);
1708     return false;
1709   }
1710   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
1711       { return ValueInitialization(E); }
1712   bool VisitCXXThisExpr(const CXXThisExpr *E) {
1713     if (!Info.CurrentCall->This)
1714       return false;
1715     Result = *Info.CurrentCall->This;
1716     return true;
1717   }
1718 
1719   // FIXME: Missing: @protocol, @selector
1720 };
1721 } // end anonymous namespace
1722 
1723 static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
1724   assert(E->isRValue() && E->getType()->hasPointerRepresentation());
1725   return PointerExprEvaluator(Info, Result).Visit(E);
1726 }
1727 
1728 bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1729   if (E->getOpcode() != BO_Add &&
1730       E->getOpcode() != BO_Sub)
1731     return false;
1732 
1733   const Expr *PExp = E->getLHS();
1734   const Expr *IExp = E->getRHS();
1735   if (IExp->getType()->isPointerType())
1736     std::swap(PExp, IExp);
1737 
1738   if (!EvaluatePointer(PExp, Result, Info))
1739     return false;
1740 
1741   llvm::APSInt Offset;
1742   if (!EvaluateInteger(IExp, Offset, Info))
1743     return false;
1744   int64_t AdditionalOffset
1745     = Offset.isSigned() ? Offset.getSExtValue()
1746                         : static_cast<int64_t>(Offset.getZExtValue());
1747   if (E->getOpcode() == BO_Sub)
1748     AdditionalOffset = -AdditionalOffset;
1749 
1750   QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
1751   return HandleLValueArrayAdjustment(Info, Result, Pointee, AdditionalOffset);
1752 }
1753 
1754 bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
1755   return EvaluateLValue(E->getSubExpr(), Result, Info);
1756 }
1757 
1758 bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
1759   const Expr* SubExpr = E->getSubExpr();
1760 
1761   switch (E->getCastKind()) {
1762   default:
1763     break;
1764 
1765   case CK_BitCast:
1766   case CK_CPointerToObjCPointerCast:
1767   case CK_BlockPointerToObjCPointerCast:
1768   case CK_AnyPointerToBlockPointerCast:
1769     if (!Visit(SubExpr))
1770       return false;
1771     Result.Designator.setInvalid();
1772     return true;
1773 
1774   case CK_DerivedToBase:
1775   case CK_UncheckedDerivedToBase: {
1776     if (!EvaluatePointer(E->getSubExpr(), Result, Info))
1777       return false;
1778 
1779     // Now figure out the necessary offset to add to the base LV to get from
1780     // the derived class to the base class.
1781     QualType Type =
1782         E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
1783 
1784     for (CastExpr::path_const_iterator PathI = E->path_begin(),
1785          PathE = E->path_end(); PathI != PathE; ++PathI) {
1786       if (!HandleLValueBase(Info, Result, Type->getAsCXXRecordDecl(), *PathI))
1787         return false;
1788       Type = (*PathI)->getType();
1789     }
1790 
1791     return true;
1792   }
1793 
1794   case CK_NullToPointer:
1795     return ValueInitialization(E);
1796 
1797   case CK_IntegralToPointer: {
1798     CCValue Value;
1799     if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
1800       break;
1801 
1802     if (Value.isInt()) {
1803       unsigned Size = Info.Ctx.getTypeSize(E->getType());
1804       uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
1805       Result.Base = 0;
1806       Result.Offset = CharUnits::fromQuantity(N);
1807       Result.Frame = 0;
1808       Result.Designator.setInvalid();
1809       return true;
1810     } else {
1811       // Cast is of an lvalue, no need to change value.
1812       Result.setFrom(Value);
1813       return true;
1814     }
1815   }
1816   case CK_ArrayToPointerDecay:
1817     // FIXME: Support array-to-pointer decay on array rvalues.
1818     if (!SubExpr->isGLValue())
1819       return Error(E);
1820     if (!EvaluateLValue(SubExpr, Result, Info))
1821       return false;
1822     // The result is a pointer to the first element of the array.
1823     Result.Designator.addIndex(0);
1824     return true;
1825 
1826   case CK_FunctionToPointerDecay:
1827     return EvaluateLValue(SubExpr, Result, Info);
1828   }
1829 
1830   return ExprEvaluatorBaseTy::VisitCastExpr(E);
1831 }
1832 
1833 bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
1834   if (IsStringLiteralCall(E))
1835     return Success(E);
1836 
1837   return ExprEvaluatorBaseTy::VisitCallExpr(E);
1838 }
1839 
1840 //===----------------------------------------------------------------------===//
1841 // Record Evaluation
1842 //===----------------------------------------------------------------------===//
1843 
1844 namespace {
1845   class RecordExprEvaluator
1846   : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
1847     const LValue &This;
1848     APValue &Result;
1849   public:
1850 
1851     RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
1852       : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
1853 
1854     bool Success(const CCValue &V, const Expr *E) {
1855       return CheckConstantExpression(V, Result);
1856     }
1857     bool Error(const Expr *E) { return false; }
1858 
1859     bool VisitCastExpr(const CastExpr *E);
1860     bool VisitInitListExpr(const InitListExpr *E);
1861     bool VisitCXXConstructExpr(const CXXConstructExpr *E);
1862   };
1863 }
1864 
1865 bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
1866   switch (E->getCastKind()) {
1867   default:
1868     return ExprEvaluatorBaseTy::VisitCastExpr(E);
1869 
1870   case CK_ConstructorConversion:
1871     return Visit(E->getSubExpr());
1872 
1873   case CK_DerivedToBase:
1874   case CK_UncheckedDerivedToBase: {
1875     CCValue DerivedObject;
1876     if (!Evaluate(DerivedObject, Info, E->getSubExpr()) ||
1877         !DerivedObject.isStruct())
1878       return false;
1879 
1880     // Derived-to-base rvalue conversion: just slice off the derived part.
1881     APValue *Value = &DerivedObject;
1882     const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
1883     for (CastExpr::path_const_iterator PathI = E->path_begin(),
1884          PathE = E->path_end(); PathI != PathE; ++PathI) {
1885       assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
1886       const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
1887       Value = &Value->getStructBase(getBaseIndex(RD, Base));
1888       RD = Base;
1889     }
1890     Result = *Value;
1891     return true;
1892   }
1893   }
1894 }
1895 
1896 bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
1897   const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
1898   const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1899 
1900   if (RD->isUnion()) {
1901     Result = APValue(E->getInitializedFieldInUnion());
1902     if (!E->getNumInits())
1903       return true;
1904     LValue Subobject = This;
1905     HandleLValueMember(Info, Subobject, E->getInitializedFieldInUnion(),
1906                        &Layout);
1907     return EvaluateConstantExpression(Result.getUnionValue(), Info,
1908                                       Subobject, E->getInit(0));
1909   }
1910 
1911   assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
1912          "initializer list for class with base classes");
1913   Result = APValue(APValue::UninitStruct(), 0,
1914                    std::distance(RD->field_begin(), RD->field_end()));
1915   unsigned ElementNo = 0;
1916   for (RecordDecl::field_iterator Field = RD->field_begin(),
1917        FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
1918     // Anonymous bit-fields are not considered members of the class for
1919     // purposes of aggregate initialization.
1920     if (Field->isUnnamedBitfield())
1921       continue;
1922 
1923     LValue Subobject = This;
1924     HandleLValueMember(Info, Subobject, *Field, &Layout);
1925 
1926     if (ElementNo < E->getNumInits()) {
1927       if (!EvaluateConstantExpression(
1928             Result.getStructField((*Field)->getFieldIndex()),
1929             Info, Subobject, E->getInit(ElementNo++)))
1930         return false;
1931     } else {
1932       // Perform an implicit value-initialization for members beyond the end of
1933       // the initializer list.
1934       ImplicitValueInitExpr VIE(Field->getType());
1935       if (!EvaluateConstantExpression(
1936             Result.getStructField((*Field)->getFieldIndex()),
1937             Info, Subobject, &VIE))
1938         return false;
1939     }
1940   }
1941 
1942   return true;
1943 }
1944 
1945 bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
1946   const CXXConstructorDecl *FD = E->getConstructor();
1947   const FunctionDecl *Definition = 0;
1948   FD->getBody(Definition);
1949 
1950   if (!Definition || !Definition->isConstexpr() || Definition->isInvalidDecl())
1951     return false;
1952 
1953   // FIXME: Elide the copy/move construction wherever we can.
1954   if (E->isElidable())
1955     if (const MaterializeTemporaryExpr *ME
1956           = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
1957       return Visit(ME->GetTemporaryExpr());
1958 
1959   llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
1960   return HandleConstructorCall(This, Args, cast<CXXConstructorDecl>(Definition),
1961                                Info, Result);
1962 }
1963 
1964 static bool EvaluateRecord(const Expr *E, const LValue &This,
1965                            APValue &Result, EvalInfo &Info) {
1966   assert(E->isRValue() && E->getType()->isRecordType() &&
1967          E->getType()->isLiteralType() &&
1968          "can't evaluate expression as a record rvalue");
1969   return RecordExprEvaluator(Info, This, Result).Visit(E);
1970 }
1971 
1972 //===----------------------------------------------------------------------===//
1973 // Vector Evaluation
1974 //===----------------------------------------------------------------------===//
1975 
1976 namespace {
1977   class VectorExprEvaluator
1978   : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
1979     APValue &Result;
1980   public:
1981 
1982     VectorExprEvaluator(EvalInfo &info, APValue &Result)
1983       : ExprEvaluatorBaseTy(info), Result(Result) {}
1984 
1985     bool Success(const ArrayRef<APValue> &V, const Expr *E) {
1986       assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
1987       // FIXME: remove this APValue copy.
1988       Result = APValue(V.data(), V.size());
1989       return true;
1990     }
1991     bool Success(const CCValue &V, const Expr *E) {
1992       assert(V.isVector());
1993       Result = V;
1994       return true;
1995     }
1996     bool Error(const Expr *E) { return false; }
1997     bool ValueInitialization(const Expr *E);
1998 
1999     bool VisitUnaryReal(const UnaryOperator *E)
2000       { return Visit(E->getSubExpr()); }
2001     bool VisitCastExpr(const CastExpr* E);
2002     bool VisitInitListExpr(const InitListExpr *E);
2003     bool VisitUnaryImag(const UnaryOperator *E);
2004     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
2005     //                 binary comparisons, binary and/or/xor,
2006     //                 shufflevector, ExtVectorElementExpr
2007     //        (Note that these require implementing conversions
2008     //         between vector types.)
2009   };
2010 } // end anonymous namespace
2011 
2012 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
2013   assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
2014   return VectorExprEvaluator(Info, Result).Visit(E);
2015 }
2016 
2017 bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
2018   const VectorType *VTy = E->getType()->castAs<VectorType>();
2019   QualType EltTy = VTy->getElementType();
2020   unsigned NElts = VTy->getNumElements();
2021   unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
2022 
2023   const Expr* SE = E->getSubExpr();
2024   QualType SETy = SE->getType();
2025 
2026   switch (E->getCastKind()) {
2027   case CK_VectorSplat: {
2028     APValue Val = APValue();
2029     if (SETy->isIntegerType()) {
2030       APSInt IntResult;
2031       if (!EvaluateInteger(SE, IntResult, Info))
2032          return Error(E);
2033       Val = APValue(IntResult);
2034     } else if (SETy->isRealFloatingType()) {
2035        APFloat F(0.0);
2036        if (!EvaluateFloat(SE, F, Info))
2037          return Error(E);
2038        Val = APValue(F);
2039     } else {
2040       return Error(E);
2041     }
2042 
2043     // Splat and create vector APValue.
2044     SmallVector<APValue, 4> Elts(NElts, Val);
2045     return Success(Elts, E);
2046   }
2047   case CK_BitCast: {
2048     // FIXME: this is wrong for any cast other than a no-op cast.
2049     if (SETy->isVectorType())
2050       return Visit(SE);
2051 
2052     if (!SETy->isIntegerType())
2053       return Error(E);
2054 
2055     APSInt Init;
2056     if (!EvaluateInteger(SE, Init, Info))
2057       return Error(E);
2058 
2059     assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
2060            "Vectors must be composed of ints or floats");
2061 
2062     SmallVector<APValue, 4> Elts;
2063     for (unsigned i = 0; i != NElts; ++i) {
2064       APSInt Tmp = Init.extOrTrunc(EltWidth);
2065 
2066       if (EltTy->isIntegerType())
2067         Elts.push_back(APValue(Tmp));
2068       else
2069         Elts.push_back(APValue(APFloat(Tmp)));
2070 
2071       Init >>= EltWidth;
2072     }
2073     return Success(Elts, E);
2074   }
2075   default:
2076     return ExprEvaluatorBaseTy::VisitCastExpr(E);
2077   }
2078 }
2079 
2080 bool
2081 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2082   const VectorType *VT = E->getType()->castAs<VectorType>();
2083   unsigned NumInits = E->getNumInits();
2084   unsigned NumElements = VT->getNumElements();
2085 
2086   QualType EltTy = VT->getElementType();
2087   SmallVector<APValue, 4> Elements;
2088 
2089   // If a vector is initialized with a single element, that value
2090   // becomes every element of the vector, not just the first.
2091   // This is the behavior described in the IBM AltiVec documentation.
2092   if (NumInits == 1) {
2093 
2094     // Handle the case where the vector is initialized by another
2095     // vector (OpenCL 6.1.6).
2096     if (E->getInit(0)->getType()->isVectorType())
2097       return Visit(E->getInit(0));
2098 
2099     APValue InitValue;
2100     if (EltTy->isIntegerType()) {
2101       llvm::APSInt sInt(32);
2102       if (!EvaluateInteger(E->getInit(0), sInt, Info))
2103         return Error(E);
2104       InitValue = APValue(sInt);
2105     } else {
2106       llvm::APFloat f(0.0);
2107       if (!EvaluateFloat(E->getInit(0), f, Info))
2108         return Error(E);
2109       InitValue = APValue(f);
2110     }
2111     for (unsigned i = 0; i < NumElements; i++) {
2112       Elements.push_back(InitValue);
2113     }
2114   } else {
2115     for (unsigned i = 0; i < NumElements; i++) {
2116       if (EltTy->isIntegerType()) {
2117         llvm::APSInt sInt(32);
2118         if (i < NumInits) {
2119           if (!EvaluateInteger(E->getInit(i), sInt, Info))
2120             return Error(E);
2121         } else {
2122           sInt = Info.Ctx.MakeIntValue(0, EltTy);
2123         }
2124         Elements.push_back(APValue(sInt));
2125       } else {
2126         llvm::APFloat f(0.0);
2127         if (i < NumInits) {
2128           if (!EvaluateFloat(E->getInit(i), f, Info))
2129             return Error(E);
2130         } else {
2131           f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
2132         }
2133         Elements.push_back(APValue(f));
2134       }
2135     }
2136   }
2137   return Success(Elements, E);
2138 }
2139 
2140 bool
2141 VectorExprEvaluator::ValueInitialization(const Expr *E) {
2142   const VectorType *VT = E->getType()->getAs<VectorType>();
2143   QualType EltTy = VT->getElementType();
2144   APValue ZeroElement;
2145   if (EltTy->isIntegerType())
2146     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
2147   else
2148     ZeroElement =
2149         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
2150 
2151   SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
2152   return Success(Elements, E);
2153 }
2154 
2155 bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2156   VisitIgnoredValue(E->getSubExpr());
2157   return ValueInitialization(E);
2158 }
2159 
2160 //===----------------------------------------------------------------------===//
2161 // Array Evaluation
2162 //===----------------------------------------------------------------------===//
2163 
2164 namespace {
2165   class ArrayExprEvaluator
2166   : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
2167     const LValue &This;
2168     APValue &Result;
2169   public:
2170 
2171     ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
2172       : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
2173 
2174     bool Success(const APValue &V, const Expr *E) {
2175       assert(V.isArray() && "Expected array type");
2176       Result = V;
2177       return true;
2178     }
2179     bool Error(const Expr *E) { return false; }
2180 
2181     bool ValueInitialization(const Expr *E) {
2182       const ConstantArrayType *CAT =
2183           Info.Ctx.getAsConstantArrayType(E->getType());
2184       if (!CAT)
2185         return false;
2186 
2187       Result = APValue(APValue::UninitArray(), 0,
2188                        CAT->getSize().getZExtValue());
2189       if (!Result.hasArrayFiller()) return true;
2190 
2191       // Value-initialize all elements.
2192       LValue Subobject = This;
2193       Subobject.Designator.addIndex(0);
2194       ImplicitValueInitExpr VIE(CAT->getElementType());
2195       return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2196                                         Subobject, &VIE);
2197     }
2198 
2199     // FIXME: We also get CXXConstructExpr, in cases like:
2200     //   struct S { constexpr S(); }; constexpr S s[10];
2201     bool VisitInitListExpr(const InitListExpr *E);
2202   };
2203 } // end anonymous namespace
2204 
2205 static bool EvaluateArray(const Expr *E, const LValue &This,
2206                           APValue &Result, EvalInfo &Info) {
2207   assert(E->isRValue() && E->getType()->isArrayType() &&
2208          E->getType()->isLiteralType() && "not a literal array rvalue");
2209   return ArrayExprEvaluator(Info, This, Result).Visit(E);
2210 }
2211 
2212 bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
2213   const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
2214   if (!CAT)
2215     return false;
2216 
2217   Result = APValue(APValue::UninitArray(), E->getNumInits(),
2218                    CAT->getSize().getZExtValue());
2219   LValue Subobject = This;
2220   Subobject.Designator.addIndex(0);
2221   unsigned Index = 0;
2222   for (InitListExpr::const_iterator I = E->begin(), End = E->end();
2223        I != End; ++I, ++Index) {
2224     if (!EvaluateConstantExpression(Result.getArrayInitializedElt(Index),
2225                                     Info, Subobject, cast<Expr>(*I)))
2226       return false;
2227     if (!HandleLValueArrayAdjustment(Info, Subobject, CAT->getElementType(), 1))
2228       return false;
2229   }
2230 
2231   if (!Result.hasArrayFiller()) return true;
2232   assert(E->hasArrayFiller() && "no array filler for incomplete init list");
2233   // FIXME: The Subobject here isn't necessarily right. This rarely matters,
2234   // but sometimes does:
2235   //   struct S { constexpr S() : p(&p) {} void *p; };
2236   //   S s[10] = {};
2237   return EvaluateConstantExpression(Result.getArrayFiller(), Info,
2238                                     Subobject, E->getArrayFiller());
2239 }
2240 
2241 //===----------------------------------------------------------------------===//
2242 // Integer Evaluation
2243 //
2244 // As a GNU extension, we support casting pointers to sufficiently-wide integer
2245 // types and back in constant folding. Integer values are thus represented
2246 // either as an integer-valued APValue, or as an lvalue-valued APValue.
2247 //===----------------------------------------------------------------------===//
2248 
2249 namespace {
2250 class IntExprEvaluator
2251   : public ExprEvaluatorBase<IntExprEvaluator, bool> {
2252   CCValue &Result;
2253 public:
2254   IntExprEvaluator(EvalInfo &info, CCValue &result)
2255     : ExprEvaluatorBaseTy(info), Result(result) {}
2256 
2257   bool Success(const llvm::APSInt &SI, const Expr *E) {
2258     assert(E->getType()->isIntegralOrEnumerationType() &&
2259            "Invalid evaluation result.");
2260     assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
2261            "Invalid evaluation result.");
2262     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
2263            "Invalid evaluation result.");
2264     Result = CCValue(SI);
2265     return true;
2266   }
2267 
2268   bool Success(const llvm::APInt &I, const Expr *E) {
2269     assert(E->getType()->isIntegralOrEnumerationType() &&
2270            "Invalid evaluation result.");
2271     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
2272            "Invalid evaluation result.");
2273     Result = CCValue(APSInt(I));
2274     Result.getInt().setIsUnsigned(
2275                             E->getType()->isUnsignedIntegerOrEnumerationType());
2276     return true;
2277   }
2278 
2279   bool Success(uint64_t Value, const Expr *E) {
2280     assert(E->getType()->isIntegralOrEnumerationType() &&
2281            "Invalid evaluation result.");
2282     Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
2283     return true;
2284   }
2285 
2286   bool Success(CharUnits Size, const Expr *E) {
2287     return Success(Size.getQuantity(), E);
2288   }
2289 
2290 
2291   bool Error(SourceLocation L, diag::kind D, const Expr *E) {
2292     // Take the first error.
2293     if (Info.EvalStatus.Diag == 0) {
2294       Info.EvalStatus.DiagLoc = L;
2295       Info.EvalStatus.Diag = D;
2296       Info.EvalStatus.DiagExpr = E;
2297     }
2298     return false;
2299   }
2300 
2301   bool Success(const CCValue &V, const Expr *E) {
2302     if (V.isLValue()) {
2303       Result = V;
2304       return true;
2305     }
2306     return Success(V.getInt(), E);
2307   }
2308   bool Error(const Expr *E) {
2309     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2310   }
2311 
2312   bool ValueInitialization(const Expr *E) { return Success(0, E); }
2313 
2314   //===--------------------------------------------------------------------===//
2315   //                            Visitor Methods
2316   //===--------------------------------------------------------------------===//
2317 
2318   bool VisitIntegerLiteral(const IntegerLiteral *E) {
2319     return Success(E->getValue(), E);
2320   }
2321   bool VisitCharacterLiteral(const CharacterLiteral *E) {
2322     return Success(E->getValue(), E);
2323   }
2324 
2325   bool CheckReferencedDecl(const Expr *E, const Decl *D);
2326   bool VisitDeclRefExpr(const DeclRefExpr *E) {
2327     if (CheckReferencedDecl(E, E->getDecl()))
2328       return true;
2329 
2330     return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
2331   }
2332   bool VisitMemberExpr(const MemberExpr *E) {
2333     if (CheckReferencedDecl(E, E->getMemberDecl())) {
2334       VisitIgnoredValue(E->getBase());
2335       return true;
2336     }
2337 
2338     return ExprEvaluatorBaseTy::VisitMemberExpr(E);
2339   }
2340 
2341   bool VisitCallExpr(const CallExpr *E);
2342   bool VisitBinaryOperator(const BinaryOperator *E);
2343   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
2344   bool VisitUnaryOperator(const UnaryOperator *E);
2345 
2346   bool VisitCastExpr(const CastExpr* E);
2347   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
2348 
2349   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
2350     return Success(E->getValue(), E);
2351   }
2352 
2353   // Note, GNU defines __null as an integer, not a pointer.
2354   bool VisitGNUNullExpr(const GNUNullExpr *E) {
2355     return ValueInitialization(E);
2356   }
2357 
2358   bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
2359     return Success(E->getValue(), E);
2360   }
2361 
2362   bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
2363     return Success(E->getValue(), E);
2364   }
2365 
2366   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2367     return Success(E->getValue(), E);
2368   }
2369 
2370   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
2371     return Success(E->getValue(), E);
2372   }
2373 
2374   bool VisitUnaryReal(const UnaryOperator *E);
2375   bool VisitUnaryImag(const UnaryOperator *E);
2376 
2377   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
2378   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
2379 
2380 private:
2381   CharUnits GetAlignOfExpr(const Expr *E);
2382   CharUnits GetAlignOfType(QualType T);
2383   static QualType GetObjectType(const Expr *E);
2384   bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
2385   // FIXME: Missing: array subscript of vector, member of vector
2386 };
2387 } // end anonymous namespace
2388 
2389 /// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
2390 /// produce either the integer value or a pointer.
2391 ///
2392 /// GCC has a heinous extension which folds casts between pointer types and
2393 /// pointer-sized integral types. We support this by allowing the evaluation of
2394 /// an integer rvalue to produce a pointer (represented as an lvalue) instead.
2395 /// Some simple arithmetic on such values is supported (they are treated much
2396 /// like char*).
2397 static bool EvaluateIntegerOrLValue(const Expr* E, CCValue &Result,
2398                                     EvalInfo &Info) {
2399   assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
2400   return IntExprEvaluator(Info, Result).Visit(E);
2401 }
2402 
2403 static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
2404   CCValue Val;
2405   if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
2406     return false;
2407   Result = Val.getInt();
2408   return true;
2409 }
2410 
2411 bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
2412   // Enums are integer constant exprs.
2413   if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
2414     // Check for signedness/width mismatches between E type and ECD value.
2415     bool SameSign = (ECD->getInitVal().isSigned()
2416                      == E->getType()->isSignedIntegerOrEnumerationType());
2417     bool SameWidth = (ECD->getInitVal().getBitWidth()
2418                       == Info.Ctx.getIntWidth(E->getType()));
2419     if (SameSign && SameWidth)
2420       return Success(ECD->getInitVal(), E);
2421     else {
2422       // Get rid of mismatch (otherwise Success assertions will fail)
2423       // by computing a new value matching the type of E.
2424       llvm::APSInt Val = ECD->getInitVal();
2425       if (!SameSign)
2426         Val.setIsSigned(!ECD->getInitVal().isSigned());
2427       if (!SameWidth)
2428         Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
2429       return Success(Val, E);
2430     }
2431   }
2432   return false;
2433 }
2434 
2435 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
2436 /// as GCC.
2437 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
2438   // The following enum mimics the values returned by GCC.
2439   // FIXME: Does GCC differ between lvalue and rvalue references here?
2440   enum gcc_type_class {
2441     no_type_class = -1,
2442     void_type_class, integer_type_class, char_type_class,
2443     enumeral_type_class, boolean_type_class,
2444     pointer_type_class, reference_type_class, offset_type_class,
2445     real_type_class, complex_type_class,
2446     function_type_class, method_type_class,
2447     record_type_class, union_type_class,
2448     array_type_class, string_type_class,
2449     lang_type_class
2450   };
2451 
2452   // If no argument was supplied, default to "no_type_class". This isn't
2453   // ideal, however it is what gcc does.
2454   if (E->getNumArgs() == 0)
2455     return no_type_class;
2456 
2457   QualType ArgTy = E->getArg(0)->getType();
2458   if (ArgTy->isVoidType())
2459     return void_type_class;
2460   else if (ArgTy->isEnumeralType())
2461     return enumeral_type_class;
2462   else if (ArgTy->isBooleanType())
2463     return boolean_type_class;
2464   else if (ArgTy->isCharType())
2465     return string_type_class; // gcc doesn't appear to use char_type_class
2466   else if (ArgTy->isIntegerType())
2467     return integer_type_class;
2468   else if (ArgTy->isPointerType())
2469     return pointer_type_class;
2470   else if (ArgTy->isReferenceType())
2471     return reference_type_class;
2472   else if (ArgTy->isRealType())
2473     return real_type_class;
2474   else if (ArgTy->isComplexType())
2475     return complex_type_class;
2476   else if (ArgTy->isFunctionType())
2477     return function_type_class;
2478   else if (ArgTy->isStructureOrClassType())
2479     return record_type_class;
2480   else if (ArgTy->isUnionType())
2481     return union_type_class;
2482   else if (ArgTy->isArrayType())
2483     return array_type_class;
2484   else if (ArgTy->isUnionType())
2485     return union_type_class;
2486   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
2487     llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
2488   return -1;
2489 }
2490 
2491 /// Retrieves the "underlying object type" of the given expression,
2492 /// as used by __builtin_object_size.
2493 QualType IntExprEvaluator::GetObjectType(const Expr *E) {
2494   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
2495     if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2496       return VD->getType();
2497   } else if (isa<CompoundLiteralExpr>(E)) {
2498     return E->getType();
2499   }
2500 
2501   return QualType();
2502 }
2503 
2504 bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
2505   // TODO: Perhaps we should let LLVM lower this?
2506   LValue Base;
2507   if (!EvaluatePointer(E->getArg(0), Base, Info))
2508     return false;
2509 
2510   // If we can prove the base is null, lower to zero now.
2511   const Expr *LVBase = Base.getLValueBase();
2512   if (!LVBase) return Success(0, E);
2513 
2514   QualType T = GetObjectType(LVBase);
2515   if (T.isNull() ||
2516       T->isIncompleteType() ||
2517       T->isFunctionType() ||
2518       T->isVariablyModifiedType() ||
2519       T->isDependentType())
2520     return false;
2521 
2522   CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
2523   CharUnits Offset = Base.getLValueOffset();
2524 
2525   if (!Offset.isNegative() && Offset <= Size)
2526     Size -= Offset;
2527   else
2528     Size = CharUnits::Zero();
2529   return Success(Size, E);
2530 }
2531 
2532 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
2533   switch (E->isBuiltinCall()) {
2534   default:
2535     return ExprEvaluatorBaseTy::VisitCallExpr(E);
2536 
2537   case Builtin::BI__builtin_object_size: {
2538     if (TryEvaluateBuiltinObjectSize(E))
2539       return true;
2540 
2541     // If evaluating the argument has side-effects we can't determine
2542     // the size of the object and lower it to unknown now.
2543     if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
2544       if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
2545         return Success(-1ULL, E);
2546       return Success(0, E);
2547     }
2548 
2549     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2550   }
2551 
2552   case Builtin::BI__builtin_classify_type:
2553     return Success(EvaluateBuiltinClassifyType(E), E);
2554 
2555   case Builtin::BI__builtin_constant_p:
2556     // __builtin_constant_p always has one operand: it returns true if that
2557     // operand can be folded, false otherwise.
2558     return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
2559 
2560   case Builtin::BI__builtin_eh_return_data_regno: {
2561     int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
2562     Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
2563     return Success(Operand, E);
2564   }
2565 
2566   case Builtin::BI__builtin_expect:
2567     return Visit(E->getArg(0));
2568 
2569   case Builtin::BIstrlen:
2570   case Builtin::BI__builtin_strlen:
2571     // As an extension, we support strlen() and __builtin_strlen() as constant
2572     // expressions when the argument is a string literal.
2573     if (const StringLiteral *S
2574                = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
2575       // The string literal may have embedded null characters. Find the first
2576       // one and truncate there.
2577       StringRef Str = S->getString();
2578       StringRef::size_type Pos = Str.find(0);
2579       if (Pos != StringRef::npos)
2580         Str = Str.substr(0, Pos);
2581 
2582       return Success(Str.size(), E);
2583     }
2584 
2585     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2586 
2587   case Builtin::BI__atomic_is_lock_free: {
2588     APSInt SizeVal;
2589     if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
2590       return false;
2591 
2592     // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
2593     // of two less than the maximum inline atomic width, we know it is
2594     // lock-free.  If the size isn't a power of two, or greater than the
2595     // maximum alignment where we promote atomics, we know it is not lock-free
2596     // (at least not in the sense of atomic_is_lock_free).  Otherwise,
2597     // the answer can only be determined at runtime; for example, 16-byte
2598     // atomics have lock-free implementations on some, but not all,
2599     // x86-64 processors.
2600 
2601     // Check power-of-two.
2602     CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
2603     if (!Size.isPowerOfTwo())
2604 #if 0
2605       // FIXME: Suppress this folding until the ABI for the promotion width
2606       // settles.
2607       return Success(0, E);
2608 #else
2609       return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2610 #endif
2611 
2612 #if 0
2613     // Check against promotion width.
2614     // FIXME: Suppress this folding until the ABI for the promotion width
2615     // settles.
2616     unsigned PromoteWidthBits =
2617         Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
2618     if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
2619       return Success(0, E);
2620 #endif
2621 
2622     // Check against inlining width.
2623     unsigned InlineWidthBits =
2624         Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
2625     if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
2626       return Success(1, E);
2627 
2628     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
2629   }
2630   }
2631 }
2632 
2633 static bool HasSameBase(const LValue &A, const LValue &B) {
2634   if (!A.getLValueBase())
2635     return !B.getLValueBase();
2636   if (!B.getLValueBase())
2637     return false;
2638 
2639   if (A.getLValueBase() != B.getLValueBase()) {
2640     const Decl *ADecl = GetLValueBaseDecl(A);
2641     if (!ADecl)
2642       return false;
2643     const Decl *BDecl = GetLValueBaseDecl(B);
2644     if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
2645       return false;
2646   }
2647 
2648   return IsGlobalLValue(A.getLValueBase()) ||
2649          A.getLValueFrame() == B.getLValueFrame();
2650 }
2651 
2652 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2653   if (E->isAssignmentOp())
2654     return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2655 
2656   if (E->getOpcode() == BO_Comma) {
2657     VisitIgnoredValue(E->getLHS());
2658     return Visit(E->getRHS());
2659   }
2660 
2661   if (E->isLogicalOp()) {
2662     // These need to be handled specially because the operands aren't
2663     // necessarily integral
2664     bool lhsResult, rhsResult;
2665 
2666     if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
2667       // We were able to evaluate the LHS, see if we can get away with not
2668       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
2669       if (lhsResult == (E->getOpcode() == BO_LOr))
2670         return Success(lhsResult, E);
2671 
2672       if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
2673         if (E->getOpcode() == BO_LOr)
2674           return Success(lhsResult || rhsResult, E);
2675         else
2676           return Success(lhsResult && rhsResult, E);
2677       }
2678     } else {
2679       if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
2680         // We can't evaluate the LHS; however, sometimes the result
2681         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
2682         if (rhsResult == (E->getOpcode() == BO_LOr) ||
2683             !rhsResult == (E->getOpcode() == BO_LAnd)) {
2684           // Since we weren't able to evaluate the left hand side, it
2685           // must have had side effects.
2686           Info.EvalStatus.HasSideEffects = true;
2687 
2688           return Success(rhsResult, E);
2689         }
2690       }
2691     }
2692 
2693     return false;
2694   }
2695 
2696   QualType LHSTy = E->getLHS()->getType();
2697   QualType RHSTy = E->getRHS()->getType();
2698 
2699   if (LHSTy->isAnyComplexType()) {
2700     assert(RHSTy->isAnyComplexType() && "Invalid comparison");
2701     ComplexValue LHS, RHS;
2702 
2703     if (!EvaluateComplex(E->getLHS(), LHS, Info))
2704       return false;
2705 
2706     if (!EvaluateComplex(E->getRHS(), RHS, Info))
2707       return false;
2708 
2709     if (LHS.isComplexFloat()) {
2710       APFloat::cmpResult CR_r =
2711         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
2712       APFloat::cmpResult CR_i =
2713         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
2714 
2715       if (E->getOpcode() == BO_EQ)
2716         return Success((CR_r == APFloat::cmpEqual &&
2717                         CR_i == APFloat::cmpEqual), E);
2718       else {
2719         assert(E->getOpcode() == BO_NE &&
2720                "Invalid complex comparison.");
2721         return Success(((CR_r == APFloat::cmpGreaterThan ||
2722                          CR_r == APFloat::cmpLessThan ||
2723                          CR_r == APFloat::cmpUnordered) ||
2724                         (CR_i == APFloat::cmpGreaterThan ||
2725                          CR_i == APFloat::cmpLessThan ||
2726                          CR_i == APFloat::cmpUnordered)), E);
2727       }
2728     } else {
2729       if (E->getOpcode() == BO_EQ)
2730         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
2731                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
2732       else {
2733         assert(E->getOpcode() == BO_NE &&
2734                "Invalid compex comparison.");
2735         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
2736                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
2737       }
2738     }
2739   }
2740 
2741   if (LHSTy->isRealFloatingType() &&
2742       RHSTy->isRealFloatingType()) {
2743     APFloat RHS(0.0), LHS(0.0);
2744 
2745     if (!EvaluateFloat(E->getRHS(), RHS, Info))
2746       return false;
2747 
2748     if (!EvaluateFloat(E->getLHS(), LHS, Info))
2749       return false;
2750 
2751     APFloat::cmpResult CR = LHS.compare(RHS);
2752 
2753     switch (E->getOpcode()) {
2754     default:
2755       llvm_unreachable("Invalid binary operator!");
2756     case BO_LT:
2757       return Success(CR == APFloat::cmpLessThan, E);
2758     case BO_GT:
2759       return Success(CR == APFloat::cmpGreaterThan, E);
2760     case BO_LE:
2761       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
2762     case BO_GE:
2763       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
2764                      E);
2765     case BO_EQ:
2766       return Success(CR == APFloat::cmpEqual, E);
2767     case BO_NE:
2768       return Success(CR == APFloat::cmpGreaterThan
2769                      || CR == APFloat::cmpLessThan
2770                      || CR == APFloat::cmpUnordered, E);
2771     }
2772   }
2773 
2774   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
2775     if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
2776       LValue LHSValue;
2777       if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
2778         return false;
2779 
2780       LValue RHSValue;
2781       if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
2782         return false;
2783 
2784       // Reject differing bases from the normal codepath; we special-case
2785       // comparisons to null.
2786       if (!HasSameBase(LHSValue, RHSValue)) {
2787         // Inequalities and subtractions between unrelated pointers have
2788         // unspecified or undefined behavior.
2789         if (!E->isEqualityOp())
2790           return false;
2791         // A constant address may compare equal to the address of a symbol.
2792         // The one exception is that address of an object cannot compare equal
2793         // to a null pointer constant.
2794         if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
2795             (!RHSValue.Base && !RHSValue.Offset.isZero()))
2796           return false;
2797         // It's implementation-defined whether distinct literals will have
2798         // distinct addresses. In clang, we do not guarantee the addresses are
2799         // distinct. However, we do know that the address of a literal will be
2800         // non-null.
2801         if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
2802             LHSValue.Base && RHSValue.Base)
2803           return false;
2804         // We can't tell whether weak symbols will end up pointing to the same
2805         // object.
2806         if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
2807           return false;
2808         // Pointers with different bases cannot represent the same object.
2809         // (Note that clang defaults to -fmerge-all-constants, which can
2810         // lead to inconsistent results for comparisons involving the address
2811         // of a constant; this generally doesn't matter in practice.)
2812         return Success(E->getOpcode() == BO_NE, E);
2813       }
2814 
2815       // FIXME: Implement the C++11 restrictions:
2816       //  - Pointer subtractions must be on elements of the same array.
2817       //  - Pointer comparisons must be between members with the same access.
2818 
2819       if (E->getOpcode() == BO_Sub) {
2820         QualType Type = E->getLHS()->getType();
2821         QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
2822 
2823         CharUnits ElementSize;
2824         if (!HandleSizeof(Info, ElementType, ElementSize))
2825           return false;
2826 
2827         CharUnits Diff = LHSValue.getLValueOffset() -
2828                              RHSValue.getLValueOffset();
2829         return Success(Diff / ElementSize, E);
2830       }
2831 
2832       const CharUnits &LHSOffset = LHSValue.getLValueOffset();
2833       const CharUnits &RHSOffset = RHSValue.getLValueOffset();
2834       switch (E->getOpcode()) {
2835       default: llvm_unreachable("missing comparison operator");
2836       case BO_LT: return Success(LHSOffset < RHSOffset, E);
2837       case BO_GT: return Success(LHSOffset > RHSOffset, E);
2838       case BO_LE: return Success(LHSOffset <= RHSOffset, E);
2839       case BO_GE: return Success(LHSOffset >= RHSOffset, E);
2840       case BO_EQ: return Success(LHSOffset == RHSOffset, E);
2841       case BO_NE: return Success(LHSOffset != RHSOffset, E);
2842       }
2843     }
2844   }
2845   if (!LHSTy->isIntegralOrEnumerationType() ||
2846       !RHSTy->isIntegralOrEnumerationType()) {
2847     // We can't continue from here for non-integral types, and they
2848     // could potentially confuse the following operations.
2849     return false;
2850   }
2851 
2852   // The LHS of a constant expr is always evaluated and needed.
2853   CCValue LHSVal;
2854   if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
2855     return false; // error in subexpression.
2856 
2857   if (!Visit(E->getRHS()))
2858     return false;
2859   CCValue &RHSVal = Result;
2860 
2861   // Handle cases like (unsigned long)&a + 4.
2862   if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
2863     CharUnits AdditionalOffset = CharUnits::fromQuantity(
2864                                      RHSVal.getInt().getZExtValue());
2865     if (E->getOpcode() == BO_Add)
2866       LHSVal.getLValueOffset() += AdditionalOffset;
2867     else
2868       LHSVal.getLValueOffset() -= AdditionalOffset;
2869     Result = LHSVal;
2870     return true;
2871   }
2872 
2873   // Handle cases like 4 + (unsigned long)&a
2874   if (E->getOpcode() == BO_Add &&
2875         RHSVal.isLValue() && LHSVal.isInt()) {
2876     RHSVal.getLValueOffset() += CharUnits::fromQuantity(
2877                                     LHSVal.getInt().getZExtValue());
2878     // Note that RHSVal is Result.
2879     return true;
2880   }
2881 
2882   // All the following cases expect both operands to be an integer
2883   if (!LHSVal.isInt() || !RHSVal.isInt())
2884     return false;
2885 
2886   APSInt &LHS = LHSVal.getInt();
2887   APSInt &RHS = RHSVal.getInt();
2888 
2889   switch (E->getOpcode()) {
2890   default:
2891     return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
2892   case BO_Mul: return Success(LHS * RHS, E);
2893   case BO_Add: return Success(LHS + RHS, E);
2894   case BO_Sub: return Success(LHS - RHS, E);
2895   case BO_And: return Success(LHS & RHS, E);
2896   case BO_Xor: return Success(LHS ^ RHS, E);
2897   case BO_Or:  return Success(LHS | RHS, E);
2898   case BO_Div:
2899     if (RHS == 0)
2900       return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
2901     return Success(LHS / RHS, E);
2902   case BO_Rem:
2903     if (RHS == 0)
2904       return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
2905     return Success(LHS % RHS, E);
2906   case BO_Shl: {
2907     // During constant-folding, a negative shift is an opposite shift.
2908     if (RHS.isSigned() && RHS.isNegative()) {
2909       RHS = -RHS;
2910       goto shift_right;
2911     }
2912 
2913   shift_left:
2914     unsigned SA
2915       = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2916     return Success(LHS << SA, E);
2917   }
2918   case BO_Shr: {
2919     // During constant-folding, a negative shift is an opposite shift.
2920     if (RHS.isSigned() && RHS.isNegative()) {
2921       RHS = -RHS;
2922       goto shift_left;
2923     }
2924 
2925   shift_right:
2926     unsigned SA =
2927       (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2928     return Success(LHS >> SA, E);
2929   }
2930 
2931   case BO_LT: return Success(LHS < RHS, E);
2932   case BO_GT: return Success(LHS > RHS, E);
2933   case BO_LE: return Success(LHS <= RHS, E);
2934   case BO_GE: return Success(LHS >= RHS, E);
2935   case BO_EQ: return Success(LHS == RHS, E);
2936   case BO_NE: return Success(LHS != RHS, E);
2937   }
2938 }
2939 
2940 CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
2941   // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2942   //   the result is the size of the referenced type."
2943   // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
2944   //   result shall be the alignment of the referenced type."
2945   if (const ReferenceType *Ref = T->getAs<ReferenceType>())
2946     T = Ref->getPointeeType();
2947 
2948   // __alignof is defined to return the preferred alignment.
2949   return Info.Ctx.toCharUnitsFromBits(
2950     Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
2951 }
2952 
2953 CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
2954   E = E->IgnoreParens();
2955 
2956   // alignof decl is always accepted, even if it doesn't make sense: we default
2957   // to 1 in those cases.
2958   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2959     return Info.Ctx.getDeclAlign(DRE->getDecl(),
2960                                  /*RefAsPointee*/true);
2961 
2962   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
2963     return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
2964                                  /*RefAsPointee*/true);
2965 
2966   return GetAlignOfType(E->getType());
2967 }
2968 
2969 
2970 /// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
2971 /// a result as the expression's type.
2972 bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
2973                                     const UnaryExprOrTypeTraitExpr *E) {
2974   switch(E->getKind()) {
2975   case UETT_AlignOf: {
2976     if (E->isArgumentType())
2977       return Success(GetAlignOfType(E->getArgumentType()), E);
2978     else
2979       return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
2980   }
2981 
2982   case UETT_VecStep: {
2983     QualType Ty = E->getTypeOfArgument();
2984 
2985     if (Ty->isVectorType()) {
2986       unsigned n = Ty->getAs<VectorType>()->getNumElements();
2987 
2988       // The vec_step built-in functions that take a 3-component
2989       // vector return 4. (OpenCL 1.1 spec 6.11.12)
2990       if (n == 3)
2991         n = 4;
2992 
2993       return Success(n, E);
2994     } else
2995       return Success(1, E);
2996   }
2997 
2998   case UETT_SizeOf: {
2999     QualType SrcTy = E->getTypeOfArgument();
3000     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
3001     //   the result is the size of the referenced type."
3002     // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
3003     //   result shall be the alignment of the referenced type."
3004     if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
3005       SrcTy = Ref->getPointeeType();
3006 
3007     CharUnits Sizeof;
3008     if (!HandleSizeof(Info, SrcTy, Sizeof))
3009       return false;
3010     return Success(Sizeof, E);
3011   }
3012   }
3013 
3014   llvm_unreachable("unknown expr/type trait");
3015   return false;
3016 }
3017 
3018 bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
3019   CharUnits Result;
3020   unsigned n = OOE->getNumComponents();
3021   if (n == 0)
3022     return false;
3023   QualType CurrentType = OOE->getTypeSourceInfo()->getType();
3024   for (unsigned i = 0; i != n; ++i) {
3025     OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
3026     switch (ON.getKind()) {
3027     case OffsetOfExpr::OffsetOfNode::Array: {
3028       const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
3029       APSInt IdxResult;
3030       if (!EvaluateInteger(Idx, IdxResult, Info))
3031         return false;
3032       const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
3033       if (!AT)
3034         return false;
3035       CurrentType = AT->getElementType();
3036       CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
3037       Result += IdxResult.getSExtValue() * ElementSize;
3038         break;
3039     }
3040 
3041     case OffsetOfExpr::OffsetOfNode::Field: {
3042       FieldDecl *MemberDecl = ON.getField();
3043       const RecordType *RT = CurrentType->getAs<RecordType>();
3044       if (!RT)
3045         return false;
3046       RecordDecl *RD = RT->getDecl();
3047       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3048       unsigned i = MemberDecl->getFieldIndex();
3049       assert(i < RL.getFieldCount() && "offsetof field in wrong type");
3050       Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
3051       CurrentType = MemberDecl->getType().getNonReferenceType();
3052       break;
3053     }
3054 
3055     case OffsetOfExpr::OffsetOfNode::Identifier:
3056       llvm_unreachable("dependent __builtin_offsetof");
3057       return false;
3058 
3059     case OffsetOfExpr::OffsetOfNode::Base: {
3060       CXXBaseSpecifier *BaseSpec = ON.getBase();
3061       if (BaseSpec->isVirtual())
3062         return false;
3063 
3064       // Find the layout of the class whose base we are looking into.
3065       const RecordType *RT = CurrentType->getAs<RecordType>();
3066       if (!RT)
3067         return false;
3068       RecordDecl *RD = RT->getDecl();
3069       const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
3070 
3071       // Find the base class itself.
3072       CurrentType = BaseSpec->getType();
3073       const RecordType *BaseRT = CurrentType->getAs<RecordType>();
3074       if (!BaseRT)
3075         return false;
3076 
3077       // Add the offset to the base.
3078       Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
3079       break;
3080     }
3081     }
3082   }
3083   return Success(Result, OOE);
3084 }
3085 
3086 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3087   if (E->getOpcode() == UO_LNot) {
3088     // LNot's operand isn't necessarily an integer, so we handle it specially.
3089     bool bres;
3090     if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
3091       return false;
3092     return Success(!bres, E);
3093   }
3094 
3095   // Only handle integral operations...
3096   if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
3097     return false;
3098 
3099   // Get the operand value.
3100   CCValue Val;
3101   if (!Evaluate(Val, Info, E->getSubExpr()))
3102     return false;
3103 
3104   switch (E->getOpcode()) {
3105   default:
3106     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
3107     // See C99 6.6p3.
3108     return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
3109   case UO_Extension:
3110     // FIXME: Should extension allow i-c-e extension expressions in its scope?
3111     // If so, we could clear the diagnostic ID.
3112     return Success(Val, E);
3113   case UO_Plus:
3114     // The result is just the value.
3115     return Success(Val, E);
3116   case UO_Minus:
3117     if (!Val.isInt()) return false;
3118     return Success(-Val.getInt(), E);
3119   case UO_Not:
3120     if (!Val.isInt()) return false;
3121     return Success(~Val.getInt(), E);
3122   }
3123 }
3124 
3125 /// HandleCast - This is used to evaluate implicit or explicit casts where the
3126 /// result type is integer.
3127 bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
3128   const Expr *SubExpr = E->getSubExpr();
3129   QualType DestType = E->getType();
3130   QualType SrcType = SubExpr->getType();
3131 
3132   switch (E->getCastKind()) {
3133   case CK_BaseToDerived:
3134   case CK_DerivedToBase:
3135   case CK_UncheckedDerivedToBase:
3136   case CK_Dynamic:
3137   case CK_ToUnion:
3138   case CK_ArrayToPointerDecay:
3139   case CK_FunctionToPointerDecay:
3140   case CK_NullToPointer:
3141   case CK_NullToMemberPointer:
3142   case CK_BaseToDerivedMemberPointer:
3143   case CK_DerivedToBaseMemberPointer:
3144   case CK_ConstructorConversion:
3145   case CK_IntegralToPointer:
3146   case CK_ToVoid:
3147   case CK_VectorSplat:
3148   case CK_IntegralToFloating:
3149   case CK_FloatingCast:
3150   case CK_CPointerToObjCPointerCast:
3151   case CK_BlockPointerToObjCPointerCast:
3152   case CK_AnyPointerToBlockPointerCast:
3153   case CK_ObjCObjectLValueCast:
3154   case CK_FloatingRealToComplex:
3155   case CK_FloatingComplexToReal:
3156   case CK_FloatingComplexCast:
3157   case CK_FloatingComplexToIntegralComplex:
3158   case CK_IntegralRealToComplex:
3159   case CK_IntegralComplexCast:
3160   case CK_IntegralComplexToFloatingComplex:
3161     llvm_unreachable("invalid cast kind for integral value");
3162 
3163   case CK_BitCast:
3164   case CK_Dependent:
3165   case CK_LValueBitCast:
3166   case CK_UserDefinedConversion:
3167   case CK_ARCProduceObject:
3168   case CK_ARCConsumeObject:
3169   case CK_ARCReclaimReturnedObject:
3170   case CK_ARCExtendBlockObject:
3171     return false;
3172 
3173   case CK_LValueToRValue:
3174   case CK_NoOp:
3175     return ExprEvaluatorBaseTy::VisitCastExpr(E);
3176 
3177   case CK_MemberPointerToBoolean:
3178   case CK_PointerToBoolean:
3179   case CK_IntegralToBoolean:
3180   case CK_FloatingToBoolean:
3181   case CK_FloatingComplexToBoolean:
3182   case CK_IntegralComplexToBoolean: {
3183     bool BoolResult;
3184     if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
3185       return false;
3186     return Success(BoolResult, E);
3187   }
3188 
3189   case CK_IntegralCast: {
3190     if (!Visit(SubExpr))
3191       return false;
3192 
3193     if (!Result.isInt()) {
3194       // Only allow casts of lvalues if they are lossless.
3195       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
3196     }
3197 
3198     return Success(HandleIntToIntCast(DestType, SrcType,
3199                                       Result.getInt(), Info.Ctx), E);
3200   }
3201 
3202   case CK_PointerToIntegral: {
3203     LValue LV;
3204     if (!EvaluatePointer(SubExpr, LV, Info))
3205       return false;
3206 
3207     if (LV.getLValueBase()) {
3208       // Only allow based lvalue casts if they are lossless.
3209       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
3210         return false;
3211 
3212       LV.moveInto(Result);
3213       return true;
3214     }
3215 
3216     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
3217                                          SrcType);
3218     return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
3219   }
3220 
3221   case CK_IntegralComplexToReal: {
3222     ComplexValue C;
3223     if (!EvaluateComplex(SubExpr, C, Info))
3224       return false;
3225     return Success(C.getComplexIntReal(), E);
3226   }
3227 
3228   case CK_FloatingToIntegral: {
3229     APFloat F(0.0);
3230     if (!EvaluateFloat(SubExpr, F, Info))
3231       return false;
3232 
3233     return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
3234   }
3235   }
3236 
3237   llvm_unreachable("unknown cast resulting in integral value");
3238   return false;
3239 }
3240 
3241 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3242   if (E->getSubExpr()->getType()->isAnyComplexType()) {
3243     ComplexValue LV;
3244     if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3245       return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3246     return Success(LV.getComplexIntReal(), E);
3247   }
3248 
3249   return Visit(E->getSubExpr());
3250 }
3251 
3252 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3253   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
3254     ComplexValue LV;
3255     if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
3256       return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
3257     return Success(LV.getComplexIntImag(), E);
3258   }
3259 
3260   VisitIgnoredValue(E->getSubExpr());
3261   return Success(0, E);
3262 }
3263 
3264 bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3265   return Success(E->getPackLength(), E);
3266 }
3267 
3268 bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
3269   return Success(E->getValue(), E);
3270 }
3271 
3272 //===----------------------------------------------------------------------===//
3273 // Float Evaluation
3274 //===----------------------------------------------------------------------===//
3275 
3276 namespace {
3277 class FloatExprEvaluator
3278   : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
3279   APFloat &Result;
3280 public:
3281   FloatExprEvaluator(EvalInfo &info, APFloat &result)
3282     : ExprEvaluatorBaseTy(info), Result(result) {}
3283 
3284   bool Success(const CCValue &V, const Expr *e) {
3285     Result = V.getFloat();
3286     return true;
3287   }
3288   bool Error(const Stmt *S) {
3289     return false;
3290   }
3291 
3292   bool ValueInitialization(const Expr *E) {
3293     Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
3294     return true;
3295   }
3296 
3297   bool VisitCallExpr(const CallExpr *E);
3298 
3299   bool VisitUnaryOperator(const UnaryOperator *E);
3300   bool VisitBinaryOperator(const BinaryOperator *E);
3301   bool VisitFloatingLiteral(const FloatingLiteral *E);
3302   bool VisitCastExpr(const CastExpr *E);
3303 
3304   bool VisitUnaryReal(const UnaryOperator *E);
3305   bool VisitUnaryImag(const UnaryOperator *E);
3306 
3307   // FIXME: Missing: array subscript of vector, member of vector,
3308   //                 ImplicitValueInitExpr
3309 };
3310 } // end anonymous namespace
3311 
3312 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
3313   assert(E->isRValue() && E->getType()->isRealFloatingType());
3314   return FloatExprEvaluator(Info, Result).Visit(E);
3315 }
3316 
3317 static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
3318                                   QualType ResultTy,
3319                                   const Expr *Arg,
3320                                   bool SNaN,
3321                                   llvm::APFloat &Result) {
3322   const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
3323   if (!S) return false;
3324 
3325   const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
3326 
3327   llvm::APInt fill;
3328 
3329   // Treat empty strings as if they were zero.
3330   if (S->getString().empty())
3331     fill = llvm::APInt(32, 0);
3332   else if (S->getString().getAsInteger(0, fill))
3333     return false;
3334 
3335   if (SNaN)
3336     Result = llvm::APFloat::getSNaN(Sem, false, &fill);
3337   else
3338     Result = llvm::APFloat::getQNaN(Sem, false, &fill);
3339   return true;
3340 }
3341 
3342 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
3343   switch (E->isBuiltinCall()) {
3344   default:
3345     return ExprEvaluatorBaseTy::VisitCallExpr(E);
3346 
3347   case Builtin::BI__builtin_huge_val:
3348   case Builtin::BI__builtin_huge_valf:
3349   case Builtin::BI__builtin_huge_vall:
3350   case Builtin::BI__builtin_inf:
3351   case Builtin::BI__builtin_inff:
3352   case Builtin::BI__builtin_infl: {
3353     const llvm::fltSemantics &Sem =
3354       Info.Ctx.getFloatTypeSemantics(E->getType());
3355     Result = llvm::APFloat::getInf(Sem);
3356     return true;
3357   }
3358 
3359   case Builtin::BI__builtin_nans:
3360   case Builtin::BI__builtin_nansf:
3361   case Builtin::BI__builtin_nansl:
3362     return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3363                                  true, Result);
3364 
3365   case Builtin::BI__builtin_nan:
3366   case Builtin::BI__builtin_nanf:
3367   case Builtin::BI__builtin_nanl:
3368     // If this is __builtin_nan() turn this into a nan, otherwise we
3369     // can't constant fold it.
3370     return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
3371                                  false, Result);
3372 
3373   case Builtin::BI__builtin_fabs:
3374   case Builtin::BI__builtin_fabsf:
3375   case Builtin::BI__builtin_fabsl:
3376     if (!EvaluateFloat(E->getArg(0), Result, Info))
3377       return false;
3378 
3379     if (Result.isNegative())
3380       Result.changeSign();
3381     return true;
3382 
3383   case Builtin::BI__builtin_copysign:
3384   case Builtin::BI__builtin_copysignf:
3385   case Builtin::BI__builtin_copysignl: {
3386     APFloat RHS(0.);
3387     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
3388         !EvaluateFloat(E->getArg(1), RHS, Info))
3389       return false;
3390     Result.copySign(RHS);
3391     return true;
3392   }
3393   }
3394 }
3395 
3396 bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3397   if (E->getSubExpr()->getType()->isAnyComplexType()) {
3398     ComplexValue CV;
3399     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3400       return false;
3401     Result = CV.FloatReal;
3402     return true;
3403   }
3404 
3405   return Visit(E->getSubExpr());
3406 }
3407 
3408 bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3409   if (E->getSubExpr()->getType()->isAnyComplexType()) {
3410     ComplexValue CV;
3411     if (!EvaluateComplex(E->getSubExpr(), CV, Info))
3412       return false;
3413     Result = CV.FloatImag;
3414     return true;
3415   }
3416 
3417   VisitIgnoredValue(E->getSubExpr());
3418   const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
3419   Result = llvm::APFloat::getZero(Sem);
3420   return true;
3421 }
3422 
3423 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3424   switch (E->getOpcode()) {
3425   default: return false;
3426   case UO_Plus:
3427     return EvaluateFloat(E->getSubExpr(), Result, Info);
3428   case UO_Minus:
3429     if (!EvaluateFloat(E->getSubExpr(), Result, Info))
3430       return false;
3431     Result.changeSign();
3432     return true;
3433   }
3434 }
3435 
3436 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
3437   if (E->getOpcode() == BO_Comma) {
3438     VisitIgnoredValue(E->getLHS());
3439     return Visit(E->getRHS());
3440   }
3441 
3442   // We can't evaluate pointer-to-member operations or assignments.
3443   if (E->isPtrMemOp() || E->isAssignmentOp())
3444     return false;
3445 
3446   // FIXME: Diagnostics?  I really don't understand how the warnings
3447   // and errors are supposed to work.
3448   APFloat RHS(0.0);
3449   if (!EvaluateFloat(E->getLHS(), Result, Info))
3450     return false;
3451   if (!EvaluateFloat(E->getRHS(), RHS, Info))
3452     return false;
3453 
3454   switch (E->getOpcode()) {
3455   default: return false;
3456   case BO_Mul:
3457     Result.multiply(RHS, APFloat::rmNearestTiesToEven);
3458     return true;
3459   case BO_Add:
3460     Result.add(RHS, APFloat::rmNearestTiesToEven);
3461     return true;
3462   case BO_Sub:
3463     Result.subtract(RHS, APFloat::rmNearestTiesToEven);
3464     return true;
3465   case BO_Div:
3466     Result.divide(RHS, APFloat::rmNearestTiesToEven);
3467     return true;
3468   }
3469 }
3470 
3471 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
3472   Result = E->getValue();
3473   return true;
3474 }
3475 
3476 bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
3477   const Expr* SubExpr = E->getSubExpr();
3478 
3479   switch (E->getCastKind()) {
3480   default:
3481     return ExprEvaluatorBaseTy::VisitCastExpr(E);
3482 
3483   case CK_IntegralToFloating: {
3484     APSInt IntResult;
3485     if (!EvaluateInteger(SubExpr, IntResult, Info))
3486       return false;
3487     Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
3488                                   IntResult, Info.Ctx);
3489     return true;
3490   }
3491 
3492   case CK_FloatingCast: {
3493     if (!Visit(SubExpr))
3494       return false;
3495     Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
3496                                     Result, Info.Ctx);
3497     return true;
3498   }
3499 
3500   case CK_FloatingComplexToReal: {
3501     ComplexValue V;
3502     if (!EvaluateComplex(SubExpr, V, Info))
3503       return false;
3504     Result = V.getComplexFloatReal();
3505     return true;
3506   }
3507   }
3508 
3509   return false;
3510 }
3511 
3512 //===----------------------------------------------------------------------===//
3513 // Complex Evaluation (for float and integer)
3514 //===----------------------------------------------------------------------===//
3515 
3516 namespace {
3517 class ComplexExprEvaluator
3518   : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
3519   ComplexValue &Result;
3520 
3521 public:
3522   ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
3523     : ExprEvaluatorBaseTy(info), Result(Result) {}
3524 
3525   bool Success(const CCValue &V, const Expr *e) {
3526     Result.setFrom(V);
3527     return true;
3528   }
3529   bool Error(const Expr *E) {
3530     return false;
3531   }
3532 
3533   //===--------------------------------------------------------------------===//
3534   //                            Visitor Methods
3535   //===--------------------------------------------------------------------===//
3536 
3537   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
3538 
3539   bool VisitCastExpr(const CastExpr *E);
3540 
3541   bool VisitBinaryOperator(const BinaryOperator *E);
3542   bool VisitUnaryOperator(const UnaryOperator *E);
3543   // FIXME Missing: ImplicitValueInitExpr, InitListExpr
3544 };
3545 } // end anonymous namespace
3546 
3547 static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
3548                             EvalInfo &Info) {
3549   assert(E->isRValue() && E->getType()->isAnyComplexType());
3550   return ComplexExprEvaluator(Info, Result).Visit(E);
3551 }
3552 
3553 bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
3554   const Expr* SubExpr = E->getSubExpr();
3555 
3556   if (SubExpr->getType()->isRealFloatingType()) {
3557     Result.makeComplexFloat();
3558     APFloat &Imag = Result.FloatImag;
3559     if (!EvaluateFloat(SubExpr, Imag, Info))
3560       return false;
3561 
3562     Result.FloatReal = APFloat(Imag.getSemantics());
3563     return true;
3564   } else {
3565     assert(SubExpr->getType()->isIntegerType() &&
3566            "Unexpected imaginary literal.");
3567 
3568     Result.makeComplexInt();
3569     APSInt &Imag = Result.IntImag;
3570     if (!EvaluateInteger(SubExpr, Imag, Info))
3571       return false;
3572 
3573     Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
3574     return true;
3575   }
3576 }
3577 
3578 bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
3579 
3580   switch (E->getCastKind()) {
3581   case CK_BitCast:
3582   case CK_BaseToDerived:
3583   case CK_DerivedToBase:
3584   case CK_UncheckedDerivedToBase:
3585   case CK_Dynamic:
3586   case CK_ToUnion:
3587   case CK_ArrayToPointerDecay:
3588   case CK_FunctionToPointerDecay:
3589   case CK_NullToPointer:
3590   case CK_NullToMemberPointer:
3591   case CK_BaseToDerivedMemberPointer:
3592   case CK_DerivedToBaseMemberPointer:
3593   case CK_MemberPointerToBoolean:
3594   case CK_ConstructorConversion:
3595   case CK_IntegralToPointer:
3596   case CK_PointerToIntegral:
3597   case CK_PointerToBoolean:
3598   case CK_ToVoid:
3599   case CK_VectorSplat:
3600   case CK_IntegralCast:
3601   case CK_IntegralToBoolean:
3602   case CK_IntegralToFloating:
3603   case CK_FloatingToIntegral:
3604   case CK_FloatingToBoolean:
3605   case CK_FloatingCast:
3606   case CK_CPointerToObjCPointerCast:
3607   case CK_BlockPointerToObjCPointerCast:
3608   case CK_AnyPointerToBlockPointerCast:
3609   case CK_ObjCObjectLValueCast:
3610   case CK_FloatingComplexToReal:
3611   case CK_FloatingComplexToBoolean:
3612   case CK_IntegralComplexToReal:
3613   case CK_IntegralComplexToBoolean:
3614   case CK_ARCProduceObject:
3615   case CK_ARCConsumeObject:
3616   case CK_ARCReclaimReturnedObject:
3617   case CK_ARCExtendBlockObject:
3618     llvm_unreachable("invalid cast kind for complex value");
3619 
3620   case CK_LValueToRValue:
3621   case CK_NoOp:
3622     return ExprEvaluatorBaseTy::VisitCastExpr(E);
3623 
3624   case CK_Dependent:
3625   case CK_LValueBitCast:
3626   case CK_UserDefinedConversion:
3627     return false;
3628 
3629   case CK_FloatingRealToComplex: {
3630     APFloat &Real = Result.FloatReal;
3631     if (!EvaluateFloat(E->getSubExpr(), Real, Info))
3632       return false;
3633 
3634     Result.makeComplexFloat();
3635     Result.FloatImag = APFloat(Real.getSemantics());
3636     return true;
3637   }
3638 
3639   case CK_FloatingComplexCast: {
3640     if (!Visit(E->getSubExpr()))
3641       return false;
3642 
3643     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3644     QualType From
3645       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3646 
3647     Result.FloatReal
3648       = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
3649     Result.FloatImag
3650       = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
3651     return true;
3652   }
3653 
3654   case CK_FloatingComplexToIntegralComplex: {
3655     if (!Visit(E->getSubExpr()))
3656       return false;
3657 
3658     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3659     QualType From
3660       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3661     Result.makeComplexInt();
3662     Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
3663     Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
3664     return true;
3665   }
3666 
3667   case CK_IntegralRealToComplex: {
3668     APSInt &Real = Result.IntReal;
3669     if (!EvaluateInteger(E->getSubExpr(), Real, Info))
3670       return false;
3671 
3672     Result.makeComplexInt();
3673     Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
3674     return true;
3675   }
3676 
3677   case CK_IntegralComplexCast: {
3678     if (!Visit(E->getSubExpr()))
3679       return false;
3680 
3681     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3682     QualType From
3683       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3684 
3685     Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
3686     Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
3687     return true;
3688   }
3689 
3690   case CK_IntegralComplexToFloatingComplex: {
3691     if (!Visit(E->getSubExpr()))
3692       return false;
3693 
3694     QualType To = E->getType()->getAs<ComplexType>()->getElementType();
3695     QualType From
3696       = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
3697     Result.makeComplexFloat();
3698     Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
3699     Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
3700     return true;
3701   }
3702   }
3703 
3704   llvm_unreachable("unknown cast resulting in complex value");
3705   return false;
3706 }
3707 
3708 bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
3709   if (E->getOpcode() == BO_Comma) {
3710     VisitIgnoredValue(E->getLHS());
3711     return Visit(E->getRHS());
3712   }
3713   if (!Visit(E->getLHS()))
3714     return false;
3715 
3716   ComplexValue RHS;
3717   if (!EvaluateComplex(E->getRHS(), RHS, Info))
3718     return false;
3719 
3720   assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
3721          "Invalid operands to binary operator.");
3722   switch (E->getOpcode()) {
3723   default: return false;
3724   case BO_Add:
3725     if (Result.isComplexFloat()) {
3726       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
3727                                        APFloat::rmNearestTiesToEven);
3728       Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
3729                                        APFloat::rmNearestTiesToEven);
3730     } else {
3731       Result.getComplexIntReal() += RHS.getComplexIntReal();
3732       Result.getComplexIntImag() += RHS.getComplexIntImag();
3733     }
3734     break;
3735   case BO_Sub:
3736     if (Result.isComplexFloat()) {
3737       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
3738                                             APFloat::rmNearestTiesToEven);
3739       Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
3740                                             APFloat::rmNearestTiesToEven);
3741     } else {
3742       Result.getComplexIntReal() -= RHS.getComplexIntReal();
3743       Result.getComplexIntImag() -= RHS.getComplexIntImag();
3744     }
3745     break;
3746   case BO_Mul:
3747     if (Result.isComplexFloat()) {
3748       ComplexValue LHS = Result;
3749       APFloat &LHS_r = LHS.getComplexFloatReal();
3750       APFloat &LHS_i = LHS.getComplexFloatImag();
3751       APFloat &RHS_r = RHS.getComplexFloatReal();
3752       APFloat &RHS_i = RHS.getComplexFloatImag();
3753 
3754       APFloat Tmp = LHS_r;
3755       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3756       Result.getComplexFloatReal() = Tmp;
3757       Tmp = LHS_i;
3758       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3759       Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
3760 
3761       Tmp = LHS_r;
3762       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3763       Result.getComplexFloatImag() = Tmp;
3764       Tmp = LHS_i;
3765       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3766       Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
3767     } else {
3768       ComplexValue LHS = Result;
3769       Result.getComplexIntReal() =
3770         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
3771          LHS.getComplexIntImag() * RHS.getComplexIntImag());
3772       Result.getComplexIntImag() =
3773         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
3774          LHS.getComplexIntImag() * RHS.getComplexIntReal());
3775     }
3776     break;
3777   case BO_Div:
3778     if (Result.isComplexFloat()) {
3779       ComplexValue LHS = Result;
3780       APFloat &LHS_r = LHS.getComplexFloatReal();
3781       APFloat &LHS_i = LHS.getComplexFloatImag();
3782       APFloat &RHS_r = RHS.getComplexFloatReal();
3783       APFloat &RHS_i = RHS.getComplexFloatImag();
3784       APFloat &Res_r = Result.getComplexFloatReal();
3785       APFloat &Res_i = Result.getComplexFloatImag();
3786 
3787       APFloat Den = RHS_r;
3788       Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3789       APFloat Tmp = RHS_i;
3790       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3791       Den.add(Tmp, APFloat::rmNearestTiesToEven);
3792 
3793       Res_r = LHS_r;
3794       Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3795       Tmp = LHS_i;
3796       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3797       Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
3798       Res_r.divide(Den, APFloat::rmNearestTiesToEven);
3799 
3800       Res_i = LHS_i;
3801       Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
3802       Tmp = LHS_r;
3803       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
3804       Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
3805       Res_i.divide(Den, APFloat::rmNearestTiesToEven);
3806     } else {
3807       if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
3808         // FIXME: what about diagnostics?
3809         return false;
3810       }
3811       ComplexValue LHS = Result;
3812       APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
3813         RHS.getComplexIntImag() * RHS.getComplexIntImag();
3814       Result.getComplexIntReal() =
3815         (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
3816          LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
3817       Result.getComplexIntImag() =
3818         (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
3819          LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
3820     }
3821     break;
3822   }
3823 
3824   return true;
3825 }
3826 
3827 bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
3828   // Get the operand value into 'Result'.
3829   if (!Visit(E->getSubExpr()))
3830     return false;
3831 
3832   switch (E->getOpcode()) {
3833   default:
3834     // FIXME: what about diagnostics?
3835     return false;
3836   case UO_Extension:
3837     return true;
3838   case UO_Plus:
3839     // The result is always just the subexpr.
3840     return true;
3841   case UO_Minus:
3842     if (Result.isComplexFloat()) {
3843       Result.getComplexFloatReal().changeSign();
3844       Result.getComplexFloatImag().changeSign();
3845     }
3846     else {
3847       Result.getComplexIntReal() = -Result.getComplexIntReal();
3848       Result.getComplexIntImag() = -Result.getComplexIntImag();
3849     }
3850     return true;
3851   case UO_Not:
3852     if (Result.isComplexFloat())
3853       Result.getComplexFloatImag().changeSign();
3854     else
3855       Result.getComplexIntImag() = -Result.getComplexIntImag();
3856     return true;
3857   }
3858 }
3859 
3860 //===----------------------------------------------------------------------===//
3861 // Top level Expr::EvaluateAsRValue method.
3862 //===----------------------------------------------------------------------===//
3863 
3864 static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
3865   // In C, function designators are not lvalues, but we evaluate them as if they
3866   // are.
3867   if (E->isGLValue() || E->getType()->isFunctionType()) {
3868     LValue LV;
3869     if (!EvaluateLValue(E, LV, Info))
3870       return false;
3871     LV.moveInto(Result);
3872   } else if (E->getType()->isVectorType()) {
3873     if (!EvaluateVector(E, Result, Info))
3874       return false;
3875   } else if (E->getType()->isIntegralOrEnumerationType()) {
3876     if (!IntExprEvaluator(Info, Result).Visit(E))
3877       return false;
3878   } else if (E->getType()->hasPointerRepresentation()) {
3879     LValue LV;
3880     if (!EvaluatePointer(E, LV, Info))
3881       return false;
3882     LV.moveInto(Result);
3883   } else if (E->getType()->isRealFloatingType()) {
3884     llvm::APFloat F(0.0);
3885     if (!EvaluateFloat(E, F, Info))
3886       return false;
3887     Result = CCValue(F);
3888   } else if (E->getType()->isAnyComplexType()) {
3889     ComplexValue C;
3890     if (!EvaluateComplex(E, C, Info))
3891       return false;
3892     C.moveInto(Result);
3893   } else if (E->getType()->isMemberPointerType()) {
3894     // FIXME: Implement evaluation of pointer-to-member types.
3895     return false;
3896   } else if (E->getType()->isArrayType() && E->getType()->isLiteralType()) {
3897     LValue LV;
3898     LV.setExpr(E, Info.CurrentCall);
3899     if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
3900       return false;
3901     Result = Info.CurrentCall->Temporaries[E];
3902   } else if (E->getType()->isRecordType() && E->getType()->isLiteralType()) {
3903     LValue LV;
3904     LV.setExpr(E, Info.CurrentCall);
3905     if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
3906       return false;
3907     Result = Info.CurrentCall->Temporaries[E];
3908   } else
3909     return false;
3910 
3911   return true;
3912 }
3913 
3914 /// EvaluateConstantExpression - Evaluate an expression as a constant expression
3915 /// in-place in an APValue. In some cases, the in-place evaluation is essential,
3916 /// since later initializers for an object can indirectly refer to subobjects
3917 /// which were initialized earlier.
3918 static bool EvaluateConstantExpression(APValue &Result, EvalInfo &Info,
3919                                        const LValue &This, const Expr *E) {
3920   if (E->isRValue() && E->getType()->isLiteralType()) {
3921     // Evaluate arrays and record types in-place, so that later initializers can
3922     // refer to earlier-initialized members of the object.
3923     if (E->getType()->isArrayType())
3924       return EvaluateArray(E, This, Result, Info);
3925     else if (E->getType()->isRecordType())
3926       return EvaluateRecord(E, This, Result, Info);
3927   }
3928 
3929   // For any other type, in-place evaluation is unimportant.
3930   CCValue CoreConstResult;
3931   return Evaluate(CoreConstResult, Info, E) &&
3932          CheckConstantExpression(CoreConstResult, Result);
3933 }
3934 
3935 
3936 /// EvaluateAsRValue - Return true if this is a constant which we can fold using
3937 /// any crazy technique (that has nothing to do with language standards) that
3938 /// we want to.  If this function returns true, it returns the folded constant
3939 /// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
3940 /// will be applied to the result.
3941 bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
3942   // FIXME: Evaluating initializers for large arrays can cause performance
3943   // problems, and we don't use such values yet. Once we have a more efficient
3944   // array representation, this should be reinstated, and used by CodeGen.
3945   if (isRValue() && getType()->isArrayType())
3946     return false;
3947 
3948   EvalInfo Info(Ctx, Result);
3949 
3950   // FIXME: If this is the initializer for an lvalue, pass that in.
3951   CCValue Value;
3952   if (!::Evaluate(Value, Info, this))
3953     return false;
3954 
3955   if (isGLValue()) {
3956     LValue LV;
3957     LV.setFrom(Value);
3958     if (!HandleLValueToRValueConversion(Info, getType(), LV, Value))
3959       return false;
3960   }
3961 
3962   // Check this core constant expression is a constant expression, and if so,
3963   // convert it to one.
3964   return CheckConstantExpression(Value, Result.Val);
3965 }
3966 
3967 bool Expr::EvaluateAsBooleanCondition(bool &Result,
3968                                       const ASTContext &Ctx) const {
3969   EvalResult Scratch;
3970   return EvaluateAsRValue(Scratch, Ctx) &&
3971          HandleConversionToBool(CCValue(Scratch.Val, CCValue::GlobalValue()),
3972                                 Result);
3973 }
3974 
3975 bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
3976   EvalResult ExprResult;
3977   if (!EvaluateAsRValue(ExprResult, Ctx) || ExprResult.HasSideEffects ||
3978       !ExprResult.Val.isInt()) {
3979     return false;
3980   }
3981   Result = ExprResult.Val.getInt();
3982   return true;
3983 }
3984 
3985 bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
3986   EvalInfo Info(Ctx, Result);
3987 
3988   LValue LV;
3989   return EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
3990          CheckLValueConstantExpression(LV, Result.Val);
3991 }
3992 
3993 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
3994 /// constant folded, but discard the result.
3995 bool Expr::isEvaluatable(const ASTContext &Ctx) const {
3996   EvalResult Result;
3997   return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
3998 }
3999 
4000 bool Expr::HasSideEffects(const ASTContext &Ctx) const {
4001   return HasSideEffect(Ctx).Visit(this);
4002 }
4003 
4004 APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
4005   EvalResult EvalResult;
4006   bool Result = EvaluateAsRValue(EvalResult, Ctx);
4007   (void)Result;
4008   assert(Result && "Could not evaluate expression");
4009   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
4010 
4011   return EvalResult.Val.getInt();
4012 }
4013 
4014  bool Expr::EvalResult::isGlobalLValue() const {
4015    assert(Val.isLValue());
4016    return IsGlobalLValue(Val.getLValueBase());
4017  }
4018 
4019 
4020 /// isIntegerConstantExpr - this recursive routine will test if an expression is
4021 /// an integer constant expression.
4022 
4023 /// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
4024 /// comma, etc
4025 ///
4026 /// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
4027 /// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
4028 /// cast+dereference.
4029 
4030 // CheckICE - This function does the fundamental ICE checking: the returned
4031 // ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
4032 // Note that to reduce code duplication, this helper does no evaluation
4033 // itself; the caller checks whether the expression is evaluatable, and
4034 // in the rare cases where CheckICE actually cares about the evaluated
4035 // value, it calls into Evalute.
4036 //
4037 // Meanings of Val:
4038 // 0: This expression is an ICE.
4039 // 1: This expression is not an ICE, but if it isn't evaluated, it's
4040 //    a legal subexpression for an ICE. This return value is used to handle
4041 //    the comma operator in C99 mode.
4042 // 2: This expression is not an ICE, and is not a legal subexpression for one.
4043 
4044 namespace {
4045 
4046 struct ICEDiag {
4047   unsigned Val;
4048   SourceLocation Loc;
4049 
4050   public:
4051   ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
4052   ICEDiag() : Val(0) {}
4053 };
4054 
4055 }
4056 
4057 static ICEDiag NoDiag() { return ICEDiag(); }
4058 
4059 static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
4060   Expr::EvalResult EVResult;
4061   if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
4062       !EVResult.Val.isInt()) {
4063     return ICEDiag(2, E->getLocStart());
4064   }
4065   return NoDiag();
4066 }
4067 
4068 static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
4069   assert(!E->isValueDependent() && "Should not see value dependent exprs!");
4070   if (!E->getType()->isIntegralOrEnumerationType()) {
4071     return ICEDiag(2, E->getLocStart());
4072   }
4073 
4074   switch (E->getStmtClass()) {
4075 #define ABSTRACT_STMT(Node)
4076 #define STMT(Node, Base) case Expr::Node##Class:
4077 #define EXPR(Node, Base)
4078 #include "clang/AST/StmtNodes.inc"
4079   case Expr::PredefinedExprClass:
4080   case Expr::FloatingLiteralClass:
4081   case Expr::ImaginaryLiteralClass:
4082   case Expr::StringLiteralClass:
4083   case Expr::ArraySubscriptExprClass:
4084   case Expr::MemberExprClass:
4085   case Expr::CompoundAssignOperatorClass:
4086   case Expr::CompoundLiteralExprClass:
4087   case Expr::ExtVectorElementExprClass:
4088   case Expr::DesignatedInitExprClass:
4089   case Expr::ImplicitValueInitExprClass:
4090   case Expr::ParenListExprClass:
4091   case Expr::VAArgExprClass:
4092   case Expr::AddrLabelExprClass:
4093   case Expr::StmtExprClass:
4094   case Expr::CXXMemberCallExprClass:
4095   case Expr::CUDAKernelCallExprClass:
4096   case Expr::CXXDynamicCastExprClass:
4097   case Expr::CXXTypeidExprClass:
4098   case Expr::CXXUuidofExprClass:
4099   case Expr::CXXNullPtrLiteralExprClass:
4100   case Expr::CXXThisExprClass:
4101   case Expr::CXXThrowExprClass:
4102   case Expr::CXXNewExprClass:
4103   case Expr::CXXDeleteExprClass:
4104   case Expr::CXXPseudoDestructorExprClass:
4105   case Expr::UnresolvedLookupExprClass:
4106   case Expr::DependentScopeDeclRefExprClass:
4107   case Expr::CXXConstructExprClass:
4108   case Expr::CXXBindTemporaryExprClass:
4109   case Expr::ExprWithCleanupsClass:
4110   case Expr::CXXTemporaryObjectExprClass:
4111   case Expr::CXXUnresolvedConstructExprClass:
4112   case Expr::CXXDependentScopeMemberExprClass:
4113   case Expr::UnresolvedMemberExprClass:
4114   case Expr::ObjCStringLiteralClass:
4115   case Expr::ObjCEncodeExprClass:
4116   case Expr::ObjCMessageExprClass:
4117   case Expr::ObjCSelectorExprClass:
4118   case Expr::ObjCProtocolExprClass:
4119   case Expr::ObjCIvarRefExprClass:
4120   case Expr::ObjCPropertyRefExprClass:
4121   case Expr::ObjCIsaExprClass:
4122   case Expr::ShuffleVectorExprClass:
4123   case Expr::BlockExprClass:
4124   case Expr::BlockDeclRefExprClass:
4125   case Expr::NoStmtClass:
4126   case Expr::OpaqueValueExprClass:
4127   case Expr::PackExpansionExprClass:
4128   case Expr::SubstNonTypeTemplateParmPackExprClass:
4129   case Expr::AsTypeExprClass:
4130   case Expr::ObjCIndirectCopyRestoreExprClass:
4131   case Expr::MaterializeTemporaryExprClass:
4132   case Expr::PseudoObjectExprClass:
4133   case Expr::AtomicExprClass:
4134     return ICEDiag(2, E->getLocStart());
4135 
4136   case Expr::InitListExprClass:
4137     if (Ctx.getLangOptions().CPlusPlus0x) {
4138       const InitListExpr *ILE = cast<InitListExpr>(E);
4139       if (ILE->getNumInits() == 0)
4140         return NoDiag();
4141       if (ILE->getNumInits() == 1)
4142         return CheckICE(ILE->getInit(0), Ctx);
4143       // Fall through for more than 1 expression.
4144     }
4145     return ICEDiag(2, E->getLocStart());
4146 
4147   case Expr::SizeOfPackExprClass:
4148   case Expr::GNUNullExprClass:
4149     // GCC considers the GNU __null value to be an integral constant expression.
4150     return NoDiag();
4151 
4152   case Expr::SubstNonTypeTemplateParmExprClass:
4153     return
4154       CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
4155 
4156   case Expr::ParenExprClass:
4157     return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
4158   case Expr::GenericSelectionExprClass:
4159     return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
4160   case Expr::IntegerLiteralClass:
4161   case Expr::CharacterLiteralClass:
4162   case Expr::CXXBoolLiteralExprClass:
4163   case Expr::CXXScalarValueInitExprClass:
4164   case Expr::UnaryTypeTraitExprClass:
4165   case Expr::BinaryTypeTraitExprClass:
4166   case Expr::ArrayTypeTraitExprClass:
4167   case Expr::ExpressionTraitExprClass:
4168   case Expr::CXXNoexceptExprClass:
4169     return NoDiag();
4170   case Expr::CallExprClass:
4171   case Expr::CXXOperatorCallExprClass: {
4172     // C99 6.6/3 allows function calls within unevaluated subexpressions of
4173     // constant expressions, but they can never be ICEs because an ICE cannot
4174     // contain an operand of (pointer to) function type.
4175     const CallExpr *CE = cast<CallExpr>(E);
4176     if (CE->isBuiltinCall())
4177       return CheckEvalInICE(E, Ctx);
4178     return ICEDiag(2, E->getLocStart());
4179   }
4180   case Expr::DeclRefExprClass:
4181     if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
4182       return NoDiag();
4183     if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
4184       const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4185 
4186       // Parameter variables are never constants.  Without this check,
4187       // getAnyInitializer() can find a default argument, which leads
4188       // to chaos.
4189       if (isa<ParmVarDecl>(D))
4190         return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4191 
4192       // C++ 7.1.5.1p2
4193       //   A variable of non-volatile const-qualified integral or enumeration
4194       //   type initialized by an ICE can be used in ICEs.
4195       if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
4196         if (!Dcl->getType()->isIntegralOrEnumerationType())
4197           return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4198 
4199         // Look for a declaration of this variable that has an initializer.
4200         const VarDecl *ID = 0;
4201         const Expr *Init = Dcl->getAnyInitializer(ID);
4202         if (Init) {
4203           if (ID->isInitKnownICE()) {
4204             // We have already checked whether this subexpression is an
4205             // integral constant expression.
4206             if (ID->isInitICE())
4207               return NoDiag();
4208             else
4209               return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4210           }
4211 
4212           // It's an ICE whether or not the definition we found is
4213           // out-of-line.  See DR 721 and the discussion in Clang PR
4214           // 6206 for details.
4215 
4216           if (Dcl->isCheckingICE()) {
4217             return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
4218           }
4219 
4220           Dcl->setCheckingICE();
4221           ICEDiag Result = CheckICE(Init, Ctx);
4222           // Cache the result of the ICE test.
4223           Dcl->setInitKnownICE(Result.Val == 0);
4224           return Result;
4225         }
4226       }
4227     }
4228     return ICEDiag(2, E->getLocStart());
4229   case Expr::UnaryOperatorClass: {
4230     const UnaryOperator *Exp = cast<UnaryOperator>(E);
4231     switch (Exp->getOpcode()) {
4232     case UO_PostInc:
4233     case UO_PostDec:
4234     case UO_PreInc:
4235     case UO_PreDec:
4236     case UO_AddrOf:
4237     case UO_Deref:
4238       // C99 6.6/3 allows increment and decrement within unevaluated
4239       // subexpressions of constant expressions, but they can never be ICEs
4240       // because an ICE cannot contain an lvalue operand.
4241       return ICEDiag(2, E->getLocStart());
4242     case UO_Extension:
4243     case UO_LNot:
4244     case UO_Plus:
4245     case UO_Minus:
4246     case UO_Not:
4247     case UO_Real:
4248     case UO_Imag:
4249       return CheckICE(Exp->getSubExpr(), Ctx);
4250     }
4251 
4252     // OffsetOf falls through here.
4253   }
4254   case Expr::OffsetOfExprClass: {
4255       // Note that per C99, offsetof must be an ICE. And AFAIK, using
4256       // EvaluateAsRValue matches the proposed gcc behavior for cases like
4257       // "offsetof(struct s{int x[4];}, x[1.0])".  This doesn't affect
4258       // compliance: we should warn earlier for offsetof expressions with
4259       // array subscripts that aren't ICEs, and if the array subscripts
4260       // are ICEs, the value of the offsetof must be an integer constant.
4261       return CheckEvalInICE(E, Ctx);
4262   }
4263   case Expr::UnaryExprOrTypeTraitExprClass: {
4264     const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
4265     if ((Exp->getKind() ==  UETT_SizeOf) &&
4266         Exp->getTypeOfArgument()->isVariableArrayType())
4267       return ICEDiag(2, E->getLocStart());
4268     return NoDiag();
4269   }
4270   case Expr::BinaryOperatorClass: {
4271     const BinaryOperator *Exp = cast<BinaryOperator>(E);
4272     switch (Exp->getOpcode()) {
4273     case BO_PtrMemD:
4274     case BO_PtrMemI:
4275     case BO_Assign:
4276     case BO_MulAssign:
4277     case BO_DivAssign:
4278     case BO_RemAssign:
4279     case BO_AddAssign:
4280     case BO_SubAssign:
4281     case BO_ShlAssign:
4282     case BO_ShrAssign:
4283     case BO_AndAssign:
4284     case BO_XorAssign:
4285     case BO_OrAssign:
4286       // C99 6.6/3 allows assignments within unevaluated subexpressions of
4287       // constant expressions, but they can never be ICEs because an ICE cannot
4288       // contain an lvalue operand.
4289       return ICEDiag(2, E->getLocStart());
4290 
4291     case BO_Mul:
4292     case BO_Div:
4293     case BO_Rem:
4294     case BO_Add:
4295     case BO_Sub:
4296     case BO_Shl:
4297     case BO_Shr:
4298     case BO_LT:
4299     case BO_GT:
4300     case BO_LE:
4301     case BO_GE:
4302     case BO_EQ:
4303     case BO_NE:
4304     case BO_And:
4305     case BO_Xor:
4306     case BO_Or:
4307     case BO_Comma: {
4308       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4309       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4310       if (Exp->getOpcode() == BO_Div ||
4311           Exp->getOpcode() == BO_Rem) {
4312         // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
4313         // we don't evaluate one.
4314         if (LHSResult.Val == 0 && RHSResult.Val == 0) {
4315           llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
4316           if (REval == 0)
4317             return ICEDiag(1, E->getLocStart());
4318           if (REval.isSigned() && REval.isAllOnesValue()) {
4319             llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
4320             if (LEval.isMinSignedValue())
4321               return ICEDiag(1, E->getLocStart());
4322           }
4323         }
4324       }
4325       if (Exp->getOpcode() == BO_Comma) {
4326         if (Ctx.getLangOptions().C99) {
4327           // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
4328           // if it isn't evaluated.
4329           if (LHSResult.Val == 0 && RHSResult.Val == 0)
4330             return ICEDiag(1, E->getLocStart());
4331         } else {
4332           // In both C89 and C++, commas in ICEs are illegal.
4333           return ICEDiag(2, E->getLocStart());
4334         }
4335       }
4336       if (LHSResult.Val >= RHSResult.Val)
4337         return LHSResult;
4338       return RHSResult;
4339     }
4340     case BO_LAnd:
4341     case BO_LOr: {
4342       ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
4343 
4344       // C++0x [expr.const]p2:
4345       //   [...] subexpressions of logical AND (5.14), logical OR
4346       //   (5.15), and condi- tional (5.16) operations that are not
4347       //   evaluated are not considered.
4348       if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
4349         if (Exp->getOpcode() == BO_LAnd &&
4350             Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
4351           return LHSResult;
4352 
4353         if (Exp->getOpcode() == BO_LOr &&
4354             Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
4355           return LHSResult;
4356       }
4357 
4358       ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
4359       if (LHSResult.Val == 0 && RHSResult.Val == 1) {
4360         // Rare case where the RHS has a comma "side-effect"; we need
4361         // to actually check the condition to see whether the side
4362         // with the comma is evaluated.
4363         if ((Exp->getOpcode() == BO_LAnd) !=
4364             (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
4365           return RHSResult;
4366         return NoDiag();
4367       }
4368 
4369       if (LHSResult.Val >= RHSResult.Val)
4370         return LHSResult;
4371       return RHSResult;
4372     }
4373     }
4374   }
4375   case Expr::ImplicitCastExprClass:
4376   case Expr::CStyleCastExprClass:
4377   case Expr::CXXFunctionalCastExprClass:
4378   case Expr::CXXStaticCastExprClass:
4379   case Expr::CXXReinterpretCastExprClass:
4380   case Expr::CXXConstCastExprClass:
4381   case Expr::ObjCBridgedCastExprClass: {
4382     const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
4383     if (isa<ExplicitCastExpr>(E) &&
4384         isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
4385       return NoDiag();
4386     switch (cast<CastExpr>(E)->getCastKind()) {
4387     case CK_LValueToRValue:
4388     case CK_NoOp:
4389     case CK_IntegralToBoolean:
4390     case CK_IntegralCast:
4391       return CheckICE(SubExpr, Ctx);
4392     default:
4393       return ICEDiag(2, E->getLocStart());
4394     }
4395   }
4396   case Expr::BinaryConditionalOperatorClass: {
4397     const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
4398     ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
4399     if (CommonResult.Val == 2) return CommonResult;
4400     ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4401     if (FalseResult.Val == 2) return FalseResult;
4402     if (CommonResult.Val == 1) return CommonResult;
4403     if (FalseResult.Val == 1 &&
4404         Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
4405     return FalseResult;
4406   }
4407   case Expr::ConditionalOperatorClass: {
4408     const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
4409     // If the condition (ignoring parens) is a __builtin_constant_p call,
4410     // then only the true side is actually considered in an integer constant
4411     // expression, and it is fully evaluated.  This is an important GNU
4412     // extension.  See GCC PR38377 for discussion.
4413     if (const CallExpr *CallCE
4414         = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
4415       if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p) {
4416         Expr::EvalResult EVResult;
4417         if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
4418             !EVResult.Val.isInt()) {
4419           return ICEDiag(2, E->getLocStart());
4420         }
4421         return NoDiag();
4422       }
4423     ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
4424     if (CondResult.Val == 2)
4425       return CondResult;
4426 
4427     // C++0x [expr.const]p2:
4428     //   subexpressions of [...] conditional (5.16) operations that
4429     //   are not evaluated are not considered
4430     bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
4431       ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
4432       : false;
4433     ICEDiag TrueResult = NoDiag();
4434     if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
4435       TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
4436     ICEDiag FalseResult = NoDiag();
4437     if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
4438       FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
4439 
4440     if (TrueResult.Val == 2)
4441       return TrueResult;
4442     if (FalseResult.Val == 2)
4443       return FalseResult;
4444     if (CondResult.Val == 1)
4445       return CondResult;
4446     if (TrueResult.Val == 0 && FalseResult.Val == 0)
4447       return NoDiag();
4448     // Rare case where the diagnostics depend on which side is evaluated
4449     // Note that if we get here, CondResult is 0, and at least one of
4450     // TrueResult and FalseResult is non-zero.
4451     if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
4452       return FalseResult;
4453     }
4454     return TrueResult;
4455   }
4456   case Expr::CXXDefaultArgExprClass:
4457     return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
4458   case Expr::ChooseExprClass: {
4459     return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
4460   }
4461   }
4462 
4463   // Silence a GCC warning
4464   return ICEDiag(2, E->getLocStart());
4465 }
4466 
4467 bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
4468                                  SourceLocation *Loc, bool isEvaluated) const {
4469   ICEDiag d = CheckICE(this, Ctx);
4470   if (d.Val != 0) {
4471     if (Loc) *Loc = d.Loc;
4472     return false;
4473   }
4474   if (!EvaluateAsInt(Result, Ctx))
4475     llvm_unreachable("ICE cannot be evaluated!");
4476   return true;
4477 }
4478