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