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