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