ExprConstant.cpp revision e2ca6d4a2f41876930fbd304caa706452d2569d8
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CharUnits.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/AST/StmtVisitor.h"
19#include "clang/AST/TypeLoc.h"
20#include "clang/AST/ASTDiagnostic.h"
21#include "clang/AST/Expr.h"
22#include "clang/Basic/Builtins.h"
23#include "clang/Basic/TargetInfo.h"
24#include "llvm/ADT/SmallString.h"
25#include <cstring>
26
27using namespace clang;
28using llvm::APSInt;
29using llvm::APFloat;
30
31/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded.  It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression.  If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
45struct EvalInfo {
46  ASTContext &Ctx;
47
48  /// EvalResult - Contains information about the evaluation.
49  Expr::EvalResult &EvalResult;
50
51  EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult)
52    : Ctx(ctx), EvalResult(evalresult) {}
53};
54
55namespace {
56  struct ComplexValue {
57  private:
58    bool IsInt;
59
60  public:
61    APSInt IntReal, IntImag;
62    APFloat FloatReal, FloatImag;
63
64    ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
65
66    void makeComplexFloat() { IsInt = false; }
67    bool isComplexFloat() const { return !IsInt; }
68    APFloat &getComplexFloatReal() { return FloatReal; }
69    APFloat &getComplexFloatImag() { return FloatImag; }
70
71    void makeComplexInt() { IsInt = true; }
72    bool isComplexInt() const { return IsInt; }
73    APSInt &getComplexIntReal() { return IntReal; }
74    APSInt &getComplexIntImag() { return IntImag; }
75
76    void moveInto(APValue &v) {
77      if (isComplexFloat())
78        v = APValue(FloatReal, FloatImag);
79      else
80        v = APValue(IntReal, IntImag);
81    }
82  };
83
84  struct LValue {
85    Expr *Base;
86    CharUnits Offset;
87
88    Expr *getLValueBase() { return Base; }
89    CharUnits getLValueOffset() { return Offset; }
90
91    void moveInto(APValue &v) {
92      v = APValue(Base, Offset);
93    }
94  };
95}
96
97static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
98static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
99static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
100static bool EvaluateIntegerOrLValue(const Expr *E, APValue  &Result,
101                                    EvalInfo &Info);
102static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
103static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
104
105//===----------------------------------------------------------------------===//
106// Misc utilities
107//===----------------------------------------------------------------------===//
108
109static bool IsGlobalLValue(const Expr* E) {
110  if (!E) return true;
111
112  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
113    if (isa<FunctionDecl>(DRE->getDecl()))
114      return true;
115    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
116      return VD->hasGlobalStorage();
117    return false;
118  }
119
120  if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
121    return CLE->isFileScope();
122
123  return true;
124}
125
126static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
127  const Expr* Base = Value.Base;
128
129  // A null base expression indicates a null pointer.  These are always
130  // evaluatable, and they are false unless the offset is zero.
131  if (!Base) {
132    Result = !Value.Offset.isZero();
133    return true;
134  }
135
136  // Require the base expression to be a global l-value.
137  if (!IsGlobalLValue(Base)) return false;
138
139  // We have a non-null base expression.  These are generally known to
140  // be true, but if it'a decl-ref to a weak symbol it can be null at
141  // runtime.
142  Result = true;
143
144  const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
145  if (!DeclRef)
146    return true;
147
148  // If it's a weak symbol, it isn't constant-evaluable.
149  const ValueDecl* Decl = DeclRef->getDecl();
150  if (Decl->hasAttr<WeakAttr>() ||
151      Decl->hasAttr<WeakRefAttr>() ||
152      Decl->hasAttr<WeakImportAttr>())
153    return false;
154
155  return true;
156}
157
158static bool HandleConversionToBool(const Expr* E, bool& Result,
159                                   EvalInfo &Info) {
160  if (E->getType()->isIntegralOrEnumerationType()) {
161    APSInt IntResult;
162    if (!EvaluateInteger(E, IntResult, Info))
163      return false;
164    Result = IntResult != 0;
165    return true;
166  } else if (E->getType()->isRealFloatingType()) {
167    APFloat FloatResult(0.0);
168    if (!EvaluateFloat(E, FloatResult, Info))
169      return false;
170    Result = !FloatResult.isZero();
171    return true;
172  } else if (E->getType()->hasPointerRepresentation()) {
173    LValue PointerResult;
174    if (!EvaluatePointer(E, PointerResult, Info))
175      return false;
176    return EvalPointerValueAsBool(PointerResult, Result);
177  } else if (E->getType()->isAnyComplexType()) {
178    ComplexValue ComplexResult;
179    if (!EvaluateComplex(E, ComplexResult, Info))
180      return false;
181    if (ComplexResult.isComplexFloat()) {
182      Result = !ComplexResult.getComplexFloatReal().isZero() ||
183               !ComplexResult.getComplexFloatImag().isZero();
184    } else {
185      Result = ComplexResult.getComplexIntReal().getBoolValue() ||
186               ComplexResult.getComplexIntImag().getBoolValue();
187    }
188    return true;
189  }
190
191  return false;
192}
193
194static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
195                                   APFloat &Value, ASTContext &Ctx) {
196  unsigned DestWidth = Ctx.getIntWidth(DestType);
197  // Determine whether we are converting to unsigned or signed.
198  bool DestSigned = DestType->isSignedIntegerType();
199
200  // FIXME: Warning for overflow.
201  uint64_t Space[4];
202  bool ignored;
203  (void)Value.convertToInteger(Space, DestWidth, DestSigned,
204                               llvm::APFloat::rmTowardZero, &ignored);
205  return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
206}
207
208static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
209                                      APFloat &Value, ASTContext &Ctx) {
210  bool ignored;
211  APFloat Result = Value;
212  Result.convert(Ctx.getFloatTypeSemantics(DestType),
213                 APFloat::rmNearestTiesToEven, &ignored);
214  return Result;
215}
216
217static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
218                                 APSInt &Value, ASTContext &Ctx) {
219  unsigned DestWidth = Ctx.getIntWidth(DestType);
220  APSInt Result = Value;
221  // Figure out if this is a truncate, extend or noop cast.
222  // If the input is signed, do a sign extend, noop, or truncate.
223  Result.extOrTrunc(DestWidth);
224  Result.setIsUnsigned(DestType->isUnsignedIntegerType());
225  return Result;
226}
227
228static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
229                                    APSInt &Value, ASTContext &Ctx) {
230
231  APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
232  Result.convertFromAPInt(Value, Value.isSigned(),
233                          APFloat::rmNearestTiesToEven);
234  return Result;
235}
236
237namespace {
238class HasSideEffect
239  : public StmtVisitor<HasSideEffect, bool> {
240  EvalInfo &Info;
241public:
242
243  HasSideEffect(EvalInfo &info) : Info(info) {}
244
245  // Unhandled nodes conservatively default to having side effects.
246  bool VisitStmt(Stmt *S) {
247    return true;
248  }
249
250  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
251  bool VisitDeclRefExpr(DeclRefExpr *E) {
252    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
253      return true;
254    return false;
255  }
256  // We don't want to evaluate BlockExprs multiple times, as they generate
257  // a ton of code.
258  bool VisitBlockExpr(BlockExpr *E) { return true; }
259  bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
260  bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
261    { return Visit(E->getInitializer()); }
262  bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
263  bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
264  bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
265  bool VisitStringLiteral(StringLiteral *E) { return false; }
266  bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
267  bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
268  bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
269    { return Visit(E->getLHS()) || Visit(E->getRHS()); }
270  bool VisitChooseExpr(ChooseExpr *E)
271    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
272  bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
273  bool VisitBinAssign(BinaryOperator *E) { return true; }
274  bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
275  bool VisitBinaryOperator(BinaryOperator *E)
276  { return Visit(E->getLHS()) || Visit(E->getRHS()); }
277  bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
278  bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
279  bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
280  bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
281  bool VisitUnaryDeref(UnaryOperator *E) {
282    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
283      return true;
284    return Visit(E->getSubExpr());
285  }
286  bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
287
288  // Has side effects if any element does.
289  bool VisitInitListExpr(InitListExpr *E) {
290    for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
291      if (Visit(E->getInit(i))) return true;
292    return false;
293  }
294};
295
296} // end anonymous namespace
297
298//===----------------------------------------------------------------------===//
299// LValue Evaluation
300//===----------------------------------------------------------------------===//
301namespace {
302class LValueExprEvaluator
303  : public StmtVisitor<LValueExprEvaluator, bool> {
304  EvalInfo &Info;
305  LValue &Result;
306
307  bool Success(Expr *E) {
308    Result.Base = E;
309    Result.Offset = CharUnits::Zero();
310    return true;
311  }
312public:
313
314  LValueExprEvaluator(EvalInfo &info, LValue &Result) :
315    Info(info), Result(Result) {}
316
317  bool VisitStmt(Stmt *S) {
318    return false;
319  }
320
321  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
322  bool VisitDeclRefExpr(DeclRefExpr *E);
323  bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
324  bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
325  bool VisitMemberExpr(MemberExpr *E);
326  bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
327  bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
328  bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
329  bool VisitUnaryDeref(UnaryOperator *E);
330  bool VisitUnaryExtension(const UnaryOperator *E)
331    { return Visit(E->getSubExpr()); }
332  bool VisitChooseExpr(const ChooseExpr *E)
333    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
334
335  bool VisitCastExpr(CastExpr *E) {
336    switch (E->getCastKind()) {
337    default:
338      return false;
339
340    case CK_NoOp:
341      return Visit(E->getSubExpr());
342    }
343  }
344  // FIXME: Missing: __real__, __imag__
345};
346} // end anonymous namespace
347
348static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
349  return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
350}
351
352bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
353  if (isa<FunctionDecl>(E->getDecl())) {
354    return Success(E);
355  } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
356    if (!VD->getType()->isReferenceType())
357      return Success(E);
358    // Reference parameters can refer to anything even if they have an
359    // "initializer" in the form of a default argument.
360    if (isa<ParmVarDecl>(VD))
361      return false;
362    // FIXME: Check whether VD might be overridden!
363    if (const Expr *Init = VD->getAnyInitializer())
364      return Visit(const_cast<Expr *>(Init));
365  }
366
367  return false;
368}
369
370bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
371  return Success(E);
372}
373
374bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
375  QualType Ty;
376  if (E->isArrow()) {
377    if (!EvaluatePointer(E->getBase(), Result, Info))
378      return false;
379    Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
380  } else {
381    if (!Visit(E->getBase()))
382      return false;
383    Ty = E->getBase()->getType();
384  }
385
386  RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
387  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
388
389  FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
390  if (!FD) // FIXME: deal with other kinds of member expressions
391    return false;
392
393  if (FD->getType()->isReferenceType())
394    return false;
395
396  // FIXME: This is linear time.
397  unsigned i = 0;
398  for (RecordDecl::field_iterator Field = RD->field_begin(),
399                               FieldEnd = RD->field_end();
400       Field != FieldEnd; (void)++Field, ++i) {
401    if (*Field == FD)
402      break;
403  }
404
405  Result.Offset += CharUnits::fromQuantity(RL.getFieldOffset(i) / 8);
406  return true;
407}
408
409bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
410  if (!EvaluatePointer(E->getBase(), Result, Info))
411    return false;
412
413  APSInt Index;
414  if (!EvaluateInteger(E->getIdx(), Index, Info))
415    return false;
416
417  CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
418  Result.Offset += Index.getSExtValue() * ElementSize;
419  return true;
420}
421
422bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
423  return EvaluatePointer(E->getSubExpr(), Result, Info);
424}
425
426//===----------------------------------------------------------------------===//
427// Pointer Evaluation
428//===----------------------------------------------------------------------===//
429
430namespace {
431class PointerExprEvaluator
432  : public StmtVisitor<PointerExprEvaluator, bool> {
433  EvalInfo &Info;
434  LValue &Result;
435
436  bool Success(Expr *E) {
437    Result.Base = E;
438    Result.Offset = CharUnits::Zero();
439    return true;
440  }
441public:
442
443  PointerExprEvaluator(EvalInfo &info, LValue &Result)
444    : Info(info), Result(Result) {}
445
446  bool VisitStmt(Stmt *S) {
447    return false;
448  }
449
450  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
451
452  bool VisitBinaryOperator(const BinaryOperator *E);
453  bool VisitCastExpr(CastExpr* E);
454  bool VisitUnaryExtension(const UnaryOperator *E)
455      { return Visit(E->getSubExpr()); }
456  bool VisitUnaryAddrOf(const UnaryOperator *E);
457  bool VisitObjCStringLiteral(ObjCStringLiteral *E)
458      { return Success(E); }
459  bool VisitAddrLabelExpr(AddrLabelExpr *E)
460      { return Success(E); }
461  bool VisitCallExpr(CallExpr *E);
462  bool VisitBlockExpr(BlockExpr *E) {
463    if (!E->hasBlockDeclRefExprs())
464      return Success(E);
465    return false;
466  }
467  bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
468      { return Success((Expr*)0); }
469  bool VisitConditionalOperator(ConditionalOperator *E);
470  bool VisitChooseExpr(ChooseExpr *E)
471      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
472  bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
473      { return Success((Expr*)0); }
474  // FIXME: Missing: @protocol, @selector
475};
476} // end anonymous namespace
477
478static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
479  assert(E->getType()->hasPointerRepresentation());
480  return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
481}
482
483bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
484  if (E->getOpcode() != BO_Add &&
485      E->getOpcode() != BO_Sub)
486    return false;
487
488  const Expr *PExp = E->getLHS();
489  const Expr *IExp = E->getRHS();
490  if (IExp->getType()->isPointerType())
491    std::swap(PExp, IExp);
492
493  if (!EvaluatePointer(PExp, Result, Info))
494    return false;
495
496  llvm::APSInt Offset;
497  if (!EvaluateInteger(IExp, Offset, Info))
498    return false;
499  int64_t AdditionalOffset
500    = Offset.isSigned() ? Offset.getSExtValue()
501                        : static_cast<int64_t>(Offset.getZExtValue());
502
503  // Compute the new offset in the appropriate width.
504
505  QualType PointeeType =
506    PExp->getType()->getAs<PointerType>()->getPointeeType();
507  CharUnits SizeOfPointee;
508
509  // Explicitly handle GNU void* and function pointer arithmetic extensions.
510  if (PointeeType->isVoidType() || PointeeType->isFunctionType())
511    SizeOfPointee = CharUnits::One();
512  else
513    SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
514
515  if (E->getOpcode() == BO_Add)
516    Result.Offset += AdditionalOffset * SizeOfPointee;
517  else
518    Result.Offset -= AdditionalOffset * SizeOfPointee;
519
520  return true;
521}
522
523bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
524  return EvaluateLValue(E->getSubExpr(), Result, Info);
525}
526
527
528bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
529  Expr* SubExpr = E->getSubExpr();
530
531  switch (E->getCastKind()) {
532  default:
533    break;
534
535  case CK_Unknown: {
536    // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
537
538    // Check for pointer->pointer cast
539    if (SubExpr->getType()->isPointerType() ||
540        SubExpr->getType()->isObjCObjectPointerType() ||
541        SubExpr->getType()->isNullPtrType() ||
542        SubExpr->getType()->isBlockPointerType())
543      return Visit(SubExpr);
544
545    if (SubExpr->getType()->isIntegralOrEnumerationType()) {
546      APValue Value;
547      if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
548        break;
549
550      if (Value.isInt()) {
551        Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
552        Result.Base = 0;
553        Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
554        return true;
555      } else {
556        Result.Base = Value.getLValueBase();
557        Result.Offset = Value.getLValueOffset();
558        return true;
559      }
560    }
561    break;
562  }
563
564  case CK_NoOp:
565  case CK_BitCast:
566  case CK_LValueBitCast:
567  case CK_AnyPointerToObjCPointerCast:
568  case CK_AnyPointerToBlockPointerCast:
569    return Visit(SubExpr);
570
571  case CK_IntegralToPointer: {
572    APValue Value;
573    if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
574      break;
575
576    if (Value.isInt()) {
577      Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
578      Result.Base = 0;
579      Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
580      return true;
581    } else {
582      // Cast is of an lvalue, no need to change value.
583      Result.Base = Value.getLValueBase();
584      Result.Offset = Value.getLValueOffset();
585      return true;
586    }
587  }
588  case CK_ArrayToPointerDecay:
589  case CK_FunctionToPointerDecay:
590    return EvaluateLValue(SubExpr, Result, Info);
591  }
592
593  return false;
594}
595
596bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
597  if (E->isBuiltinCall(Info.Ctx) ==
598        Builtin::BI__builtin___CFStringMakeConstantString ||
599      E->isBuiltinCall(Info.Ctx) ==
600        Builtin::BI__builtin___NSStringMakeConstantString)
601    return Success(E);
602  return false;
603}
604
605bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
606  bool BoolResult;
607  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
608    return false;
609
610  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
611  return Visit(EvalExpr);
612}
613
614//===----------------------------------------------------------------------===//
615// Vector Evaluation
616//===----------------------------------------------------------------------===//
617
618namespace {
619  class VectorExprEvaluator
620  : public StmtVisitor<VectorExprEvaluator, APValue> {
621    EvalInfo &Info;
622    APValue GetZeroVector(QualType VecType);
623  public:
624
625    VectorExprEvaluator(EvalInfo &info) : Info(info) {}
626
627    APValue VisitStmt(Stmt *S) {
628      return APValue();
629    }
630
631    APValue VisitParenExpr(ParenExpr *E)
632        { return Visit(E->getSubExpr()); }
633    APValue VisitUnaryExtension(const UnaryOperator *E)
634      { return Visit(E->getSubExpr()); }
635    APValue VisitUnaryPlus(const UnaryOperator *E)
636      { return Visit(E->getSubExpr()); }
637    APValue VisitUnaryReal(const UnaryOperator *E)
638      { return Visit(E->getSubExpr()); }
639    APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
640      { return GetZeroVector(E->getType()); }
641    APValue VisitCastExpr(const CastExpr* E);
642    APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
643    APValue VisitInitListExpr(const InitListExpr *E);
644    APValue VisitConditionalOperator(const ConditionalOperator *E);
645    APValue VisitChooseExpr(const ChooseExpr *E)
646      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
647    APValue VisitUnaryImag(const UnaryOperator *E);
648    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
649    //                 binary comparisons, binary and/or/xor,
650    //                 shufflevector, ExtVectorElementExpr
651    //        (Note that these require implementing conversions
652    //         between vector types.)
653  };
654} // end anonymous namespace
655
656static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
657  if (!E->getType()->isVectorType())
658    return false;
659  Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
660  return !Result.isUninit();
661}
662
663APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
664  const VectorType *VTy = E->getType()->getAs<VectorType>();
665  QualType EltTy = VTy->getElementType();
666  unsigned NElts = VTy->getNumElements();
667  unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
668
669  const Expr* SE = E->getSubExpr();
670  QualType SETy = SE->getType();
671  APValue Result = APValue();
672
673  // Check for vector->vector bitcast and scalar->vector splat.
674  if (SETy->isVectorType()) {
675    return this->Visit(const_cast<Expr*>(SE));
676  } else if (SETy->isIntegerType()) {
677    APSInt IntResult;
678    if (!EvaluateInteger(SE, IntResult, Info))
679      return APValue();
680    Result = APValue(IntResult);
681  } else if (SETy->isRealFloatingType()) {
682    APFloat F(0.0);
683    if (!EvaluateFloat(SE, F, Info))
684      return APValue();
685    Result = APValue(F);
686  } else
687    return APValue();
688
689  // For casts of a scalar to ExtVector, convert the scalar to the element type
690  // and splat it to all elements.
691  if (E->getType()->isExtVectorType()) {
692    if (EltTy->isIntegerType() && Result.isInt())
693      Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
694                                          Info.Ctx));
695    else if (EltTy->isIntegerType())
696      Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
697                                            Info.Ctx));
698    else if (EltTy->isRealFloatingType() && Result.isInt())
699      Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
700                                            Info.Ctx));
701    else if (EltTy->isRealFloatingType())
702      Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
703                                              Info.Ctx));
704    else
705      return APValue();
706
707    // Splat and create vector APValue.
708    llvm::SmallVector<APValue, 4> Elts(NElts, Result);
709    return APValue(&Elts[0], Elts.size());
710  }
711
712  // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
713  // to the vector. To construct the APValue vector initializer, bitcast the
714  // initializing value to an APInt, and shift out the bits pertaining to each
715  // element.
716  APSInt Init;
717  Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
718
719  llvm::SmallVector<APValue, 4> Elts;
720  for (unsigned i = 0; i != NElts; ++i) {
721    APSInt Tmp = Init;
722    Tmp.extOrTrunc(EltWidth);
723
724    if (EltTy->isIntegerType())
725      Elts.push_back(APValue(Tmp));
726    else if (EltTy->isRealFloatingType())
727      Elts.push_back(APValue(APFloat(Tmp)));
728    else
729      return APValue();
730
731    Init >>= EltWidth;
732  }
733  return APValue(&Elts[0], Elts.size());
734}
735
736APValue
737VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
738  return this->Visit(const_cast<Expr*>(E->getInitializer()));
739}
740
741APValue
742VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
743  const VectorType *VT = E->getType()->getAs<VectorType>();
744  unsigned NumInits = E->getNumInits();
745  unsigned NumElements = VT->getNumElements();
746
747  QualType EltTy = VT->getElementType();
748  llvm::SmallVector<APValue, 4> Elements;
749
750  // If a vector is initialized with a single element, that value
751  // becomes every element of the vector, not just the first.
752  // This is the behavior described in the IBM AltiVec documentation.
753  if (NumInits == 1) {
754    APValue InitValue;
755    if (EltTy->isIntegerType()) {
756      llvm::APSInt sInt(32);
757      if (!EvaluateInteger(E->getInit(0), sInt, Info))
758        return APValue();
759      InitValue = APValue(sInt);
760    } else {
761      llvm::APFloat f(0.0);
762      if (!EvaluateFloat(E->getInit(0), f, Info))
763        return APValue();
764      InitValue = APValue(f);
765    }
766    for (unsigned i = 0; i < NumElements; i++) {
767      Elements.push_back(InitValue);
768    }
769  } else {
770    for (unsigned i = 0; i < NumElements; i++) {
771      if (EltTy->isIntegerType()) {
772        llvm::APSInt sInt(32);
773        if (i < NumInits) {
774          if (!EvaluateInteger(E->getInit(i), sInt, Info))
775            return APValue();
776        } else {
777          sInt = Info.Ctx.MakeIntValue(0, EltTy);
778        }
779        Elements.push_back(APValue(sInt));
780      } else {
781        llvm::APFloat f(0.0);
782        if (i < NumInits) {
783          if (!EvaluateFloat(E->getInit(i), f, Info))
784            return APValue();
785        } else {
786          f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
787        }
788        Elements.push_back(APValue(f));
789      }
790    }
791  }
792  return APValue(&Elements[0], Elements.size());
793}
794
795APValue
796VectorExprEvaluator::GetZeroVector(QualType T) {
797  const VectorType *VT = T->getAs<VectorType>();
798  QualType EltTy = VT->getElementType();
799  APValue ZeroElement;
800  if (EltTy->isIntegerType())
801    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
802  else
803    ZeroElement =
804        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
805
806  llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
807  return APValue(&Elements[0], Elements.size());
808}
809
810APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
811  bool BoolResult;
812  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
813    return APValue();
814
815  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
816
817  APValue Result;
818  if (EvaluateVector(EvalExpr, Result, Info))
819    return Result;
820  return APValue();
821}
822
823APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
824  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
825    Info.EvalResult.HasSideEffects = true;
826  return GetZeroVector(E->getType());
827}
828
829//===----------------------------------------------------------------------===//
830// Integer Evaluation
831//===----------------------------------------------------------------------===//
832
833namespace {
834class IntExprEvaluator
835  : public StmtVisitor<IntExprEvaluator, bool> {
836  EvalInfo &Info;
837  APValue &Result;
838public:
839  IntExprEvaluator(EvalInfo &info, APValue &result)
840    : Info(info), Result(result) {}
841
842  bool Success(const llvm::APSInt &SI, const Expr *E) {
843    assert(E->getType()->isIntegralOrEnumerationType() &&
844           "Invalid evaluation result.");
845    assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
846           "Invalid evaluation result.");
847    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
848           "Invalid evaluation result.");
849    Result = APValue(SI);
850    return true;
851  }
852
853  bool Success(const llvm::APInt &I, const Expr *E) {
854    assert(E->getType()->isIntegralOrEnumerationType() &&
855           "Invalid evaluation result.");
856    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
857           "Invalid evaluation result.");
858    Result = APValue(APSInt(I));
859    Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
860    return true;
861  }
862
863  bool Success(uint64_t Value, const Expr *E) {
864    assert(E->getType()->isIntegralOrEnumerationType() &&
865           "Invalid evaluation result.");
866    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
867    return true;
868  }
869
870  bool Error(SourceLocation L, diag::kind D, const Expr *E) {
871    // Take the first error.
872    if (Info.EvalResult.Diag == 0) {
873      Info.EvalResult.DiagLoc = L;
874      Info.EvalResult.Diag = D;
875      Info.EvalResult.DiagExpr = E;
876    }
877    return false;
878  }
879
880  //===--------------------------------------------------------------------===//
881  //                            Visitor Methods
882  //===--------------------------------------------------------------------===//
883
884  bool VisitStmt(Stmt *) {
885    assert(0 && "This should be called on integers, stmts are not integers");
886    return false;
887  }
888
889  bool VisitExpr(Expr *E) {
890    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
891  }
892
893  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
894
895  bool VisitIntegerLiteral(const IntegerLiteral *E) {
896    return Success(E->getValue(), E);
897  }
898  bool VisitCharacterLiteral(const CharacterLiteral *E) {
899    return Success(E->getValue(), E);
900  }
901  bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
902    // Per gcc docs "this built-in function ignores top level
903    // qualifiers".  We need to use the canonical version to properly
904    // be able to strip CRV qualifiers from the type.
905    QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
906    QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
907    return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
908                                               T1.getUnqualifiedType()),
909                   E);
910  }
911
912  bool CheckReferencedDecl(const Expr *E, const Decl *D);
913  bool VisitDeclRefExpr(const DeclRefExpr *E) {
914    return CheckReferencedDecl(E, E->getDecl());
915  }
916  bool VisitMemberExpr(const MemberExpr *E) {
917    if (CheckReferencedDecl(E, E->getMemberDecl())) {
918      // Conservatively assume a MemberExpr will have side-effects
919      Info.EvalResult.HasSideEffects = true;
920      return true;
921    }
922    return false;
923  }
924
925  bool VisitCallExpr(CallExpr *E);
926  bool VisitBinaryOperator(const BinaryOperator *E);
927  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
928  bool VisitUnaryOperator(const UnaryOperator *E);
929  bool VisitConditionalOperator(const ConditionalOperator *E);
930
931  bool VisitCastExpr(CastExpr* E);
932  bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
933
934  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
935    return Success(E->getValue(), E);
936  }
937
938  bool VisitGNUNullExpr(const GNUNullExpr *E) {
939    return Success(0, E);
940  }
941
942  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
943    return Success(0, E);
944  }
945
946  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
947    return Success(0, E);
948  }
949
950  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
951    return Success(E->EvaluateTrait(Info.Ctx), E);
952  }
953
954  bool VisitChooseExpr(const ChooseExpr *E) {
955    return Visit(E->getChosenSubExpr(Info.Ctx));
956  }
957
958  bool VisitUnaryReal(const UnaryOperator *E);
959  bool VisitUnaryImag(const UnaryOperator *E);
960
961private:
962  CharUnits GetAlignOfExpr(const Expr *E);
963  CharUnits GetAlignOfType(QualType T);
964  static QualType GetObjectType(const Expr *E);
965  bool TryEvaluateBuiltinObjectSize(CallExpr *E);
966  // FIXME: Missing: array subscript of vector, member of vector
967};
968} // end anonymous namespace
969
970static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
971  assert(E->getType()->isIntegralOrEnumerationType());
972  return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
973}
974
975static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
976  assert(E->getType()->isIntegralOrEnumerationType());
977
978  APValue Val;
979  if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
980    return false;
981  Result = Val.getInt();
982  return true;
983}
984
985bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
986  // Enums are integer constant exprs.
987  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
988    return Success(ECD->getInitVal(), E);
989
990  // In C++, const, non-volatile integers initialized with ICEs are ICEs.
991  // In C, they can also be folded, although they are not ICEs.
992  if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
993                                                        == Qualifiers::Const) {
994
995    if (isa<ParmVarDecl>(D))
996      return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
997
998    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
999      if (const Expr *Init = VD->getAnyInitializer()) {
1000        if (APValue *V = VD->getEvaluatedValue()) {
1001          if (V->isInt())
1002            return Success(V->getInt(), E);
1003          return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1004        }
1005
1006        if (VD->isEvaluatingValue())
1007          return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1008
1009        VD->setEvaluatingValue();
1010
1011        if (Visit(const_cast<Expr*>(Init))) {
1012          // Cache the evaluated value in the variable declaration.
1013          VD->setEvaluatedValue(Result);
1014          return true;
1015        }
1016
1017        VD->setEvaluatedValue(APValue());
1018        return false;
1019      }
1020    }
1021  }
1022
1023  // Otherwise, random variable references are not constants.
1024  return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1025}
1026
1027/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1028/// as GCC.
1029static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1030  // The following enum mimics the values returned by GCC.
1031  // FIXME: Does GCC differ between lvalue and rvalue references here?
1032  enum gcc_type_class {
1033    no_type_class = -1,
1034    void_type_class, integer_type_class, char_type_class,
1035    enumeral_type_class, boolean_type_class,
1036    pointer_type_class, reference_type_class, offset_type_class,
1037    real_type_class, complex_type_class,
1038    function_type_class, method_type_class,
1039    record_type_class, union_type_class,
1040    array_type_class, string_type_class,
1041    lang_type_class
1042  };
1043
1044  // If no argument was supplied, default to "no_type_class". This isn't
1045  // ideal, however it is what gcc does.
1046  if (E->getNumArgs() == 0)
1047    return no_type_class;
1048
1049  QualType ArgTy = E->getArg(0)->getType();
1050  if (ArgTy->isVoidType())
1051    return void_type_class;
1052  else if (ArgTy->isEnumeralType())
1053    return enumeral_type_class;
1054  else if (ArgTy->isBooleanType())
1055    return boolean_type_class;
1056  else if (ArgTy->isCharType())
1057    return string_type_class; // gcc doesn't appear to use char_type_class
1058  else if (ArgTy->isIntegerType())
1059    return integer_type_class;
1060  else if (ArgTy->isPointerType())
1061    return pointer_type_class;
1062  else if (ArgTy->isReferenceType())
1063    return reference_type_class;
1064  else if (ArgTy->isRealType())
1065    return real_type_class;
1066  else if (ArgTy->isComplexType())
1067    return complex_type_class;
1068  else if (ArgTy->isFunctionType())
1069    return function_type_class;
1070  else if (ArgTy->isStructureOrClassType())
1071    return record_type_class;
1072  else if (ArgTy->isUnionType())
1073    return union_type_class;
1074  else if (ArgTy->isArrayType())
1075    return array_type_class;
1076  else if (ArgTy->isUnionType())
1077    return union_type_class;
1078  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
1079    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1080  return -1;
1081}
1082
1083/// Retrieves the "underlying object type" of the given expression,
1084/// as used by __builtin_object_size.
1085QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1086  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1087    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1088      return VD->getType();
1089  } else if (isa<CompoundLiteralExpr>(E)) {
1090    return E->getType();
1091  }
1092
1093  return QualType();
1094}
1095
1096bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1097  // TODO: Perhaps we should let LLVM lower this?
1098  LValue Base;
1099  if (!EvaluatePointer(E->getArg(0), Base, Info))
1100    return false;
1101
1102  // If we can prove the base is null, lower to zero now.
1103  const Expr *LVBase = Base.getLValueBase();
1104  if (!LVBase) return Success(0, E);
1105
1106  QualType T = GetObjectType(LVBase);
1107  if (T.isNull() ||
1108      T->isIncompleteType() ||
1109      T->isFunctionType() ||
1110      T->isVariablyModifiedType() ||
1111      T->isDependentType())
1112    return false;
1113
1114  CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1115  CharUnits Offset = Base.getLValueOffset();
1116
1117  if (!Offset.isNegative() && Offset <= Size)
1118    Size -= Offset;
1119  else
1120    Size = CharUnits::Zero();
1121  return Success(Size.getQuantity(), E);
1122}
1123
1124bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
1125  switch (E->isBuiltinCall(Info.Ctx)) {
1126  default:
1127    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1128
1129  case Builtin::BI__builtin_object_size: {
1130    if (TryEvaluateBuiltinObjectSize(E))
1131      return true;
1132
1133    // If evaluating the argument has side-effects we can't determine
1134    // the size of the object and lower it to unknown now.
1135    if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
1136      if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
1137        return Success(-1ULL, E);
1138      return Success(0, E);
1139    }
1140
1141    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1142  }
1143
1144  case Builtin::BI__builtin_classify_type:
1145    return Success(EvaluateBuiltinClassifyType(E), E);
1146
1147  case Builtin::BI__builtin_constant_p:
1148    // __builtin_constant_p always has one operand: it returns true if that
1149    // operand can be folded, false otherwise.
1150    return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
1151
1152  case Builtin::BI__builtin_eh_return_data_regno: {
1153    int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1154    Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1155    return Success(Operand, E);
1156  }
1157
1158  case Builtin::BI__builtin_expect:
1159    return Visit(E->getArg(0));
1160  }
1161}
1162
1163bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1164  if (E->getOpcode() == BO_Comma) {
1165    if (!Visit(E->getRHS()))
1166      return false;
1167
1168    // If we can't evaluate the LHS, it might have side effects;
1169    // conservatively mark it.
1170    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1171      Info.EvalResult.HasSideEffects = true;
1172
1173    return true;
1174  }
1175
1176  if (E->isLogicalOp()) {
1177    // These need to be handled specially because the operands aren't
1178    // necessarily integral
1179    bool lhsResult, rhsResult;
1180
1181    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
1182      // We were able to evaluate the LHS, see if we can get away with not
1183      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1184      if (lhsResult == (E->getOpcode() == BO_LOr))
1185        return Success(lhsResult, E);
1186
1187      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1188        if (E->getOpcode() == BO_LOr)
1189          return Success(lhsResult || rhsResult, E);
1190        else
1191          return Success(lhsResult && rhsResult, E);
1192      }
1193    } else {
1194      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1195        // We can't evaluate the LHS; however, sometimes the result
1196        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1197        if (rhsResult == (E->getOpcode() == BO_LOr) ||
1198            !rhsResult == (E->getOpcode() == BO_LAnd)) {
1199          // Since we weren't able to evaluate the left hand side, it
1200          // must have had side effects.
1201          Info.EvalResult.HasSideEffects = true;
1202
1203          return Success(rhsResult, E);
1204        }
1205      }
1206    }
1207
1208    return false;
1209  }
1210
1211  QualType LHSTy = E->getLHS()->getType();
1212  QualType RHSTy = E->getRHS()->getType();
1213
1214  if (LHSTy->isAnyComplexType()) {
1215    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1216    ComplexValue LHS, RHS;
1217
1218    if (!EvaluateComplex(E->getLHS(), LHS, Info))
1219      return false;
1220
1221    if (!EvaluateComplex(E->getRHS(), RHS, Info))
1222      return false;
1223
1224    if (LHS.isComplexFloat()) {
1225      APFloat::cmpResult CR_r =
1226        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
1227      APFloat::cmpResult CR_i =
1228        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1229
1230      if (E->getOpcode() == BO_EQ)
1231        return Success((CR_r == APFloat::cmpEqual &&
1232                        CR_i == APFloat::cmpEqual), E);
1233      else {
1234        assert(E->getOpcode() == BO_NE &&
1235               "Invalid complex comparison.");
1236        return Success(((CR_r == APFloat::cmpGreaterThan ||
1237                         CR_r == APFloat::cmpLessThan ||
1238                         CR_r == APFloat::cmpUnordered) ||
1239                        (CR_i == APFloat::cmpGreaterThan ||
1240                         CR_i == APFloat::cmpLessThan ||
1241                         CR_i == APFloat::cmpUnordered)), E);
1242      }
1243    } else {
1244      if (E->getOpcode() == BO_EQ)
1245        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1246                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1247      else {
1248        assert(E->getOpcode() == BO_NE &&
1249               "Invalid compex comparison.");
1250        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1251                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1252      }
1253    }
1254  }
1255
1256  if (LHSTy->isRealFloatingType() &&
1257      RHSTy->isRealFloatingType()) {
1258    APFloat RHS(0.0), LHS(0.0);
1259
1260    if (!EvaluateFloat(E->getRHS(), RHS, Info))
1261      return false;
1262
1263    if (!EvaluateFloat(E->getLHS(), LHS, Info))
1264      return false;
1265
1266    APFloat::cmpResult CR = LHS.compare(RHS);
1267
1268    switch (E->getOpcode()) {
1269    default:
1270      assert(0 && "Invalid binary operator!");
1271    case BO_LT:
1272      return Success(CR == APFloat::cmpLessThan, E);
1273    case BO_GT:
1274      return Success(CR == APFloat::cmpGreaterThan, E);
1275    case BO_LE:
1276      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
1277    case BO_GE:
1278      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
1279                     E);
1280    case BO_EQ:
1281      return Success(CR == APFloat::cmpEqual, E);
1282    case BO_NE:
1283      return Success(CR == APFloat::cmpGreaterThan
1284                     || CR == APFloat::cmpLessThan
1285                     || CR == APFloat::cmpUnordered, E);
1286    }
1287  }
1288
1289  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1290    if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
1291      LValue LHSValue;
1292      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1293        return false;
1294
1295      LValue RHSValue;
1296      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1297        return false;
1298
1299      // Reject any bases from the normal codepath; we special-case comparisons
1300      // to null.
1301      if (LHSValue.getLValueBase()) {
1302        if (!E->isEqualityOp())
1303          return false;
1304        if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
1305          return false;
1306        bool bres;
1307        if (!EvalPointerValueAsBool(LHSValue, bres))
1308          return false;
1309        return Success(bres ^ (E->getOpcode() == BO_EQ), E);
1310      } else if (RHSValue.getLValueBase()) {
1311        if (!E->isEqualityOp())
1312          return false;
1313        if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
1314          return false;
1315        bool bres;
1316        if (!EvalPointerValueAsBool(RHSValue, bres))
1317          return false;
1318        return Success(bres ^ (E->getOpcode() == BO_EQ), E);
1319      }
1320
1321      if (E->getOpcode() == BO_Sub) {
1322        QualType Type = E->getLHS()->getType();
1323        QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
1324
1325        CharUnits ElementSize = CharUnits::One();
1326        if (!ElementType->isVoidType() && !ElementType->isFunctionType())
1327          ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
1328
1329        CharUnits Diff = LHSValue.getLValueOffset() -
1330                             RHSValue.getLValueOffset();
1331        return Success(Diff / ElementSize, E);
1332      }
1333      bool Result;
1334      if (E->getOpcode() == BO_EQ) {
1335        Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
1336      } else {
1337        Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1338      }
1339      return Success(Result, E);
1340    }
1341  }
1342  if (!LHSTy->isIntegralOrEnumerationType() ||
1343      !RHSTy->isIntegralOrEnumerationType()) {
1344    // We can't continue from here for non-integral types, and they
1345    // could potentially confuse the following operations.
1346    return false;
1347  }
1348
1349  // The LHS of a constant expr is always evaluated and needed.
1350  if (!Visit(E->getLHS()))
1351    return false; // error in subexpression.
1352
1353  APValue RHSVal;
1354  if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1355    return false;
1356
1357  // Handle cases like (unsigned long)&a + 4.
1358  if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1359    CharUnits Offset = Result.getLValueOffset();
1360    CharUnits AdditionalOffset = CharUnits::fromQuantity(
1361                                     RHSVal.getInt().getZExtValue());
1362    if (E->getOpcode() == BO_Add)
1363      Offset += AdditionalOffset;
1364    else
1365      Offset -= AdditionalOffset;
1366    Result = APValue(Result.getLValueBase(), Offset);
1367    return true;
1368  }
1369
1370  // Handle cases like 4 + (unsigned long)&a
1371  if (E->getOpcode() == BO_Add &&
1372        RHSVal.isLValue() && Result.isInt()) {
1373    CharUnits Offset = RHSVal.getLValueOffset();
1374    Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1375    Result = APValue(RHSVal.getLValueBase(), Offset);
1376    return true;
1377  }
1378
1379  // All the following cases expect both operands to be an integer
1380  if (!Result.isInt() || !RHSVal.isInt())
1381    return false;
1382
1383  APSInt& RHS = RHSVal.getInt();
1384
1385  switch (E->getOpcode()) {
1386  default:
1387    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1388  case BO_Mul: return Success(Result.getInt() * RHS, E);
1389  case BO_Add: return Success(Result.getInt() + RHS, E);
1390  case BO_Sub: return Success(Result.getInt() - RHS, E);
1391  case BO_And: return Success(Result.getInt() & RHS, E);
1392  case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1393  case BO_Or:  return Success(Result.getInt() | RHS, E);
1394  case BO_Div:
1395    if (RHS == 0)
1396      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1397    return Success(Result.getInt() / RHS, E);
1398  case BO_Rem:
1399    if (RHS == 0)
1400      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1401    return Success(Result.getInt() % RHS, E);
1402  case BO_Shl: {
1403    // FIXME: Warn about out of range shift amounts!
1404    unsigned SA =
1405      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1406    return Success(Result.getInt() << SA, E);
1407  }
1408  case BO_Shr: {
1409    unsigned SA =
1410      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1411    return Success(Result.getInt() >> SA, E);
1412  }
1413
1414  case BO_LT: return Success(Result.getInt() < RHS, E);
1415  case BO_GT: return Success(Result.getInt() > RHS, E);
1416  case BO_LE: return Success(Result.getInt() <= RHS, E);
1417  case BO_GE: return Success(Result.getInt() >= RHS, E);
1418  case BO_EQ: return Success(Result.getInt() == RHS, E);
1419  case BO_NE: return Success(Result.getInt() != RHS, E);
1420  }
1421}
1422
1423bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1424  bool Cond;
1425  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1426    return false;
1427
1428  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1429}
1430
1431CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
1432  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1433  //   the result is the size of the referenced type."
1434  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1435  //   result shall be the alignment of the referenced type."
1436  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1437    T = Ref->getPointeeType();
1438
1439  // Get information about the alignment.
1440  unsigned CharSize = Info.Ctx.Target.getCharWidth();
1441
1442  // __alignof is defined to return the preferred alignment.
1443  return CharUnits::fromQuantity(
1444      Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
1445}
1446
1447CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1448  E = E->IgnoreParens();
1449
1450  // alignof decl is always accepted, even if it doesn't make sense: we default
1451  // to 1 in those cases.
1452  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1453    return Info.Ctx.getDeclAlign(DRE->getDecl(),
1454                                 /*RefAsPointee*/true);
1455
1456  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1457    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1458                                 /*RefAsPointee*/true);
1459
1460  return GetAlignOfType(E->getType());
1461}
1462
1463
1464/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1465/// expression's type.
1466bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1467  // Handle alignof separately.
1468  if (!E->isSizeOf()) {
1469    if (E->isArgumentType())
1470      return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
1471    else
1472      return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
1473  }
1474
1475  QualType SrcTy = E->getTypeOfArgument();
1476  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1477  //   the result is the size of the referenced type."
1478  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1479  //   result shall be the alignment of the referenced type."
1480  if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1481    SrcTy = Ref->getPointeeType();
1482
1483  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1484  // extension.
1485  if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1486    return Success(1, E);
1487
1488  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1489  if (!SrcTy->isConstantSizeType())
1490    return false;
1491
1492  // Get information about the size.
1493  return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
1494}
1495
1496bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1497  CharUnits Result;
1498  unsigned n = E->getNumComponents();
1499  OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1500  if (n == 0)
1501    return false;
1502  QualType CurrentType = E->getTypeSourceInfo()->getType();
1503  for (unsigned i = 0; i != n; ++i) {
1504    OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1505    switch (ON.getKind()) {
1506    case OffsetOfExpr::OffsetOfNode::Array: {
1507      Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1508      APSInt IdxResult;
1509      if (!EvaluateInteger(Idx, IdxResult, Info))
1510        return false;
1511      const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1512      if (!AT)
1513        return false;
1514      CurrentType = AT->getElementType();
1515      CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1516      Result += IdxResult.getSExtValue() * ElementSize;
1517        break;
1518    }
1519
1520    case OffsetOfExpr::OffsetOfNode::Field: {
1521      FieldDecl *MemberDecl = ON.getField();
1522      const RecordType *RT = CurrentType->getAs<RecordType>();
1523      if (!RT)
1524        return false;
1525      RecordDecl *RD = RT->getDecl();
1526      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1527      unsigned i = 0;
1528      // FIXME: It would be nice if we didn't have to loop here!
1529      for (RecordDecl::field_iterator Field = RD->field_begin(),
1530                                      FieldEnd = RD->field_end();
1531           Field != FieldEnd; (void)++Field, ++i) {
1532        if (*Field == MemberDecl)
1533          break;
1534      }
1535      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1536      Result += CharUnits::fromQuantity(
1537                           RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
1538      CurrentType = MemberDecl->getType().getNonReferenceType();
1539      break;
1540    }
1541
1542    case OffsetOfExpr::OffsetOfNode::Identifier:
1543      llvm_unreachable("dependent __builtin_offsetof");
1544      return false;
1545
1546    case OffsetOfExpr::OffsetOfNode::Base: {
1547      CXXBaseSpecifier *BaseSpec = ON.getBase();
1548      if (BaseSpec->isVirtual())
1549        return false;
1550
1551      // Find the layout of the class whose base we are looking into.
1552      const RecordType *RT = CurrentType->getAs<RecordType>();
1553      if (!RT)
1554        return false;
1555      RecordDecl *RD = RT->getDecl();
1556      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1557
1558      // Find the base class itself.
1559      CurrentType = BaseSpec->getType();
1560      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1561      if (!BaseRT)
1562        return false;
1563
1564      // Add the offset to the base.
1565      Result += CharUnits::fromQuantity(
1566                RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1567                                        / Info.Ctx.getCharWidth());
1568      break;
1569    }
1570    }
1571  }
1572  return Success(Result.getQuantity(), E);
1573}
1574
1575bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1576  if (E->getOpcode() == UO_LNot) {
1577    // LNot's operand isn't necessarily an integer, so we handle it specially.
1578    bool bres;
1579    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1580      return false;
1581    return Success(!bres, E);
1582  }
1583
1584  // Only handle integral operations...
1585  if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
1586    return false;
1587
1588  // Get the operand value into 'Result'.
1589  if (!Visit(E->getSubExpr()))
1590    return false;
1591
1592  switch (E->getOpcode()) {
1593  default:
1594    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1595    // See C99 6.6p3.
1596    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1597  case UO_Extension:
1598    // FIXME: Should extension allow i-c-e extension expressions in its scope?
1599    // If so, we could clear the diagnostic ID.
1600    return true;
1601  case UO_Plus:
1602    // The result is always just the subexpr.
1603    return true;
1604  case UO_Minus:
1605    if (!Result.isInt()) return false;
1606    return Success(-Result.getInt(), E);
1607  case UO_Not:
1608    if (!Result.isInt()) return false;
1609    return Success(~Result.getInt(), E);
1610  }
1611}
1612
1613/// HandleCast - This is used to evaluate implicit or explicit casts where the
1614/// result type is integer.
1615bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1616  Expr *SubExpr = E->getSubExpr();
1617  QualType DestType = E->getType();
1618  QualType SrcType = SubExpr->getType();
1619
1620  if (DestType->isBooleanType()) {
1621    bool BoolResult;
1622    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1623      return false;
1624    return Success(BoolResult, E);
1625  }
1626
1627  // Handle simple integer->integer casts.
1628  if (SrcType->isIntegralOrEnumerationType()) {
1629    if (!Visit(SubExpr))
1630      return false;
1631
1632    if (!Result.isInt()) {
1633      // Only allow casts of lvalues if they are lossless.
1634      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1635    }
1636
1637    return Success(HandleIntToIntCast(DestType, SrcType,
1638                                      Result.getInt(), Info.Ctx), E);
1639  }
1640
1641  // FIXME: Clean this up!
1642  if (SrcType->isPointerType()) {
1643    LValue LV;
1644    if (!EvaluatePointer(SubExpr, LV, Info))
1645      return false;
1646
1647    if (LV.getLValueBase()) {
1648      // Only allow based lvalue casts if they are lossless.
1649      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1650        return false;
1651
1652      LV.moveInto(Result);
1653      return true;
1654    }
1655
1656    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1657                                         SrcType);
1658    return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1659  }
1660
1661  if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1662    // This handles double-conversion cases, where there's both
1663    // an l-value promotion and an implicit conversion to int.
1664    LValue LV;
1665    if (!EvaluateLValue(SubExpr, LV, Info))
1666      return false;
1667
1668    if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1669      return false;
1670
1671    LV.moveInto(Result);
1672    return true;
1673  }
1674
1675  if (SrcType->isAnyComplexType()) {
1676    ComplexValue C;
1677    if (!EvaluateComplex(SubExpr, C, Info))
1678      return false;
1679    if (C.isComplexFloat())
1680      return Success(HandleFloatToIntCast(DestType, SrcType,
1681                                          C.getComplexFloatReal(), Info.Ctx),
1682                     E);
1683    else
1684      return Success(HandleIntToIntCast(DestType, SrcType,
1685                                        C.getComplexIntReal(), Info.Ctx), E);
1686  }
1687  // FIXME: Handle vectors
1688
1689  if (!SrcType->isRealFloatingType())
1690    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1691
1692  APFloat F(0.0);
1693  if (!EvaluateFloat(SubExpr, F, Info))
1694    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1695
1696  return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1697}
1698
1699bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1700  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1701    ComplexValue LV;
1702    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1703      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1704    return Success(LV.getComplexIntReal(), E);
1705  }
1706
1707  return Visit(E->getSubExpr());
1708}
1709
1710bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1711  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1712    ComplexValue LV;
1713    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1714      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1715    return Success(LV.getComplexIntImag(), E);
1716  }
1717
1718  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1719    Info.EvalResult.HasSideEffects = true;
1720  return Success(0, E);
1721}
1722
1723//===----------------------------------------------------------------------===//
1724// Float Evaluation
1725//===----------------------------------------------------------------------===//
1726
1727namespace {
1728class FloatExprEvaluator
1729  : public StmtVisitor<FloatExprEvaluator, bool> {
1730  EvalInfo &Info;
1731  APFloat &Result;
1732public:
1733  FloatExprEvaluator(EvalInfo &info, APFloat &result)
1734    : Info(info), Result(result) {}
1735
1736  bool VisitStmt(Stmt *S) {
1737    return false;
1738  }
1739
1740  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1741  bool VisitCallExpr(const CallExpr *E);
1742
1743  bool VisitUnaryOperator(const UnaryOperator *E);
1744  bool VisitBinaryOperator(const BinaryOperator *E);
1745  bool VisitFloatingLiteral(const FloatingLiteral *E);
1746  bool VisitCastExpr(CastExpr *E);
1747  bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1748  bool VisitConditionalOperator(ConditionalOperator *E);
1749
1750  bool VisitChooseExpr(const ChooseExpr *E)
1751    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1752  bool VisitUnaryExtension(const UnaryOperator *E)
1753    { return Visit(E->getSubExpr()); }
1754  bool VisitUnaryReal(const UnaryOperator *E);
1755  bool VisitUnaryImag(const UnaryOperator *E);
1756
1757  // FIXME: Missing: array subscript of vector, member of vector,
1758  //                 ImplicitValueInitExpr
1759};
1760} // end anonymous namespace
1761
1762static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1763  assert(E->getType()->isRealFloatingType());
1764  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1765}
1766
1767static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1768                                  QualType ResultTy,
1769                                  const Expr *Arg,
1770                                  bool SNaN,
1771                                  llvm::APFloat &Result) {
1772  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1773  if (!S) return false;
1774
1775  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1776
1777  llvm::APInt fill;
1778
1779  // Treat empty strings as if they were zero.
1780  if (S->getString().empty())
1781    fill = llvm::APInt(32, 0);
1782  else if (S->getString().getAsInteger(0, fill))
1783    return false;
1784
1785  if (SNaN)
1786    Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1787  else
1788    Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1789  return true;
1790}
1791
1792bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1793  switch (E->isBuiltinCall(Info.Ctx)) {
1794  default: return false;
1795  case Builtin::BI__builtin_huge_val:
1796  case Builtin::BI__builtin_huge_valf:
1797  case Builtin::BI__builtin_huge_vall:
1798  case Builtin::BI__builtin_inf:
1799  case Builtin::BI__builtin_inff:
1800  case Builtin::BI__builtin_infl: {
1801    const llvm::fltSemantics &Sem =
1802      Info.Ctx.getFloatTypeSemantics(E->getType());
1803    Result = llvm::APFloat::getInf(Sem);
1804    return true;
1805  }
1806
1807  case Builtin::BI__builtin_nans:
1808  case Builtin::BI__builtin_nansf:
1809  case Builtin::BI__builtin_nansl:
1810    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1811                                 true, Result);
1812
1813  case Builtin::BI__builtin_nan:
1814  case Builtin::BI__builtin_nanf:
1815  case Builtin::BI__builtin_nanl:
1816    // If this is __builtin_nan() turn this into a nan, otherwise we
1817    // can't constant fold it.
1818    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1819                                 false, Result);
1820
1821  case Builtin::BI__builtin_fabs:
1822  case Builtin::BI__builtin_fabsf:
1823  case Builtin::BI__builtin_fabsl:
1824    if (!EvaluateFloat(E->getArg(0), Result, Info))
1825      return false;
1826
1827    if (Result.isNegative())
1828      Result.changeSign();
1829    return true;
1830
1831  case Builtin::BI__builtin_copysign:
1832  case Builtin::BI__builtin_copysignf:
1833  case Builtin::BI__builtin_copysignl: {
1834    APFloat RHS(0.);
1835    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1836        !EvaluateFloat(E->getArg(1), RHS, Info))
1837      return false;
1838    Result.copySign(RHS);
1839    return true;
1840  }
1841  }
1842}
1843
1844bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1845  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1846    ComplexValue CV;
1847    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1848      return false;
1849    Result = CV.FloatReal;
1850    return true;
1851  }
1852
1853  return Visit(E->getSubExpr());
1854}
1855
1856bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1857  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1858    ComplexValue CV;
1859    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1860      return false;
1861    Result = CV.FloatImag;
1862    return true;
1863  }
1864
1865  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1866    Info.EvalResult.HasSideEffects = true;
1867  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
1868  Result = llvm::APFloat::getZero(Sem);
1869  return true;
1870}
1871
1872bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1873  if (E->getOpcode() == UO_Deref)
1874    return false;
1875
1876  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1877    return false;
1878
1879  switch (E->getOpcode()) {
1880  default: return false;
1881  case UO_Plus:
1882    return true;
1883  case UO_Minus:
1884    Result.changeSign();
1885    return true;
1886  }
1887}
1888
1889bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1890  if (E->getOpcode() == BO_Comma) {
1891    if (!EvaluateFloat(E->getRHS(), Result, Info))
1892      return false;
1893
1894    // If we can't evaluate the LHS, it might have side effects;
1895    // conservatively mark it.
1896    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1897      Info.EvalResult.HasSideEffects = true;
1898
1899    return true;
1900  }
1901
1902  // FIXME: Diagnostics?  I really don't understand how the warnings
1903  // and errors are supposed to work.
1904  APFloat RHS(0.0);
1905  if (!EvaluateFloat(E->getLHS(), Result, Info))
1906    return false;
1907  if (!EvaluateFloat(E->getRHS(), RHS, Info))
1908    return false;
1909
1910  switch (E->getOpcode()) {
1911  default: return false;
1912  case BO_Mul:
1913    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1914    return true;
1915  case BO_Add:
1916    Result.add(RHS, APFloat::rmNearestTiesToEven);
1917    return true;
1918  case BO_Sub:
1919    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1920    return true;
1921  case BO_Div:
1922    Result.divide(RHS, APFloat::rmNearestTiesToEven);
1923    return true;
1924  }
1925}
1926
1927bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1928  Result = E->getValue();
1929  return true;
1930}
1931
1932bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1933  Expr* SubExpr = E->getSubExpr();
1934
1935  if (SubExpr->getType()->isIntegralOrEnumerationType()) {
1936    APSInt IntResult;
1937    if (!EvaluateInteger(SubExpr, IntResult, Info))
1938      return false;
1939    Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1940                                  IntResult, Info.Ctx);
1941    return true;
1942  }
1943  if (SubExpr->getType()->isRealFloatingType()) {
1944    if (!Visit(SubExpr))
1945      return false;
1946    Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1947                                    Result, Info.Ctx);
1948    return true;
1949  }
1950  // FIXME: Handle complex types
1951
1952  return false;
1953}
1954
1955bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1956  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1957  return true;
1958}
1959
1960bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1961  bool Cond;
1962  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1963    return false;
1964
1965  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1966}
1967
1968//===----------------------------------------------------------------------===//
1969// Complex Evaluation (for float and integer)
1970//===----------------------------------------------------------------------===//
1971
1972namespace {
1973class ComplexExprEvaluator
1974  : public StmtVisitor<ComplexExprEvaluator, bool> {
1975  EvalInfo &Info;
1976  ComplexValue &Result;
1977
1978public:
1979  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
1980    : Info(info), Result(Result) {}
1981
1982  //===--------------------------------------------------------------------===//
1983  //                            Visitor Methods
1984  //===--------------------------------------------------------------------===//
1985
1986  bool VisitStmt(Stmt *S) {
1987    return false;
1988  }
1989
1990  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1991
1992  bool VisitImaginaryLiteral(ImaginaryLiteral *E);
1993
1994  bool VisitCastExpr(CastExpr *E);
1995
1996  bool VisitBinaryOperator(const BinaryOperator *E);
1997  bool VisitChooseExpr(const ChooseExpr *E)
1998    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1999  bool VisitUnaryExtension(const UnaryOperator *E)
2000    { return Visit(E->getSubExpr()); }
2001  // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
2002  //                conditional ?:, comma
2003};
2004} // end anonymous namespace
2005
2006static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2007                            EvalInfo &Info) {
2008  assert(E->getType()->isAnyComplexType());
2009  return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
2010}
2011
2012bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2013  Expr* SubExpr = E->getSubExpr();
2014
2015  if (SubExpr->getType()->isRealFloatingType()) {
2016    Result.makeComplexFloat();
2017    APFloat &Imag = Result.FloatImag;
2018    if (!EvaluateFloat(SubExpr, Imag, Info))
2019      return false;
2020
2021    Result.FloatReal = APFloat(Imag.getSemantics());
2022    return true;
2023  } else {
2024    assert(SubExpr->getType()->isIntegerType() &&
2025           "Unexpected imaginary literal.");
2026
2027    Result.makeComplexInt();
2028    APSInt &Imag = Result.IntImag;
2029    if (!EvaluateInteger(SubExpr, Imag, Info))
2030      return false;
2031
2032    Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2033    return true;
2034  }
2035}
2036
2037bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
2038  Expr* SubExpr = E->getSubExpr();
2039  QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
2040  QualType SubType = SubExpr->getType();
2041
2042  if (SubType->isRealFloatingType()) {
2043    APFloat &Real = Result.FloatReal;
2044    if (!EvaluateFloat(SubExpr, Real, Info))
2045      return false;
2046
2047    if (EltType->isRealFloatingType()) {
2048      Result.makeComplexFloat();
2049      Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
2050      Result.FloatImag = APFloat(Real.getSemantics());
2051      return true;
2052    } else {
2053      Result.makeComplexInt();
2054      Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
2055      Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
2056                              !Result.IntReal.isSigned());
2057      return true;
2058    }
2059  } else if (SubType->isIntegerType()) {
2060    APSInt &Real = Result.IntReal;
2061    if (!EvaluateInteger(SubExpr, Real, Info))
2062      return false;
2063
2064    if (EltType->isRealFloatingType()) {
2065      Result.makeComplexFloat();
2066      Result.FloatReal
2067        = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
2068      Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
2069      return true;
2070    } else {
2071      Result.makeComplexInt();
2072      Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
2073      Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2074      return true;
2075    }
2076  } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
2077    if (!Visit(SubExpr))
2078      return false;
2079
2080    QualType SrcType = CT->getElementType();
2081
2082    if (Result.isComplexFloat()) {
2083      if (EltType->isRealFloatingType()) {
2084        Result.makeComplexFloat();
2085        Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
2086                                                  Result.FloatReal,
2087                                                  Info.Ctx);
2088        Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
2089                                                  Result.FloatImag,
2090                                                  Info.Ctx);
2091        return true;
2092      } else {
2093        Result.makeComplexInt();
2094        Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
2095                                              Result.FloatReal,
2096                                              Info.Ctx);
2097        Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
2098                                              Result.FloatImag,
2099                                              Info.Ctx);
2100        return true;
2101      }
2102    } else {
2103      assert(Result.isComplexInt() && "Invalid evaluate result.");
2104      if (EltType->isRealFloatingType()) {
2105        Result.makeComplexFloat();
2106        Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
2107                                                Result.IntReal,
2108                                                Info.Ctx);
2109        Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2110                                                Result.IntImag,
2111                                                Info.Ctx);
2112        return true;
2113      } else {
2114        Result.makeComplexInt();
2115        Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2116                                            Result.IntReal,
2117                                            Info.Ctx);
2118        Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2119                                            Result.IntImag,
2120                                            Info.Ctx);
2121        return true;
2122      }
2123    }
2124  }
2125
2126  // FIXME: Handle more casts.
2127  return false;
2128}
2129
2130bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2131  if (!Visit(E->getLHS()))
2132    return false;
2133
2134  ComplexValue RHS;
2135  if (!EvaluateComplex(E->getRHS(), RHS, Info))
2136    return false;
2137
2138  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2139         "Invalid operands to binary operator.");
2140  switch (E->getOpcode()) {
2141  default: return false;
2142  case BO_Add:
2143    if (Result.isComplexFloat()) {
2144      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2145                                       APFloat::rmNearestTiesToEven);
2146      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2147                                       APFloat::rmNearestTiesToEven);
2148    } else {
2149      Result.getComplexIntReal() += RHS.getComplexIntReal();
2150      Result.getComplexIntImag() += RHS.getComplexIntImag();
2151    }
2152    break;
2153  case BO_Sub:
2154    if (Result.isComplexFloat()) {
2155      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2156                                            APFloat::rmNearestTiesToEven);
2157      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2158                                            APFloat::rmNearestTiesToEven);
2159    } else {
2160      Result.getComplexIntReal() -= RHS.getComplexIntReal();
2161      Result.getComplexIntImag() -= RHS.getComplexIntImag();
2162    }
2163    break;
2164  case BO_Mul:
2165    if (Result.isComplexFloat()) {
2166      ComplexValue LHS = Result;
2167      APFloat &LHS_r = LHS.getComplexFloatReal();
2168      APFloat &LHS_i = LHS.getComplexFloatImag();
2169      APFloat &RHS_r = RHS.getComplexFloatReal();
2170      APFloat &RHS_i = RHS.getComplexFloatImag();
2171
2172      APFloat Tmp = LHS_r;
2173      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2174      Result.getComplexFloatReal() = Tmp;
2175      Tmp = LHS_i;
2176      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2177      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2178
2179      Tmp = LHS_r;
2180      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2181      Result.getComplexFloatImag() = Tmp;
2182      Tmp = LHS_i;
2183      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2184      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2185    } else {
2186      ComplexValue LHS = Result;
2187      Result.getComplexIntReal() =
2188        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2189         LHS.getComplexIntImag() * RHS.getComplexIntImag());
2190      Result.getComplexIntImag() =
2191        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2192         LHS.getComplexIntImag() * RHS.getComplexIntReal());
2193    }
2194    break;
2195  }
2196
2197  return true;
2198}
2199
2200//===----------------------------------------------------------------------===//
2201// Top level Expr::Evaluate method.
2202//===----------------------------------------------------------------------===//
2203
2204/// Evaluate - Return true if this is a constant which we can fold using
2205/// any crazy technique (that has nothing to do with language standards) that
2206/// we want to.  If this function returns true, it returns the folded constant
2207/// in Result.
2208bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2209  const Expr *E = this;
2210  EvalInfo Info(Ctx, Result);
2211  if (E->getType()->isVectorType()) {
2212    if (!EvaluateVector(E, Info.EvalResult.Val, Info))
2213      return false;
2214  } else if (E->getType()->isIntegerType()) {
2215    if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
2216      return false;
2217    if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2218      return false;
2219  } else if (E->getType()->hasPointerRepresentation()) {
2220    LValue LV;
2221    if (!EvaluatePointer(E, LV, Info))
2222      return false;
2223    if (!IsGlobalLValue(LV.Base))
2224      return false;
2225    LV.moveInto(Info.EvalResult.Val);
2226  } else if (E->getType()->isRealFloatingType()) {
2227    llvm::APFloat F(0.0);
2228    if (!EvaluateFloat(E, F, Info))
2229      return false;
2230
2231    Info.EvalResult.Val = APValue(F);
2232  } else if (E->getType()->isAnyComplexType()) {
2233    ComplexValue C;
2234    if (!EvaluateComplex(E, C, Info))
2235      return false;
2236    C.moveInto(Info.EvalResult.Val);
2237  } else
2238    return false;
2239
2240  return true;
2241}
2242
2243bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2244  EvalResult Scratch;
2245  EvalInfo Info(Ctx, Scratch);
2246
2247  return HandleConversionToBool(this, Result, Info);
2248}
2249
2250bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2251  EvalInfo Info(Ctx, Result);
2252
2253  LValue LV;
2254  if (EvaluateLValue(this, LV, Info) &&
2255      !Result.HasSideEffects &&
2256      IsGlobalLValue(LV.Base)) {
2257    LV.moveInto(Result.Val);
2258    return true;
2259  }
2260  return false;
2261}
2262
2263bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2264  EvalInfo Info(Ctx, Result);
2265
2266  LValue LV;
2267  if (EvaluateLValue(this, LV, Info)) {
2268    LV.moveInto(Result.Val);
2269    return true;
2270  }
2271  return false;
2272}
2273
2274/// isEvaluatable - Call Evaluate to see if this expression can be constant
2275/// folded, but discard the result.
2276bool Expr::isEvaluatable(ASTContext &Ctx) const {
2277  EvalResult Result;
2278  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
2279}
2280
2281bool Expr::HasSideEffects(ASTContext &Ctx) const {
2282  Expr::EvalResult Result;
2283  EvalInfo Info(Ctx, Result);
2284  return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2285}
2286
2287APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
2288  EvalResult EvalResult;
2289  bool Result = Evaluate(EvalResult, Ctx);
2290  Result = Result;
2291  assert(Result && "Could not evaluate expression");
2292  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
2293
2294  return EvalResult.Val.getInt();
2295}
2296
2297 bool Expr::EvalResult::isGlobalLValue() const {
2298   assert(Val.isLValue());
2299   return IsGlobalLValue(Val.getLValueBase());
2300 }
2301
2302
2303/// isIntegerConstantExpr - this recursive routine will test if an expression is
2304/// an integer constant expression.
2305
2306/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2307/// comma, etc
2308///
2309/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
2310/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
2311/// cast+dereference.
2312
2313// CheckICE - This function does the fundamental ICE checking: the returned
2314// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2315// Note that to reduce code duplication, this helper does no evaluation
2316// itself; the caller checks whether the expression is evaluatable, and
2317// in the rare cases where CheckICE actually cares about the evaluated
2318// value, it calls into Evalute.
2319//
2320// Meanings of Val:
2321// 0: This expression is an ICE if it can be evaluated by Evaluate.
2322// 1: This expression is not an ICE, but if it isn't evaluated, it's
2323//    a legal subexpression for an ICE. This return value is used to handle
2324//    the comma operator in C99 mode.
2325// 2: This expression is not an ICE, and is not a legal subexpression for one.
2326
2327namespace {
2328
2329struct ICEDiag {
2330  unsigned Val;
2331  SourceLocation Loc;
2332
2333  public:
2334  ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2335  ICEDiag() : Val(0) {}
2336};
2337
2338}
2339
2340static ICEDiag NoDiag() { return ICEDiag(); }
2341
2342static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2343  Expr::EvalResult EVResult;
2344  if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2345      !EVResult.Val.isInt()) {
2346    return ICEDiag(2, E->getLocStart());
2347  }
2348  return NoDiag();
2349}
2350
2351static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2352  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2353  if (!E->getType()->isIntegralOrEnumerationType()) {
2354    return ICEDiag(2, E->getLocStart());
2355  }
2356
2357  switch (E->getStmtClass()) {
2358#define STMT(Node, Base) case Expr::Node##Class:
2359#define EXPR(Node, Base)
2360#include "clang/AST/StmtNodes.inc"
2361  case Expr::PredefinedExprClass:
2362  case Expr::FloatingLiteralClass:
2363  case Expr::ImaginaryLiteralClass:
2364  case Expr::StringLiteralClass:
2365  case Expr::ArraySubscriptExprClass:
2366  case Expr::MemberExprClass:
2367  case Expr::CompoundAssignOperatorClass:
2368  case Expr::CompoundLiteralExprClass:
2369  case Expr::ExtVectorElementExprClass:
2370  case Expr::InitListExprClass:
2371  case Expr::DesignatedInitExprClass:
2372  case Expr::ImplicitValueInitExprClass:
2373  case Expr::ParenListExprClass:
2374  case Expr::VAArgExprClass:
2375  case Expr::AddrLabelExprClass:
2376  case Expr::StmtExprClass:
2377  case Expr::CXXMemberCallExprClass:
2378  case Expr::CXXDynamicCastExprClass:
2379  case Expr::CXXTypeidExprClass:
2380  case Expr::CXXNullPtrLiteralExprClass:
2381  case Expr::CXXThisExprClass:
2382  case Expr::CXXThrowExprClass:
2383  case Expr::CXXNewExprClass:
2384  case Expr::CXXDeleteExprClass:
2385  case Expr::CXXPseudoDestructorExprClass:
2386  case Expr::UnresolvedLookupExprClass:
2387  case Expr::DependentScopeDeclRefExprClass:
2388  case Expr::CXXConstructExprClass:
2389  case Expr::CXXBindTemporaryExprClass:
2390  case Expr::CXXExprWithTemporariesClass:
2391  case Expr::CXXTemporaryObjectExprClass:
2392  case Expr::CXXUnresolvedConstructExprClass:
2393  case Expr::CXXDependentScopeMemberExprClass:
2394  case Expr::UnresolvedMemberExprClass:
2395  case Expr::ObjCStringLiteralClass:
2396  case Expr::ObjCEncodeExprClass:
2397  case Expr::ObjCMessageExprClass:
2398  case Expr::ObjCSelectorExprClass:
2399  case Expr::ObjCProtocolExprClass:
2400  case Expr::ObjCIvarRefExprClass:
2401  case Expr::ObjCPropertyRefExprClass:
2402  case Expr::ObjCImplicitSetterGetterRefExprClass:
2403  case Expr::ObjCSuperExprClass:
2404  case Expr::ObjCIsaExprClass:
2405  case Expr::ShuffleVectorExprClass:
2406  case Expr::BlockExprClass:
2407  case Expr::BlockDeclRefExprClass:
2408  case Expr::NoStmtClass:
2409    return ICEDiag(2, E->getLocStart());
2410
2411  case Expr::GNUNullExprClass:
2412    // GCC considers the GNU __null value to be an integral constant expression.
2413    return NoDiag();
2414
2415  case Expr::ParenExprClass:
2416    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2417  case Expr::IntegerLiteralClass:
2418  case Expr::CharacterLiteralClass:
2419  case Expr::CXXBoolLiteralExprClass:
2420  case Expr::CXXScalarValueInitExprClass:
2421  case Expr::TypesCompatibleExprClass:
2422  case Expr::UnaryTypeTraitExprClass:
2423    return NoDiag();
2424  case Expr::CallExprClass:
2425  case Expr::CXXOperatorCallExprClass: {
2426    const CallExpr *CE = cast<CallExpr>(E);
2427    if (CE->isBuiltinCall(Ctx))
2428      return CheckEvalInICE(E, Ctx);
2429    return ICEDiag(2, E->getLocStart());
2430  }
2431  case Expr::DeclRefExprClass:
2432    if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2433      return NoDiag();
2434    if (Ctx.getLangOptions().CPlusPlus &&
2435        E->getType().getCVRQualifiers() == Qualifiers::Const) {
2436      const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2437
2438      // Parameter variables are never constants.  Without this check,
2439      // getAnyInitializer() can find a default argument, which leads
2440      // to chaos.
2441      if (isa<ParmVarDecl>(D))
2442        return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2443
2444      // C++ 7.1.5.1p2
2445      //   A variable of non-volatile const-qualified integral or enumeration
2446      //   type initialized by an ICE can be used in ICEs.
2447      if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2448        Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2449        if (Quals.hasVolatile() || !Quals.hasConst())
2450          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2451
2452        // Look for a declaration of this variable that has an initializer.
2453        const VarDecl *ID = 0;
2454        const Expr *Init = Dcl->getAnyInitializer(ID);
2455        if (Init) {
2456          if (ID->isInitKnownICE()) {
2457            // We have already checked whether this subexpression is an
2458            // integral constant expression.
2459            if (ID->isInitICE())
2460              return NoDiag();
2461            else
2462              return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2463          }
2464
2465          // It's an ICE whether or not the definition we found is
2466          // out-of-line.  See DR 721 and the discussion in Clang PR
2467          // 6206 for details.
2468
2469          if (Dcl->isCheckingICE()) {
2470            return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2471          }
2472
2473          Dcl->setCheckingICE();
2474          ICEDiag Result = CheckICE(Init, Ctx);
2475          // Cache the result of the ICE test.
2476          Dcl->setInitKnownICE(Result.Val == 0);
2477          return Result;
2478        }
2479      }
2480    }
2481    return ICEDiag(2, E->getLocStart());
2482  case Expr::UnaryOperatorClass: {
2483    const UnaryOperator *Exp = cast<UnaryOperator>(E);
2484    switch (Exp->getOpcode()) {
2485    case UO_PostInc:
2486    case UO_PostDec:
2487    case UO_PreInc:
2488    case UO_PreDec:
2489    case UO_AddrOf:
2490    case UO_Deref:
2491      return ICEDiag(2, E->getLocStart());
2492    case UO_Extension:
2493    case UO_LNot:
2494    case UO_Plus:
2495    case UO_Minus:
2496    case UO_Not:
2497    case UO_Real:
2498    case UO_Imag:
2499      return CheckICE(Exp->getSubExpr(), Ctx);
2500    }
2501
2502    // OffsetOf falls through here.
2503  }
2504  case Expr::OffsetOfExprClass: {
2505      // Note that per C99, offsetof must be an ICE. And AFAIK, using
2506      // Evaluate matches the proposed gcc behavior for cases like
2507      // "offsetof(struct s{int x[4];}, x[!.0])".  This doesn't affect
2508      // compliance: we should warn earlier for offsetof expressions with
2509      // array subscripts that aren't ICEs, and if the array subscripts
2510      // are ICEs, the value of the offsetof must be an integer constant.
2511      return CheckEvalInICE(E, Ctx);
2512  }
2513  case Expr::SizeOfAlignOfExprClass: {
2514    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2515    if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2516      return ICEDiag(2, E->getLocStart());
2517    return NoDiag();
2518  }
2519  case Expr::BinaryOperatorClass: {
2520    const BinaryOperator *Exp = cast<BinaryOperator>(E);
2521    switch (Exp->getOpcode()) {
2522    case BO_PtrMemD:
2523    case BO_PtrMemI:
2524    case BO_Assign:
2525    case BO_MulAssign:
2526    case BO_DivAssign:
2527    case BO_RemAssign:
2528    case BO_AddAssign:
2529    case BO_SubAssign:
2530    case BO_ShlAssign:
2531    case BO_ShrAssign:
2532    case BO_AndAssign:
2533    case BO_XorAssign:
2534    case BO_OrAssign:
2535      return ICEDiag(2, E->getLocStart());
2536
2537    case BO_Mul:
2538    case BO_Div:
2539    case BO_Rem:
2540    case BO_Add:
2541    case BO_Sub:
2542    case BO_Shl:
2543    case BO_Shr:
2544    case BO_LT:
2545    case BO_GT:
2546    case BO_LE:
2547    case BO_GE:
2548    case BO_EQ:
2549    case BO_NE:
2550    case BO_And:
2551    case BO_Xor:
2552    case BO_Or:
2553    case BO_Comma: {
2554      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2555      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2556      if (Exp->getOpcode() == BO_Div ||
2557          Exp->getOpcode() == BO_Rem) {
2558        // Evaluate gives an error for undefined Div/Rem, so make sure
2559        // we don't evaluate one.
2560        if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2561          llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2562          if (REval == 0)
2563            return ICEDiag(1, E->getLocStart());
2564          if (REval.isSigned() && REval.isAllOnesValue()) {
2565            llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2566            if (LEval.isMinSignedValue())
2567              return ICEDiag(1, E->getLocStart());
2568          }
2569        }
2570      }
2571      if (Exp->getOpcode() == BO_Comma) {
2572        if (Ctx.getLangOptions().C99) {
2573          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2574          // if it isn't evaluated.
2575          if (LHSResult.Val == 0 && RHSResult.Val == 0)
2576            return ICEDiag(1, E->getLocStart());
2577        } else {
2578          // In both C89 and C++, commas in ICEs are illegal.
2579          return ICEDiag(2, E->getLocStart());
2580        }
2581      }
2582      if (LHSResult.Val >= RHSResult.Val)
2583        return LHSResult;
2584      return RHSResult;
2585    }
2586    case BO_LAnd:
2587    case BO_LOr: {
2588      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2589      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2590      if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2591        // Rare case where the RHS has a comma "side-effect"; we need
2592        // to actually check the condition to see whether the side
2593        // with the comma is evaluated.
2594        if ((Exp->getOpcode() == BO_LAnd) !=
2595            (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2596          return RHSResult;
2597        return NoDiag();
2598      }
2599
2600      if (LHSResult.Val >= RHSResult.Val)
2601        return LHSResult;
2602      return RHSResult;
2603    }
2604    }
2605  }
2606  case Expr::ImplicitCastExprClass:
2607  case Expr::CStyleCastExprClass:
2608  case Expr::CXXFunctionalCastExprClass:
2609  case Expr::CXXStaticCastExprClass:
2610  case Expr::CXXReinterpretCastExprClass:
2611  case Expr::CXXConstCastExprClass: {
2612    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2613    if (SubExpr->getType()->isIntegralOrEnumerationType())
2614      return CheckICE(SubExpr, Ctx);
2615    if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2616      return NoDiag();
2617    return ICEDiag(2, E->getLocStart());
2618  }
2619  case Expr::ConditionalOperatorClass: {
2620    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2621    // If the condition (ignoring parens) is a __builtin_constant_p call,
2622    // then only the true side is actually considered in an integer constant
2623    // expression, and it is fully evaluated.  This is an important GNU
2624    // extension.  See GCC PR38377 for discussion.
2625    if (const CallExpr *CallCE
2626        = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2627      if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2628        Expr::EvalResult EVResult;
2629        if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2630            !EVResult.Val.isInt()) {
2631          return ICEDiag(2, E->getLocStart());
2632        }
2633        return NoDiag();
2634      }
2635    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2636    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2637    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2638    if (CondResult.Val == 2)
2639      return CondResult;
2640    if (TrueResult.Val == 2)
2641      return TrueResult;
2642    if (FalseResult.Val == 2)
2643      return FalseResult;
2644    if (CondResult.Val == 1)
2645      return CondResult;
2646    if (TrueResult.Val == 0 && FalseResult.Val == 0)
2647      return NoDiag();
2648    // Rare case where the diagnostics depend on which side is evaluated
2649    // Note that if we get here, CondResult is 0, and at least one of
2650    // TrueResult and FalseResult is non-zero.
2651    if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2652      return FalseResult;
2653    }
2654    return TrueResult;
2655  }
2656  case Expr::CXXDefaultArgExprClass:
2657    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2658  case Expr::ChooseExprClass: {
2659    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2660  }
2661  }
2662
2663  // Silence a GCC warning
2664  return ICEDiag(2, E->getLocStart());
2665}
2666
2667bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2668                                 SourceLocation *Loc, bool isEvaluated) const {
2669  ICEDiag d = CheckICE(this, Ctx);
2670  if (d.Val != 0) {
2671    if (Loc) *Loc = d.Loc;
2672    return false;
2673  }
2674  EvalResult EvalResult;
2675  if (!Evaluate(EvalResult, Ctx))
2676    llvm_unreachable("ICE cannot be evaluated!");
2677  assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2678  assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2679  Result = EvalResult.Val.getInt();
2680  return true;
2681}
2682