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/RecordLayout.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/AST/ASTDiagnostic.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/Support/Compiler.h"
23 #include <cstring>
24 
25 using namespace clang;
26 using llvm::APSInt;
27 using llvm::APFloat;
28 
29 /// EvalInfo - This is a private struct used by the evaluator to capture
30 /// information about a subexpression as it is folded.  It retains information
31 /// about the AST context, but also maintains information about the folded
32 /// expression.
33 ///
34 /// If an expression could be evaluated, it is still possible it is not a C
35 /// "integer constant expression" or constant expression.  If not, this struct
36 /// captures information about how and why not.
37 ///
38 /// One bit of information passed *into* the request for constant folding
39 /// indicates whether the subexpression is "evaluated" or not according to C
40 /// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
41 /// evaluate the expression regardless of what the RHS is, but C only allows
42 /// certain things in certain situations.
43 struct EvalInfo {
44   ASTContext &Ctx;
45 
46   /// EvalResult - Contains information about the evaluation.
47   Expr::EvalResult &EvalResult;
48 
49   EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
50            EvalResult(evalresult) {}
51 };
52 
53 
54 static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
55 static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
56 static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
57 static bool EvaluateIntegerOrLValue(const Expr *E, APValue  &Result, EvalInfo &Info);
58 static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
59 static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
60 
61 //===----------------------------------------------------------------------===//
62 // Misc utilities
63 //===----------------------------------------------------------------------===//
64 
65 static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
66   // FIXME: Is this accurate for all kinds of bases?  If not, what would
67   // the check look like?
68   Result = Value.getLValueBase() || Value.getLValueOffset();
69   return true;
70 }
71 
72 static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
73   if (E->getType()->isIntegralType()) {
74     APSInt IntResult;
75     if (!EvaluateInteger(E, IntResult, Info))
76       return false;
77     Result = IntResult != 0;
78     return true;
79   } else if (E->getType()->isRealFloatingType()) {
80     APFloat FloatResult(0.0);
81     if (!EvaluateFloat(E, FloatResult, Info))
82       return false;
83     Result = !FloatResult.isZero();
84     return true;
85   } else if (E->getType()->hasPointerRepresentation()) {
86     APValue PointerResult;
87     if (!EvaluatePointer(E, PointerResult, Info))
88       return false;
89     return EvalPointerValueAsBool(PointerResult, Result);
90   } else if (E->getType()->isAnyComplexType()) {
91     APValue ComplexResult;
92     if (!EvaluateComplex(E, ComplexResult, Info))
93       return false;
94     if (ComplexResult.isComplexFloat()) {
95       Result = !ComplexResult.getComplexFloatReal().isZero() ||
96                !ComplexResult.getComplexFloatImag().isZero();
97     } else {
98       Result = ComplexResult.getComplexIntReal().getBoolValue() ||
99                ComplexResult.getComplexIntImag().getBoolValue();
100     }
101     return true;
102   }
103 
104   return false;
105 }
106 
107 static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
108                                    APFloat &Value, ASTContext &Ctx) {
109   unsigned DestWidth = Ctx.getIntWidth(DestType);
110   // Determine whether we are converting to unsigned or signed.
111   bool DestSigned = DestType->isSignedIntegerType();
112 
113   // FIXME: Warning for overflow.
114   uint64_t Space[4];
115   bool ignored;
116   (void)Value.convertToInteger(Space, DestWidth, DestSigned,
117                                llvm::APFloat::rmTowardZero, &ignored);
118   return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
119 }
120 
121 static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
122                                       APFloat &Value, ASTContext &Ctx) {
123   bool ignored;
124   APFloat Result = Value;
125   Result.convert(Ctx.getFloatTypeSemantics(DestType),
126                  APFloat::rmNearestTiesToEven, &ignored);
127   return Result;
128 }
129 
130 static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
131                                  APSInt &Value, ASTContext &Ctx) {
132   unsigned DestWidth = Ctx.getIntWidth(DestType);
133   APSInt Result = Value;
134   // Figure out if this is a truncate, extend or noop cast.
135   // If the input is signed, do a sign extend, noop, or truncate.
136   Result.extOrTrunc(DestWidth);
137   Result.setIsUnsigned(DestType->isUnsignedIntegerType());
138   return Result;
139 }
140 
141 static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
142                                     APSInt &Value, ASTContext &Ctx) {
143 
144   APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
145   Result.convertFromAPInt(Value, Value.isSigned(),
146                           APFloat::rmNearestTiesToEven);
147   return Result;
148 }
149 
150 //===----------------------------------------------------------------------===//
151 // LValue Evaluation
152 //===----------------------------------------------------------------------===//
153 namespace {
154 class VISIBILITY_HIDDEN LValueExprEvaluator
155   : public StmtVisitor<LValueExprEvaluator, APValue> {
156   EvalInfo &Info;
157 public:
158 
159   LValueExprEvaluator(EvalInfo &info) : Info(info) {}
160 
161   APValue VisitStmt(Stmt *S) {
162     return APValue();
163   }
164 
165   APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
166   APValue VisitDeclRefExpr(DeclRefExpr *E);
167   APValue VisitBlockExpr(BlockExpr *E);
168   APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
169   APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
170   APValue VisitMemberExpr(MemberExpr *E);
171   APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
172   APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E, 0); }
173   APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
174   APValue VisitUnaryDeref(UnaryOperator *E);
175   APValue VisitUnaryExtension(const UnaryOperator *E)
176     { return Visit(E->getSubExpr()); }
177   APValue VisitChooseExpr(const ChooseExpr *E)
178     { return Visit(E->getChosenSubExpr(Info.Ctx)); }
179   // FIXME: Missing: __real__, __imag__
180 };
181 } // end anonymous namespace
182 
183 static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
184   Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
185   return Result.isLValue();
186 }
187 
188 APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
189 {
190   if (!E->hasGlobalStorage())
191     return APValue();
192 
193   if (isa<FunctionDecl>(E->getDecl())) {
194     return APValue(E, 0);
195   } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
196     if (!VD->getType()->isReferenceType())
197       return APValue(E, 0);
198     if (VD->getInit())
199       return Visit(VD->getInit());
200   }
201 
202   return APValue();
203 }
204 
205 APValue LValueExprEvaluator::VisitBlockExpr(BlockExpr *E)
206 {
207   if (E->hasBlockDeclRefExprs())
208     return APValue();
209 
210   return APValue(E, 0);
211 }
212 
213 APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
214   if (E->isFileScope())
215     return APValue(E, 0);
216   return APValue();
217 }
218 
219 APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
220   APValue result;
221   QualType Ty;
222   if (E->isArrow()) {
223     if (!EvaluatePointer(E->getBase(), result, Info))
224       return APValue();
225     Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
226   } else {
227     result = Visit(E->getBase());
228     if (result.isUninit())
229       return APValue();
230     Ty = E->getBase()->getType();
231   }
232 
233   RecordDecl *RD = Ty->getAsRecordType()->getDecl();
234   const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
235 
236   FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
237   if (!FD) // FIXME: deal with other kinds of member expressions
238     return APValue();
239 
240   if (FD->getType()->isReferenceType())
241     return APValue();
242 
243   // FIXME: This is linear time.
244   unsigned i = 0;
245   for (RecordDecl::field_iterator Field = RD->field_begin(),
246                                FieldEnd = RD->field_end();
247        Field != FieldEnd; (void)++Field, ++i) {
248     if (*Field == FD)
249       break;
250   }
251 
252   result.setLValue(result.getLValueBase(),
253                    result.getLValueOffset() + RL.getFieldOffset(i) / 8);
254 
255   return result;
256 }
257 
258 APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
259 {
260   APValue Result;
261 
262   if (!EvaluatePointer(E->getBase(), Result, Info))
263     return APValue();
264 
265   APSInt Index;
266   if (!EvaluateInteger(E->getIdx(), Index, Info))
267     return APValue();
268 
269   uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
270 
271   uint64_t Offset = Index.getSExtValue() * ElementSize;
272   Result.setLValue(Result.getLValueBase(),
273                    Result.getLValueOffset() + Offset);
274   return Result;
275 }
276 
277 APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E)
278 {
279   APValue Result;
280   if (!EvaluatePointer(E->getSubExpr(), Result, Info))
281     return APValue();
282   return Result;
283 }
284 
285 //===----------------------------------------------------------------------===//
286 // Pointer Evaluation
287 //===----------------------------------------------------------------------===//
288 
289 namespace {
290 class VISIBILITY_HIDDEN PointerExprEvaluator
291   : public StmtVisitor<PointerExprEvaluator, APValue> {
292   EvalInfo &Info;
293 public:
294 
295   PointerExprEvaluator(EvalInfo &info) : Info(info) {}
296 
297   APValue VisitStmt(Stmt *S) {
298     return APValue();
299   }
300 
301   APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
302 
303   APValue VisitBinaryOperator(const BinaryOperator *E);
304   APValue VisitCastExpr(const CastExpr* E);
305   APValue VisitUnaryExtension(const UnaryOperator *E)
306       { return Visit(E->getSubExpr()); }
307   APValue VisitUnaryAddrOf(const UnaryOperator *E);
308   APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
309       { return APValue(E, 0); }
310   APValue VisitAddrLabelExpr(AddrLabelExpr *E)
311       { return APValue(E, 0); }
312   APValue VisitCallExpr(CallExpr *E);
313   APValue VisitBlockExpr(BlockExpr *E) {
314     if (!E->hasBlockDeclRefExprs())
315       return APValue(E, 0);
316     return APValue();
317   }
318   APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
319       { return APValue((Expr*)0, 0); }
320   APValue VisitConditionalOperator(ConditionalOperator *E);
321   APValue VisitChooseExpr(ChooseExpr *E)
322       { return Visit(E->getChosenSubExpr(Info.Ctx)); }
323   APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
324       { return APValue((Expr*)0, 0); }
325   // FIXME: Missing: @protocol, @selector
326 };
327 } // end anonymous namespace
328 
329 static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
330   if (!E->getType()->hasPointerRepresentation())
331     return false;
332   Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
333   return Result.isLValue();
334 }
335 
336 APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
337   if (E->getOpcode() != BinaryOperator::Add &&
338       E->getOpcode() != BinaryOperator::Sub)
339     return APValue();
340 
341   const Expr *PExp = E->getLHS();
342   const Expr *IExp = E->getRHS();
343   if (IExp->getType()->isPointerType())
344     std::swap(PExp, IExp);
345 
346   APValue ResultLValue;
347   if (!EvaluatePointer(PExp, ResultLValue, Info))
348     return APValue();
349 
350   llvm::APSInt AdditionalOffset(32);
351   if (!EvaluateInteger(IExp, AdditionalOffset, Info))
352     return APValue();
353 
354   QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
355   uint64_t SizeOfPointee;
356 
357   // Explicitly handle GNU void* and function pointer arithmetic extensions.
358   if (PointeeType->isVoidType() || PointeeType->isFunctionType())
359     SizeOfPointee = 1;
360   else
361     SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
362 
363   uint64_t Offset = ResultLValue.getLValueOffset();
364 
365   if (E->getOpcode() == BinaryOperator::Add)
366     Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
367   else
368     Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
369 
370   return APValue(ResultLValue.getLValueBase(), Offset);
371 }
372 
373 APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
374   APValue result;
375   if (EvaluateLValue(E->getSubExpr(), result, Info))
376     return result;
377   return APValue();
378 }
379 
380 
381 APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
382   const Expr* SubExpr = E->getSubExpr();
383 
384    // Check for pointer->pointer cast
385   if (SubExpr->getType()->isPointerType()) {
386     APValue Result;
387     if (EvaluatePointer(SubExpr, Result, Info))
388       return Result;
389     return APValue();
390   }
391 
392   if (SubExpr->getType()->isIntegralType()) {
393     APValue Result;
394     if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
395       return APValue();
396 
397     if (Result.isInt()) {
398       Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
399       return APValue(0, Result.getInt().getZExtValue());
400     }
401 
402     // Cast is of an lvalue, no need to change value.
403     return Result;
404   }
405 
406   if (SubExpr->getType()->isFunctionType() ||
407       SubExpr->getType()->isBlockPointerType() ||
408       SubExpr->getType()->isArrayType()) {
409     APValue Result;
410     if (EvaluateLValue(SubExpr, Result, Info))
411       return Result;
412     return APValue();
413   }
414 
415   return APValue();
416 }
417 
418 APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
419   if (E->isBuiltinCall(Info.Ctx) ==
420         Builtin::BI__builtin___CFStringMakeConstantString)
421     return APValue(E, 0);
422   return APValue();
423 }
424 
425 APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
426   bool BoolResult;
427   if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
428     return APValue();
429 
430   Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
431 
432   APValue Result;
433   if (EvaluatePointer(EvalExpr, Result, Info))
434     return Result;
435   return APValue();
436 }
437 
438 //===----------------------------------------------------------------------===//
439 // Vector Evaluation
440 //===----------------------------------------------------------------------===//
441 
442 namespace {
443   class VISIBILITY_HIDDEN VectorExprEvaluator
444   : public StmtVisitor<VectorExprEvaluator, APValue> {
445     EvalInfo &Info;
446     APValue GetZeroVector(QualType VecType);
447   public:
448 
449     VectorExprEvaluator(EvalInfo &info) : Info(info) {}
450 
451     APValue VisitStmt(Stmt *S) {
452       return APValue();
453     }
454 
455     APValue VisitParenExpr(ParenExpr *E)
456         { return Visit(E->getSubExpr()); }
457     APValue VisitUnaryExtension(const UnaryOperator *E)
458       { return Visit(E->getSubExpr()); }
459     APValue VisitUnaryPlus(const UnaryOperator *E)
460       { return Visit(E->getSubExpr()); }
461     APValue VisitUnaryReal(const UnaryOperator *E)
462       { return Visit(E->getSubExpr()); }
463     APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
464       { return GetZeroVector(E->getType()); }
465     APValue VisitCastExpr(const CastExpr* E);
466     APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
467     APValue VisitInitListExpr(const InitListExpr *E);
468     APValue VisitConditionalOperator(const ConditionalOperator *E);
469     APValue VisitChooseExpr(const ChooseExpr *E)
470       { return Visit(E->getChosenSubExpr(Info.Ctx)); }
471     APValue VisitUnaryImag(const UnaryOperator *E);
472     // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
473     //                 binary comparisons, binary and/or/xor,
474     //                 shufflevector, ExtVectorElementExpr
475     //        (Note that these require implementing conversions
476     //         between vector types.)
477   };
478 } // end anonymous namespace
479 
480 static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
481   if (!E->getType()->isVectorType())
482     return false;
483   Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
484   return !Result.isUninit();
485 }
486 
487 APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
488   const VectorType *VTy = E->getType()->getAsVectorType();
489   QualType EltTy = VTy->getElementType();
490   unsigned NElts = VTy->getNumElements();
491   unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
492 
493   const Expr* SE = E->getSubExpr();
494   QualType SETy = SE->getType();
495   APValue Result = APValue();
496 
497   // Check for vector->vector bitcast and scalar->vector splat.
498   if (SETy->isVectorType()) {
499     return this->Visit(const_cast<Expr*>(SE));
500   } else if (SETy->isIntegerType()) {
501     APSInt IntResult;
502     if (!EvaluateInteger(SE, IntResult, Info))
503       return APValue();
504     Result = APValue(IntResult);
505   } else if (SETy->isRealFloatingType()) {
506     APFloat F(0.0);
507     if (!EvaluateFloat(SE, F, Info))
508       return APValue();
509     Result = APValue(F);
510   } else
511     return APValue();
512 
513   // For casts of a scalar to ExtVector, convert the scalar to the element type
514   // and splat it to all elements.
515   if (E->getType()->isExtVectorType()) {
516     if (EltTy->isIntegerType() && Result.isInt())
517       Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
518                                           Info.Ctx));
519     else if (EltTy->isIntegerType())
520       Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
521                                             Info.Ctx));
522     else if (EltTy->isRealFloatingType() && Result.isInt())
523       Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
524                                             Info.Ctx));
525     else if (EltTy->isRealFloatingType())
526       Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
527                                               Info.Ctx));
528     else
529       return APValue();
530 
531     // Splat and create vector APValue.
532     llvm::SmallVector<APValue, 4> Elts(NElts, Result);
533     return APValue(&Elts[0], Elts.size());
534   }
535 
536   // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
537   // to the vector. To construct the APValue vector initializer, bitcast the
538   // initializing value to an APInt, and shift out the bits pertaining to each
539   // element.
540   APSInt Init;
541   Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
542 
543   llvm::SmallVector<APValue, 4> Elts;
544   for (unsigned i = 0; i != NElts; ++i) {
545     APSInt Tmp = Init;
546     Tmp.extOrTrunc(EltWidth);
547 
548     if (EltTy->isIntegerType())
549       Elts.push_back(APValue(Tmp));
550     else if (EltTy->isRealFloatingType())
551       Elts.push_back(APValue(APFloat(Tmp)));
552     else
553       return APValue();
554 
555     Init >>= EltWidth;
556   }
557   return APValue(&Elts[0], Elts.size());
558 }
559 
560 APValue
561 VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
562   return this->Visit(const_cast<Expr*>(E->getInitializer()));
563 }
564 
565 APValue
566 VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
567   const VectorType *VT = E->getType()->getAsVectorType();
568   unsigned NumInits = E->getNumInits();
569   unsigned NumElements = VT->getNumElements();
570 
571   QualType EltTy = VT->getElementType();
572   llvm::SmallVector<APValue, 4> Elements;
573 
574   for (unsigned i = 0; i < NumElements; i++) {
575     if (EltTy->isIntegerType()) {
576       llvm::APSInt sInt(32);
577       if (i < NumInits) {
578         if (!EvaluateInteger(E->getInit(i), sInt, Info))
579           return APValue();
580       } else {
581         sInt = Info.Ctx.MakeIntValue(0, EltTy);
582       }
583       Elements.push_back(APValue(sInt));
584     } else {
585       llvm::APFloat f(0.0);
586       if (i < NumInits) {
587         if (!EvaluateFloat(E->getInit(i), f, Info))
588           return APValue();
589       } else {
590         f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
591       }
592       Elements.push_back(APValue(f));
593     }
594   }
595   return APValue(&Elements[0], Elements.size());
596 }
597 
598 APValue
599 VectorExprEvaluator::GetZeroVector(QualType T) {
600   const VectorType *VT = T->getAsVectorType();
601   QualType EltTy = VT->getElementType();
602   APValue ZeroElement;
603   if (EltTy->isIntegerType())
604     ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
605   else
606     ZeroElement =
607         APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
608 
609   llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
610   return APValue(&Elements[0], Elements.size());
611 }
612 
613 APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
614   bool BoolResult;
615   if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
616     return APValue();
617 
618   Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
619 
620   APValue Result;
621   if (EvaluateVector(EvalExpr, Result, Info))
622     return Result;
623   return APValue();
624 }
625 
626 APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
627   if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
628     Info.EvalResult.HasSideEffects = true;
629   return GetZeroVector(E->getType());
630 }
631 
632 //===----------------------------------------------------------------------===//
633 // Integer Evaluation
634 //===----------------------------------------------------------------------===//
635 
636 namespace {
637 class VISIBILITY_HIDDEN IntExprEvaluator
638   : public StmtVisitor<IntExprEvaluator, bool> {
639   EvalInfo &Info;
640   APValue &Result;
641 public:
642   IntExprEvaluator(EvalInfo &info, APValue &result)
643     : Info(info), Result(result) {}
644 
645   bool Success(const llvm::APSInt &SI, const Expr *E) {
646     assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
647     assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
648            "Invalid evaluation result.");
649     assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
650            "Invalid evaluation result.");
651     Result = APValue(SI);
652     return true;
653   }
654 
655   bool Success(const llvm::APInt &I, const Expr *E) {
656     assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
657     assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
658            "Invalid evaluation result.");
659     Result = APValue(APSInt(I));
660     Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
661     return true;
662   }
663 
664   bool Success(uint64_t Value, const Expr *E) {
665     assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
666     Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
667     return true;
668   }
669 
670   bool Error(SourceLocation L, diag::kind D, const Expr *E) {
671     // Take the first error.
672     if (Info.EvalResult.Diag == 0) {
673       Info.EvalResult.DiagLoc = L;
674       Info.EvalResult.Diag = D;
675       Info.EvalResult.DiagExpr = E;
676     }
677     return false;
678   }
679 
680   //===--------------------------------------------------------------------===//
681   //                            Visitor Methods
682   //===--------------------------------------------------------------------===//
683 
684   bool VisitStmt(Stmt *) {
685     assert(0 && "This should be called on integers, stmts are not integers");
686     return false;
687   }
688 
689   bool VisitExpr(Expr *E) {
690     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
691   }
692 
693   bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
694 
695   bool VisitIntegerLiteral(const IntegerLiteral *E) {
696     return Success(E->getValue(), E);
697   }
698   bool VisitCharacterLiteral(const CharacterLiteral *E) {
699     return Success(E->getValue(), E);
700   }
701   bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
702     // Per gcc docs "this built-in function ignores top level
703     // qualifiers".  We need to use the canonical version to properly
704     // be able to strip CRV qualifiers from the type.
705     QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
706     QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
707     return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
708                                                T1.getUnqualifiedType()),
709                    E);
710   }
711   bool VisitDeclRefExpr(const DeclRefExpr *E);
712   bool VisitCallExpr(const CallExpr *E);
713   bool VisitBinaryOperator(const BinaryOperator *E);
714   bool VisitUnaryOperator(const UnaryOperator *E);
715   bool VisitConditionalOperator(const ConditionalOperator *E);
716 
717   bool VisitCastExpr(CastExpr* E);
718   bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
719 
720   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
721     return Success(E->getValue(), E);
722   }
723 
724   bool VisitGNUNullExpr(const GNUNullExpr *E) {
725     return Success(0, E);
726   }
727 
728   bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
729     return Success(0, E);
730   }
731 
732   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
733     return Success(0, E);
734   }
735 
736   bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
737     return Success(E->EvaluateTrait(), E);
738   }
739 
740   bool VisitChooseExpr(const ChooseExpr *E) {
741     return Visit(E->getChosenSubExpr(Info.Ctx));
742   }
743 
744   bool VisitUnaryReal(const UnaryOperator *E);
745   bool VisitUnaryImag(const UnaryOperator *E);
746 
747 private:
748   unsigned GetAlignOfExpr(const Expr *E);
749   unsigned GetAlignOfType(QualType T);
750   // FIXME: Missing: array subscript of vector, member of vector
751 };
752 } // end anonymous namespace
753 
754 static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
755   if (!E->getType()->isIntegralType())
756     return false;
757 
758   return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
759 }
760 
761 static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
762   APValue Val;
763   if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
764     return false;
765   Result = Val.getInt();
766   return true;
767 }
768 
769 bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
770   // Enums are integer constant exprs.
771   if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
772     // FIXME: This is an ugly hack around the fact that enums don't set their
773     // signedness consistently; see PR3173.
774     APSInt SI = D->getInitVal();
775     SI.setIsUnsigned(!E->getType()->isSignedIntegerType());
776     // FIXME: This is an ugly hack around the fact that enums don't
777     // set their width (!?!) consistently; see PR3173.
778     SI.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
779     return Success(SI, E);
780   }
781 
782   // In C++, const, non-volatile integers initialized with ICEs are ICEs.
783   // In C, they can also be folded, although they are not ICEs.
784   if (E->getType().getCVRQualifiers() == QualType::Const) {
785     if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
786       if (APValue *V = D->getEvaluatedValue())
787         return Success(V->getInt(), E);
788       if (const Expr *Init = D->getInit()) {
789         if (Visit(const_cast<Expr*>(Init))) {
790           // Cache the evaluated value in the variable declaration.
791           D->setEvaluatedValue(Info.Ctx, Result);
792           return true;
793         }
794 
795         return false;
796       }
797     }
798   }
799 
800   // Otherwise, random variable references are not constants.
801   return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
802 }
803 
804 /// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
805 /// as GCC.
806 static int EvaluateBuiltinClassifyType(const CallExpr *E) {
807   // The following enum mimics the values returned by GCC.
808   // FIXME: Does GCC differ between lvalue and rvalue references here?
809   enum gcc_type_class {
810     no_type_class = -1,
811     void_type_class, integer_type_class, char_type_class,
812     enumeral_type_class, boolean_type_class,
813     pointer_type_class, reference_type_class, offset_type_class,
814     real_type_class, complex_type_class,
815     function_type_class, method_type_class,
816     record_type_class, union_type_class,
817     array_type_class, string_type_class,
818     lang_type_class
819   };
820 
821   // If no argument was supplied, default to "no_type_class". This isn't
822   // ideal, however it is what gcc does.
823   if (E->getNumArgs() == 0)
824     return no_type_class;
825 
826   QualType ArgTy = E->getArg(0)->getType();
827   if (ArgTy->isVoidType())
828     return void_type_class;
829   else if (ArgTy->isEnumeralType())
830     return enumeral_type_class;
831   else if (ArgTy->isBooleanType())
832     return boolean_type_class;
833   else if (ArgTy->isCharType())
834     return string_type_class; // gcc doesn't appear to use char_type_class
835   else if (ArgTy->isIntegerType())
836     return integer_type_class;
837   else if (ArgTy->isPointerType())
838     return pointer_type_class;
839   else if (ArgTy->isReferenceType())
840     return reference_type_class;
841   else if (ArgTy->isRealType())
842     return real_type_class;
843   else if (ArgTy->isComplexType())
844     return complex_type_class;
845   else if (ArgTy->isFunctionType())
846     return function_type_class;
847   else if (ArgTy->isStructureType())
848     return record_type_class;
849   else if (ArgTy->isUnionType())
850     return union_type_class;
851   else if (ArgTy->isArrayType())
852     return array_type_class;
853   else if (ArgTy->isUnionType())
854     return union_type_class;
855   else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
856     assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
857   return -1;
858 }
859 
860 bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
861   switch (E->isBuiltinCall(Info.Ctx)) {
862   default:
863     return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
864   case Builtin::BI__builtin_classify_type:
865     return Success(EvaluateBuiltinClassifyType(E), E);
866 
867   case Builtin::BI__builtin_constant_p:
868     // __builtin_constant_p always has one operand: it returns true if that
869     // operand can be folded, false otherwise.
870     return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
871   }
872 }
873 
874 bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
875   if (E->getOpcode() == BinaryOperator::Comma) {
876     if (!Visit(E->getRHS()))
877       return false;
878 
879     // If we can't evaluate the LHS, it might have side effects;
880     // conservatively mark it.
881     if (!E->getLHS()->isEvaluatable(Info.Ctx))
882       Info.EvalResult.HasSideEffects = true;
883 
884     return true;
885   }
886 
887   if (E->isLogicalOp()) {
888     // These need to be handled specially because the operands aren't
889     // necessarily integral
890     bool lhsResult, rhsResult;
891 
892     if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
893       // We were able to evaluate the LHS, see if we can get away with not
894       // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
895       if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
896         return Success(lhsResult, E);
897 
898       if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
899         if (E->getOpcode() == BinaryOperator::LOr)
900           return Success(lhsResult || rhsResult, E);
901         else
902           return Success(lhsResult && rhsResult, E);
903       }
904     } else {
905       if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
906         // We can't evaluate the LHS; however, sometimes the result
907         // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
908         if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
909             !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
910           // Since we weren't able to evaluate the left hand side, it
911           // must have had side effects.
912           Info.EvalResult.HasSideEffects = true;
913 
914           return Success(rhsResult, E);
915         }
916       }
917     }
918 
919     return false;
920   }
921 
922   QualType LHSTy = E->getLHS()->getType();
923   QualType RHSTy = E->getRHS()->getType();
924 
925   if (LHSTy->isAnyComplexType()) {
926     assert(RHSTy->isAnyComplexType() && "Invalid comparison");
927     APValue LHS, RHS;
928 
929     if (!EvaluateComplex(E->getLHS(), LHS, Info))
930       return false;
931 
932     if (!EvaluateComplex(E->getRHS(), RHS, Info))
933       return false;
934 
935     if (LHS.isComplexFloat()) {
936       APFloat::cmpResult CR_r =
937         LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
938       APFloat::cmpResult CR_i =
939         LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
940 
941       if (E->getOpcode() == BinaryOperator::EQ)
942         return Success((CR_r == APFloat::cmpEqual &&
943                         CR_i == APFloat::cmpEqual), E);
944       else {
945         assert(E->getOpcode() == BinaryOperator::NE &&
946                "Invalid complex comparison.");
947         return Success(((CR_r == APFloat::cmpGreaterThan ||
948                          CR_r == APFloat::cmpLessThan) &&
949                         (CR_i == APFloat::cmpGreaterThan ||
950                          CR_i == APFloat::cmpLessThan)), E);
951       }
952     } else {
953       if (E->getOpcode() == BinaryOperator::EQ)
954         return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
955                         LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
956       else {
957         assert(E->getOpcode() == BinaryOperator::NE &&
958                "Invalid compex comparison.");
959         return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
960                         LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
961       }
962     }
963   }
964 
965   if (LHSTy->isRealFloatingType() &&
966       RHSTy->isRealFloatingType()) {
967     APFloat RHS(0.0), LHS(0.0);
968 
969     if (!EvaluateFloat(E->getRHS(), RHS, Info))
970       return false;
971 
972     if (!EvaluateFloat(E->getLHS(), LHS, Info))
973       return false;
974 
975     APFloat::cmpResult CR = LHS.compare(RHS);
976 
977     switch (E->getOpcode()) {
978     default:
979       assert(0 && "Invalid binary operator!");
980     case BinaryOperator::LT:
981       return Success(CR == APFloat::cmpLessThan, E);
982     case BinaryOperator::GT:
983       return Success(CR == APFloat::cmpGreaterThan, E);
984     case BinaryOperator::LE:
985       return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
986     case BinaryOperator::GE:
987       return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
988                      E);
989     case BinaryOperator::EQ:
990       return Success(CR == APFloat::cmpEqual, E);
991     case BinaryOperator::NE:
992       return Success(CR == APFloat::cmpGreaterThan
993                      || CR == APFloat::cmpLessThan, E);
994     }
995   }
996 
997   if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
998     if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
999       APValue LHSValue;
1000       if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1001         return false;
1002 
1003       APValue RHSValue;
1004       if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1005         return false;
1006 
1007       // Reject any bases from the normal codepath; we special-case comparisons
1008       // to null.
1009       if (LHSValue.getLValueBase()) {
1010         if (!E->isEqualityOp())
1011           return false;
1012         if (RHSValue.getLValueBase() || RHSValue.getLValueOffset())
1013           return false;
1014         bool bres;
1015         if (!EvalPointerValueAsBool(LHSValue, bres))
1016           return false;
1017         return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1018       } else if (RHSValue.getLValueBase()) {
1019         if (!E->isEqualityOp())
1020           return false;
1021         if (LHSValue.getLValueBase() || LHSValue.getLValueOffset())
1022           return false;
1023         bool bres;
1024         if (!EvalPointerValueAsBool(RHSValue, bres))
1025           return false;
1026         return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1027       }
1028 
1029       if (E->getOpcode() == BinaryOperator::Sub) {
1030         const QualType Type = E->getLHS()->getType();
1031         const QualType ElementType = Type->getAsPointerType()->getPointeeType();
1032 
1033         uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
1034         if (!ElementType->isVoidType() && !ElementType->isFunctionType())
1035           D /= Info.Ctx.getTypeSize(ElementType) / 8;
1036 
1037         return Success(D, E);
1038       }
1039       bool Result;
1040       if (E->getOpcode() == BinaryOperator::EQ) {
1041         Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
1042       } else {
1043         Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1044       }
1045       return Success(Result, E);
1046     }
1047   }
1048   if (!LHSTy->isIntegralType() ||
1049       !RHSTy->isIntegralType()) {
1050     // We can't continue from here for non-integral types, and they
1051     // could potentially confuse the following operations.
1052     return false;
1053   }
1054 
1055   // The LHS of a constant expr is always evaluated and needed.
1056   if (!Visit(E->getLHS()))
1057     return false; // error in subexpression.
1058 
1059   APValue RHSVal;
1060   if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1061     return false;
1062 
1063   // Handle cases like (unsigned long)&a + 4.
1064   if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1065     uint64_t offset = Result.getLValueOffset();
1066     if (E->getOpcode() == BinaryOperator::Add)
1067       offset += RHSVal.getInt().getZExtValue();
1068     else
1069       offset -= RHSVal.getInt().getZExtValue();
1070     Result = APValue(Result.getLValueBase(), offset);
1071     return true;
1072   }
1073 
1074   // Handle cases like 4 + (unsigned long)&a
1075   if (E->getOpcode() == BinaryOperator::Add &&
1076         RHSVal.isLValue() && Result.isInt()) {
1077     uint64_t offset = RHSVal.getLValueOffset();
1078     offset += Result.getInt().getZExtValue();
1079     Result = APValue(RHSVal.getLValueBase(), offset);
1080     return true;
1081   }
1082 
1083   // All the following cases expect both operands to be an integer
1084   if (!Result.isInt() || !RHSVal.isInt())
1085     return false;
1086 
1087   APSInt& RHS = RHSVal.getInt();
1088 
1089   switch (E->getOpcode()) {
1090   default:
1091     return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1092   case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1093   case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1094   case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1095   case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1096   case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1097   case BinaryOperator::Or:  return Success(Result.getInt() | RHS, E);
1098   case BinaryOperator::Div:
1099     if (RHS == 0)
1100       return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1101     return Success(Result.getInt() / RHS, E);
1102   case BinaryOperator::Rem:
1103     if (RHS == 0)
1104       return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1105     return Success(Result.getInt() % RHS, E);
1106   case BinaryOperator::Shl: {
1107     // FIXME: Warn about out of range shift amounts!
1108     unsigned SA =
1109       (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1110     return Success(Result.getInt() << SA, E);
1111   }
1112   case BinaryOperator::Shr: {
1113     unsigned SA =
1114       (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1115     return Success(Result.getInt() >> SA, E);
1116   }
1117 
1118   case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1119   case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1120   case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1121   case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1122   case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1123   case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
1124   }
1125 }
1126 
1127 bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1128   bool Cond;
1129   if (!HandleConversionToBool(E->getCond(), Cond, Info))
1130     return false;
1131 
1132   return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1133 }
1134 
1135 unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
1136   // Get information about the alignment.
1137   unsigned CharSize = Info.Ctx.Target.getCharWidth();
1138 
1139   // __alignof is defined to return the preferred alignment.
1140   return Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize;
1141 }
1142 
1143 unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1144   E = E->IgnoreParens();
1145 
1146   // alignof decl is always accepted, even if it doesn't make sense: we default
1147   // to 1 in those cases.
1148   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1149     return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
1150 
1151   if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1152     return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
1153 
1154   return GetAlignOfType(E->getType());
1155 }
1156 
1157 
1158 /// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1159 /// expression's type.
1160 bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1161   QualType DstTy = E->getType();
1162 
1163   // Handle alignof separately.
1164   if (!E->isSizeOf()) {
1165     if (E->isArgumentType())
1166       return Success(GetAlignOfType(E->getArgumentType()), E);
1167     else
1168       return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
1169   }
1170 
1171   QualType SrcTy = E->getTypeOfArgument();
1172 
1173   // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1174   // extension.
1175   if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1176     return Success(1, E);
1177 
1178   // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1179   if (!SrcTy->isConstantSizeType())
1180     return false;
1181 
1182   // Get information about the size.
1183   unsigned BitWidth = Info.Ctx.getTypeSize(SrcTy);
1184   return Success(BitWidth / Info.Ctx.Target.getCharWidth(), E);
1185 }
1186 
1187 bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1188   // Special case unary operators that do not need their subexpression
1189   // evaluated.  offsetof/sizeof/alignof are all special.
1190   if (E->isOffsetOfOp()) {
1191     // The AST for offsetof is defined in such a way that we can just
1192     // directly Evaluate it as an l-value.
1193     APValue LV;
1194     if (!EvaluateLValue(E->getSubExpr(), LV, Info))
1195       return false;
1196     if (LV.getLValueBase())
1197       return false;
1198     return Success(LV.getLValueOffset(), E);
1199   }
1200 
1201   if (E->getOpcode() == UnaryOperator::LNot) {
1202     // LNot's operand isn't necessarily an integer, so we handle it specially.
1203     bool bres;
1204     if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1205       return false;
1206     return Success(!bres, E);
1207   }
1208 
1209   // Only handle integral operations...
1210   if (!E->getSubExpr()->getType()->isIntegralType())
1211     return false;
1212 
1213   // Get the operand value into 'Result'.
1214   if (!Visit(E->getSubExpr()))
1215     return false;
1216 
1217   switch (E->getOpcode()) {
1218   default:
1219     // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1220     // See C99 6.6p3.
1221     return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1222   case UnaryOperator::Extension:
1223     // FIXME: Should extension allow i-c-e extension expressions in its scope?
1224     // If so, we could clear the diagnostic ID.
1225     return true;
1226   case UnaryOperator::Plus:
1227     // The result is always just the subexpr.
1228     return true;
1229   case UnaryOperator::Minus:
1230     if (!Result.isInt()) return false;
1231     return Success(-Result.getInt(), E);
1232   case UnaryOperator::Not:
1233     if (!Result.isInt()) return false;
1234     return Success(~Result.getInt(), E);
1235   }
1236 }
1237 
1238 /// HandleCast - This is used to evaluate implicit or explicit casts where the
1239 /// result type is integer.
1240 bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1241   Expr *SubExpr = E->getSubExpr();
1242   QualType DestType = E->getType();
1243   QualType SrcType = SubExpr->getType();
1244 
1245   if (DestType->isBooleanType()) {
1246     bool BoolResult;
1247     if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1248       return false;
1249     return Success(BoolResult, E);
1250   }
1251 
1252   // Handle simple integer->integer casts.
1253   if (SrcType->isIntegralType()) {
1254     if (!Visit(SubExpr))
1255       return false;
1256 
1257     if (!Result.isInt()) {
1258       // Only allow casts of lvalues if they are lossless.
1259       return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1260     }
1261 
1262     return Success(HandleIntToIntCast(DestType, SrcType,
1263                                       Result.getInt(), Info.Ctx), E);
1264   }
1265 
1266   // FIXME: Clean this up!
1267   if (SrcType->isPointerType()) {
1268     APValue LV;
1269     if (!EvaluatePointer(SubExpr, LV, Info))
1270       return false;
1271 
1272     if (LV.getLValueBase()) {
1273       // Only allow based lvalue casts if they are lossless.
1274       if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1275         return false;
1276 
1277       Result = LV;
1278       return true;
1279     }
1280 
1281     APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset(), SrcType);
1282     return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1283   }
1284 
1285   if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1286     // This handles double-conversion cases, where there's both
1287     // an l-value promotion and an implicit conversion to int.
1288     APValue LV;
1289     if (!EvaluateLValue(SubExpr, LV, Info))
1290       return false;
1291 
1292     if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1293       return false;
1294 
1295     Result = LV;
1296     return true;
1297   }
1298 
1299   if (SrcType->isAnyComplexType()) {
1300     APValue C;
1301     if (!EvaluateComplex(SubExpr, C, Info))
1302       return false;
1303     if (C.isComplexFloat())
1304       return Success(HandleFloatToIntCast(DestType, SrcType,
1305                                           C.getComplexFloatReal(), Info.Ctx),
1306                      E);
1307     else
1308       return Success(HandleIntToIntCast(DestType, SrcType,
1309                                         C.getComplexIntReal(), Info.Ctx), E);
1310   }
1311   // FIXME: Handle vectors
1312 
1313   if (!SrcType->isRealFloatingType())
1314     return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1315 
1316   APFloat F(0.0);
1317   if (!EvaluateFloat(SubExpr, F, Info))
1318     return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1319 
1320   return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1321 }
1322 
1323 bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1324   if (E->getSubExpr()->getType()->isAnyComplexType()) {
1325     APValue LV;
1326     if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1327       return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1328     return Success(LV.getComplexIntReal(), E);
1329   }
1330 
1331   return Visit(E->getSubExpr());
1332 }
1333 
1334 bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1335   if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1336     APValue LV;
1337     if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1338       return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1339     return Success(LV.getComplexIntImag(), E);
1340   }
1341 
1342   if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1343     Info.EvalResult.HasSideEffects = true;
1344   return Success(0, E);
1345 }
1346 
1347 //===----------------------------------------------------------------------===//
1348 // Float Evaluation
1349 //===----------------------------------------------------------------------===//
1350 
1351 namespace {
1352 class VISIBILITY_HIDDEN FloatExprEvaluator
1353   : public StmtVisitor<FloatExprEvaluator, bool> {
1354   EvalInfo &Info;
1355   APFloat &Result;
1356 public:
1357   FloatExprEvaluator(EvalInfo &info, APFloat &result)
1358     : Info(info), Result(result) {}
1359 
1360   bool VisitStmt(Stmt *S) {
1361     return false;
1362   }
1363 
1364   bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1365   bool VisitCallExpr(const CallExpr *E);
1366 
1367   bool VisitUnaryOperator(const UnaryOperator *E);
1368   bool VisitBinaryOperator(const BinaryOperator *E);
1369   bool VisitFloatingLiteral(const FloatingLiteral *E);
1370   bool VisitCastExpr(CastExpr *E);
1371   bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
1372 
1373   bool VisitChooseExpr(const ChooseExpr *E)
1374     { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1375   bool VisitUnaryExtension(const UnaryOperator *E)
1376     { return Visit(E->getSubExpr()); }
1377 
1378   // FIXME: Missing: __real__/__imag__, array subscript of vector,
1379   //                 member of vector, ImplicitValueInitExpr,
1380   //                 conditional ?:, comma
1381 };
1382 } // end anonymous namespace
1383 
1384 static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1385   return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1386 }
1387 
1388 bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1389   switch (E->isBuiltinCall(Info.Ctx)) {
1390   default: return false;
1391   case Builtin::BI__builtin_huge_val:
1392   case Builtin::BI__builtin_huge_valf:
1393   case Builtin::BI__builtin_huge_vall:
1394   case Builtin::BI__builtin_inf:
1395   case Builtin::BI__builtin_inff:
1396   case Builtin::BI__builtin_infl: {
1397     const llvm::fltSemantics &Sem =
1398       Info.Ctx.getFloatTypeSemantics(E->getType());
1399     Result = llvm::APFloat::getInf(Sem);
1400     return true;
1401   }
1402 
1403   case Builtin::BI__builtin_nan:
1404   case Builtin::BI__builtin_nanf:
1405   case Builtin::BI__builtin_nanl:
1406     // If this is __builtin_nan() turn this into a nan, otherwise we
1407     // can't constant fold it.
1408     if (const StringLiteral *S =
1409         dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1410       if (!S->isWide()) {
1411         const llvm::fltSemantics &Sem =
1412           Info.Ctx.getFloatTypeSemantics(E->getType());
1413         llvm::SmallString<16> s;
1414         s.append(S->getStrData(), S->getStrData() + S->getByteLength());
1415         s += '\0';
1416         long l;
1417         char *endp;
1418         l = strtol(&s[0], &endp, 0);
1419         if (endp != s.end()-1)
1420           return false;
1421         unsigned type = (unsigned int)l;;
1422         Result = llvm::APFloat::getNaN(Sem, false, type);
1423         return true;
1424       }
1425     }
1426     return false;
1427 
1428   case Builtin::BI__builtin_fabs:
1429   case Builtin::BI__builtin_fabsf:
1430   case Builtin::BI__builtin_fabsl:
1431     if (!EvaluateFloat(E->getArg(0), Result, Info))
1432       return false;
1433 
1434     if (Result.isNegative())
1435       Result.changeSign();
1436     return true;
1437 
1438   case Builtin::BI__builtin_copysign:
1439   case Builtin::BI__builtin_copysignf:
1440   case Builtin::BI__builtin_copysignl: {
1441     APFloat RHS(0.);
1442     if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1443         !EvaluateFloat(E->getArg(1), RHS, Info))
1444       return false;
1445     Result.copySign(RHS);
1446     return true;
1447   }
1448   }
1449 }
1450 
1451 bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1452   if (E->getOpcode() == UnaryOperator::Deref)
1453     return false;
1454 
1455   if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1456     return false;
1457 
1458   switch (E->getOpcode()) {
1459   default: return false;
1460   case UnaryOperator::Plus:
1461     return true;
1462   case UnaryOperator::Minus:
1463     Result.changeSign();
1464     return true;
1465   }
1466 }
1467 
1468 bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1469   // FIXME: Diagnostics?  I really don't understand how the warnings
1470   // and errors are supposed to work.
1471   APFloat RHS(0.0);
1472   if (!EvaluateFloat(E->getLHS(), Result, Info))
1473     return false;
1474   if (!EvaluateFloat(E->getRHS(), RHS, Info))
1475     return false;
1476 
1477   switch (E->getOpcode()) {
1478   default: return false;
1479   case BinaryOperator::Mul:
1480     Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1481     return true;
1482   case BinaryOperator::Add:
1483     Result.add(RHS, APFloat::rmNearestTiesToEven);
1484     return true;
1485   case BinaryOperator::Sub:
1486     Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1487     return true;
1488   case BinaryOperator::Div:
1489     Result.divide(RHS, APFloat::rmNearestTiesToEven);
1490     return true;
1491   }
1492 }
1493 
1494 bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1495   Result = E->getValue();
1496   return true;
1497 }
1498 
1499 bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1500   Expr* SubExpr = E->getSubExpr();
1501 
1502   if (SubExpr->getType()->isIntegralType()) {
1503     APSInt IntResult;
1504     if (!EvaluateInteger(SubExpr, IntResult, Info))
1505       return false;
1506     Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1507                                   IntResult, Info.Ctx);
1508     return true;
1509   }
1510   if (SubExpr->getType()->isRealFloatingType()) {
1511     if (!Visit(SubExpr))
1512       return false;
1513     Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1514                                     Result, Info.Ctx);
1515     return true;
1516   }
1517   // FIXME: Handle complex types
1518 
1519   return false;
1520 }
1521 
1522 bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1523   Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1524   return true;
1525 }
1526 
1527 //===----------------------------------------------------------------------===//
1528 // Complex Evaluation (for float and integer)
1529 //===----------------------------------------------------------------------===//
1530 
1531 namespace {
1532 class VISIBILITY_HIDDEN ComplexExprEvaluator
1533   : public StmtVisitor<ComplexExprEvaluator, APValue> {
1534   EvalInfo &Info;
1535 
1536 public:
1537   ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
1538 
1539   //===--------------------------------------------------------------------===//
1540   //                            Visitor Methods
1541   //===--------------------------------------------------------------------===//
1542 
1543   APValue VisitStmt(Stmt *S) {
1544     return APValue();
1545   }
1546 
1547   APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1548 
1549   APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1550     Expr* SubExpr = E->getSubExpr();
1551 
1552     if (SubExpr->getType()->isRealFloatingType()) {
1553       APFloat Result(0.0);
1554 
1555       if (!EvaluateFloat(SubExpr, Result, Info))
1556         return APValue();
1557 
1558       return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
1559                      Result);
1560     } else {
1561       assert(SubExpr->getType()->isIntegerType() &&
1562              "Unexpected imaginary literal.");
1563 
1564       llvm::APSInt Result;
1565       if (!EvaluateInteger(SubExpr, Result, Info))
1566         return APValue();
1567 
1568       llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1569       Zero = 0;
1570       return APValue(Zero, Result);
1571     }
1572   }
1573 
1574   APValue VisitCastExpr(CastExpr *E) {
1575     Expr* SubExpr = E->getSubExpr();
1576     QualType EltType = E->getType()->getAsComplexType()->getElementType();
1577     QualType SubType = SubExpr->getType();
1578 
1579     if (SubType->isRealFloatingType()) {
1580       APFloat Result(0.0);
1581 
1582       if (!EvaluateFloat(SubExpr, Result, Info))
1583         return APValue();
1584 
1585       if (EltType->isRealFloatingType()) {
1586         Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
1587         return APValue(Result,
1588                        APFloat(Result.getSemantics(), APFloat::fcZero, false));
1589       } else {
1590         llvm::APSInt IResult;
1591         IResult = HandleFloatToIntCast(EltType, SubType, Result, Info.Ctx);
1592         llvm::APSInt Zero(IResult.getBitWidth(), !IResult.isSigned());
1593         Zero = 0;
1594         return APValue(IResult, Zero);
1595       }
1596     } else if (SubType->isIntegerType()) {
1597       APSInt Result;
1598 
1599       if (!EvaluateInteger(SubExpr, Result, Info))
1600         return APValue();
1601 
1602       if (EltType->isRealFloatingType()) {
1603         APFloat FResult =
1604             HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx);
1605         return APValue(FResult,
1606                        APFloat(FResult.getSemantics(), APFloat::fcZero, false));
1607       } else {
1608         Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
1609         llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1610         Zero = 0;
1611         return APValue(Result, Zero);
1612       }
1613     } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1614       APValue Src;
1615 
1616       if (!EvaluateComplex(SubExpr, Src, Info))
1617         return APValue();
1618 
1619       QualType SrcType = CT->getElementType();
1620 
1621       if (Src.isComplexFloat()) {
1622         if (EltType->isRealFloatingType()) {
1623           return APValue(HandleFloatToFloatCast(EltType, SrcType,
1624                                                 Src.getComplexFloatReal(),
1625                                                 Info.Ctx),
1626                          HandleFloatToFloatCast(EltType, SrcType,
1627                                                 Src.getComplexFloatImag(),
1628                                                 Info.Ctx));
1629         } else {
1630           return APValue(HandleFloatToIntCast(EltType, SrcType,
1631                                               Src.getComplexFloatReal(),
1632                                               Info.Ctx),
1633                          HandleFloatToIntCast(EltType, SrcType,
1634                                               Src.getComplexFloatImag(),
1635                                               Info.Ctx));
1636         }
1637       } else {
1638         assert(Src.isComplexInt() && "Invalid evaluate result.");
1639         if (EltType->isRealFloatingType()) {
1640           return APValue(HandleIntToFloatCast(EltType, SrcType,
1641                                               Src.getComplexIntReal(),
1642                                               Info.Ctx),
1643                          HandleIntToFloatCast(EltType, SrcType,
1644                                               Src.getComplexIntImag(),
1645                                               Info.Ctx));
1646         } else {
1647           return APValue(HandleIntToIntCast(EltType, SrcType,
1648                                             Src.getComplexIntReal(),
1649                                             Info.Ctx),
1650                          HandleIntToIntCast(EltType, SrcType,
1651                                             Src.getComplexIntImag(),
1652                                             Info.Ctx));
1653         }
1654       }
1655     }
1656 
1657     // FIXME: Handle more casts.
1658     return APValue();
1659   }
1660 
1661   APValue VisitBinaryOperator(const BinaryOperator *E);
1662   APValue VisitChooseExpr(const ChooseExpr *E)
1663     { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1664   APValue VisitUnaryExtension(const UnaryOperator *E)
1665     { return Visit(E->getSubExpr()); }
1666   // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
1667   //                conditional ?:, comma
1668 };
1669 } // end anonymous namespace
1670 
1671 static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
1672 {
1673   Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1674   assert((!Result.isComplexFloat() ||
1675           (&Result.getComplexFloatReal().getSemantics() ==
1676            &Result.getComplexFloatImag().getSemantics())) &&
1677          "Invalid complex evaluation.");
1678   return Result.isComplexFloat() || Result.isComplexInt();
1679 }
1680 
1681 APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1682 {
1683   APValue Result, RHS;
1684 
1685   if (!EvaluateComplex(E->getLHS(), Result, Info))
1686     return APValue();
1687 
1688   if (!EvaluateComplex(E->getRHS(), RHS, Info))
1689     return APValue();
1690 
1691   assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1692          "Invalid operands to binary operator.");
1693   switch (E->getOpcode()) {
1694   default: return APValue();
1695   case BinaryOperator::Add:
1696     if (Result.isComplexFloat()) {
1697       Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1698                                        APFloat::rmNearestTiesToEven);
1699       Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1700                                        APFloat::rmNearestTiesToEven);
1701     } else {
1702       Result.getComplexIntReal() += RHS.getComplexIntReal();
1703       Result.getComplexIntImag() += RHS.getComplexIntImag();
1704     }
1705     break;
1706   case BinaryOperator::Sub:
1707     if (Result.isComplexFloat()) {
1708       Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1709                                             APFloat::rmNearestTiesToEven);
1710       Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1711                                             APFloat::rmNearestTiesToEven);
1712     } else {
1713       Result.getComplexIntReal() -= RHS.getComplexIntReal();
1714       Result.getComplexIntImag() -= RHS.getComplexIntImag();
1715     }
1716     break;
1717   case BinaryOperator::Mul:
1718     if (Result.isComplexFloat()) {
1719       APValue LHS = Result;
1720       APFloat &LHS_r = LHS.getComplexFloatReal();
1721       APFloat &LHS_i = LHS.getComplexFloatImag();
1722       APFloat &RHS_r = RHS.getComplexFloatReal();
1723       APFloat &RHS_i = RHS.getComplexFloatImag();
1724 
1725       APFloat Tmp = LHS_r;
1726       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1727       Result.getComplexFloatReal() = Tmp;
1728       Tmp = LHS_i;
1729       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1730       Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1731 
1732       Tmp = LHS_r;
1733       Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1734       Result.getComplexFloatImag() = Tmp;
1735       Tmp = LHS_i;
1736       Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1737       Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1738     } else {
1739       APValue LHS = Result;
1740       Result.getComplexIntReal() =
1741         (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1742          LHS.getComplexIntImag() * RHS.getComplexIntImag());
1743       Result.getComplexIntImag() =
1744         (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1745          LHS.getComplexIntImag() * RHS.getComplexIntReal());
1746     }
1747     break;
1748   }
1749 
1750   return Result;
1751 }
1752 
1753 //===----------------------------------------------------------------------===//
1754 // Top level Expr::Evaluate method.
1755 //===----------------------------------------------------------------------===//
1756 
1757 /// Evaluate - Return true if this is a constant which we can fold using
1758 /// any crazy technique (that has nothing to do with language standards) that
1759 /// we want to.  If this function returns true, it returns the folded constant
1760 /// in Result.
1761 bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1762   EvalInfo Info(Ctx, Result);
1763 
1764   if (getType()->isVectorType()) {
1765     if (!EvaluateVector(this, Result.Val, Info))
1766       return false;
1767   } else if (getType()->isIntegerType()) {
1768     if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
1769       return false;
1770   } else if (getType()->hasPointerRepresentation()) {
1771     if (!EvaluatePointer(this, Result.Val, Info))
1772       return false;
1773   } else if (getType()->isRealFloatingType()) {
1774     llvm::APFloat f(0.0);
1775     if (!EvaluateFloat(this, f, Info))
1776       return false;
1777 
1778     Result.Val = APValue(f);
1779   } else if (getType()->isAnyComplexType()) {
1780     if (!EvaluateComplex(this, Result.Val, Info))
1781       return false;
1782   } else
1783     return false;
1784 
1785   return true;
1786 }
1787 
1788 bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
1789   EvalInfo Info(Ctx, Result);
1790 
1791   return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
1792 }
1793 
1794 /// isEvaluatable - Call Evaluate to see if this expression can be constant
1795 /// folded, but discard the result.
1796 bool Expr::isEvaluatable(ASTContext &Ctx) const {
1797   EvalResult Result;
1798   return Evaluate(Result, Ctx) && !Result.HasSideEffects;
1799 }
1800 
1801 APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1802   EvalResult EvalResult;
1803   bool Result = Evaluate(EvalResult, Ctx);
1804   Result = Result;
1805   assert(Result && "Could not evaluate expression");
1806   assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
1807 
1808   return EvalResult.Val.getInt();
1809 }
1810