ExprConstant.cpp revision 0d4739a839520772aab5652dd1dcd5009ddc1969
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        Expr::EvalResult EResult;
1012        if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1013            EResult.Val.isInt()) {
1014          // Cache the evaluated value in the variable declaration.
1015          Result = EResult.Val;
1016          VD->setEvaluatedValue(Result);
1017          return true;
1018        }
1019
1020        VD->setEvaluatedValue(APValue());
1021      }
1022    }
1023  }
1024
1025  // Otherwise, random variable references are not constants.
1026  return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1027}
1028
1029/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1030/// as GCC.
1031static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1032  // The following enum mimics the values returned by GCC.
1033  // FIXME: Does GCC differ between lvalue and rvalue references here?
1034  enum gcc_type_class {
1035    no_type_class = -1,
1036    void_type_class, integer_type_class, char_type_class,
1037    enumeral_type_class, boolean_type_class,
1038    pointer_type_class, reference_type_class, offset_type_class,
1039    real_type_class, complex_type_class,
1040    function_type_class, method_type_class,
1041    record_type_class, union_type_class,
1042    array_type_class, string_type_class,
1043    lang_type_class
1044  };
1045
1046  // If no argument was supplied, default to "no_type_class". This isn't
1047  // ideal, however it is what gcc does.
1048  if (E->getNumArgs() == 0)
1049    return no_type_class;
1050
1051  QualType ArgTy = E->getArg(0)->getType();
1052  if (ArgTy->isVoidType())
1053    return void_type_class;
1054  else if (ArgTy->isEnumeralType())
1055    return enumeral_type_class;
1056  else if (ArgTy->isBooleanType())
1057    return boolean_type_class;
1058  else if (ArgTy->isCharType())
1059    return string_type_class; // gcc doesn't appear to use char_type_class
1060  else if (ArgTy->isIntegerType())
1061    return integer_type_class;
1062  else if (ArgTy->isPointerType())
1063    return pointer_type_class;
1064  else if (ArgTy->isReferenceType())
1065    return reference_type_class;
1066  else if (ArgTy->isRealType())
1067    return real_type_class;
1068  else if (ArgTy->isComplexType())
1069    return complex_type_class;
1070  else if (ArgTy->isFunctionType())
1071    return function_type_class;
1072  else if (ArgTy->isStructureOrClassType())
1073    return record_type_class;
1074  else if (ArgTy->isUnionType())
1075    return union_type_class;
1076  else if (ArgTy->isArrayType())
1077    return array_type_class;
1078  else if (ArgTy->isUnionType())
1079    return union_type_class;
1080  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
1081    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1082  return -1;
1083}
1084
1085/// Retrieves the "underlying object type" of the given expression,
1086/// as used by __builtin_object_size.
1087QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1088  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1089    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1090      return VD->getType();
1091  } else if (isa<CompoundLiteralExpr>(E)) {
1092    return E->getType();
1093  }
1094
1095  return QualType();
1096}
1097
1098bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1099  // TODO: Perhaps we should let LLVM lower this?
1100  LValue Base;
1101  if (!EvaluatePointer(E->getArg(0), Base, Info))
1102    return false;
1103
1104  // If we can prove the base is null, lower to zero now.
1105  const Expr *LVBase = Base.getLValueBase();
1106  if (!LVBase) return Success(0, E);
1107
1108  QualType T = GetObjectType(LVBase);
1109  if (T.isNull() ||
1110      T->isIncompleteType() ||
1111      T->isFunctionType() ||
1112      T->isVariablyModifiedType() ||
1113      T->isDependentType())
1114    return false;
1115
1116  CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1117  CharUnits Offset = Base.getLValueOffset();
1118
1119  if (!Offset.isNegative() && Offset <= Size)
1120    Size -= Offset;
1121  else
1122    Size = CharUnits::Zero();
1123  return Success(Size.getQuantity(), E);
1124}
1125
1126bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
1127  switch (E->isBuiltinCall(Info.Ctx)) {
1128  default:
1129    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1130
1131  case Builtin::BI__builtin_object_size: {
1132    if (TryEvaluateBuiltinObjectSize(E))
1133      return true;
1134
1135    // If evaluating the argument has side-effects we can't determine
1136    // the size of the object and lower it to unknown now.
1137    if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
1138      if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
1139        return Success(-1ULL, E);
1140      return Success(0, E);
1141    }
1142
1143    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1144  }
1145
1146  case Builtin::BI__builtin_classify_type:
1147    return Success(EvaluateBuiltinClassifyType(E), E);
1148
1149  case Builtin::BI__builtin_constant_p:
1150    // __builtin_constant_p always has one operand: it returns true if that
1151    // operand can be folded, false otherwise.
1152    return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
1153
1154  case Builtin::BI__builtin_eh_return_data_regno: {
1155    int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1156    Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1157    return Success(Operand, E);
1158  }
1159
1160  case Builtin::BI__builtin_expect:
1161    return Visit(E->getArg(0));
1162  }
1163}
1164
1165bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1166  if (E->getOpcode() == BO_Comma) {
1167    if (!Visit(E->getRHS()))
1168      return false;
1169
1170    // If we can't evaluate the LHS, it might have side effects;
1171    // conservatively mark it.
1172    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1173      Info.EvalResult.HasSideEffects = true;
1174
1175    return true;
1176  }
1177
1178  if (E->isLogicalOp()) {
1179    // These need to be handled specially because the operands aren't
1180    // necessarily integral
1181    bool lhsResult, rhsResult;
1182
1183    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
1184      // We were able to evaluate the LHS, see if we can get away with not
1185      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1186      if (lhsResult == (E->getOpcode() == BO_LOr))
1187        return Success(lhsResult, E);
1188
1189      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1190        if (E->getOpcode() == BO_LOr)
1191          return Success(lhsResult || rhsResult, E);
1192        else
1193          return Success(lhsResult && rhsResult, E);
1194      }
1195    } else {
1196      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1197        // We can't evaluate the LHS; however, sometimes the result
1198        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1199        if (rhsResult == (E->getOpcode() == BO_LOr) ||
1200            !rhsResult == (E->getOpcode() == BO_LAnd)) {
1201          // Since we weren't able to evaluate the left hand side, it
1202          // must have had side effects.
1203          Info.EvalResult.HasSideEffects = true;
1204
1205          return Success(rhsResult, E);
1206        }
1207      }
1208    }
1209
1210    return false;
1211  }
1212
1213  QualType LHSTy = E->getLHS()->getType();
1214  QualType RHSTy = E->getRHS()->getType();
1215
1216  if (LHSTy->isAnyComplexType()) {
1217    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1218    ComplexValue LHS, RHS;
1219
1220    if (!EvaluateComplex(E->getLHS(), LHS, Info))
1221      return false;
1222
1223    if (!EvaluateComplex(E->getRHS(), RHS, Info))
1224      return false;
1225
1226    if (LHS.isComplexFloat()) {
1227      APFloat::cmpResult CR_r =
1228        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
1229      APFloat::cmpResult CR_i =
1230        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1231
1232      if (E->getOpcode() == BO_EQ)
1233        return Success((CR_r == APFloat::cmpEqual &&
1234                        CR_i == APFloat::cmpEqual), E);
1235      else {
1236        assert(E->getOpcode() == BO_NE &&
1237               "Invalid complex comparison.");
1238        return Success(((CR_r == APFloat::cmpGreaterThan ||
1239                         CR_r == APFloat::cmpLessThan ||
1240                         CR_r == APFloat::cmpUnordered) ||
1241                        (CR_i == APFloat::cmpGreaterThan ||
1242                         CR_i == APFloat::cmpLessThan ||
1243                         CR_i == APFloat::cmpUnordered)), E);
1244      }
1245    } else {
1246      if (E->getOpcode() == BO_EQ)
1247        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1248                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1249      else {
1250        assert(E->getOpcode() == BO_NE &&
1251               "Invalid compex comparison.");
1252        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1253                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1254      }
1255    }
1256  }
1257
1258  if (LHSTy->isRealFloatingType() &&
1259      RHSTy->isRealFloatingType()) {
1260    APFloat RHS(0.0), LHS(0.0);
1261
1262    if (!EvaluateFloat(E->getRHS(), RHS, Info))
1263      return false;
1264
1265    if (!EvaluateFloat(E->getLHS(), LHS, Info))
1266      return false;
1267
1268    APFloat::cmpResult CR = LHS.compare(RHS);
1269
1270    switch (E->getOpcode()) {
1271    default:
1272      assert(0 && "Invalid binary operator!");
1273    case BO_LT:
1274      return Success(CR == APFloat::cmpLessThan, E);
1275    case BO_GT:
1276      return Success(CR == APFloat::cmpGreaterThan, E);
1277    case BO_LE:
1278      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
1279    case BO_GE:
1280      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
1281                     E);
1282    case BO_EQ:
1283      return Success(CR == APFloat::cmpEqual, E);
1284    case BO_NE:
1285      return Success(CR == APFloat::cmpGreaterThan
1286                     || CR == APFloat::cmpLessThan
1287                     || CR == APFloat::cmpUnordered, E);
1288    }
1289  }
1290
1291  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1292    if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
1293      LValue LHSValue;
1294      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1295        return false;
1296
1297      LValue RHSValue;
1298      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1299        return false;
1300
1301      // Reject any bases from the normal codepath; we special-case comparisons
1302      // to null.
1303      if (LHSValue.getLValueBase()) {
1304        if (!E->isEqualityOp())
1305          return false;
1306        if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
1307          return false;
1308        bool bres;
1309        if (!EvalPointerValueAsBool(LHSValue, bres))
1310          return false;
1311        return Success(bres ^ (E->getOpcode() == BO_EQ), E);
1312      } else if (RHSValue.getLValueBase()) {
1313        if (!E->isEqualityOp())
1314          return false;
1315        if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
1316          return false;
1317        bool bres;
1318        if (!EvalPointerValueAsBool(RHSValue, bres))
1319          return false;
1320        return Success(bres ^ (E->getOpcode() == BO_EQ), E);
1321      }
1322
1323      if (E->getOpcode() == BO_Sub) {
1324        QualType Type = E->getLHS()->getType();
1325        QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
1326
1327        CharUnits ElementSize = CharUnits::One();
1328        if (!ElementType->isVoidType() && !ElementType->isFunctionType())
1329          ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
1330
1331        CharUnits Diff = LHSValue.getLValueOffset() -
1332                             RHSValue.getLValueOffset();
1333        return Success(Diff / ElementSize, E);
1334      }
1335      bool Result;
1336      if (E->getOpcode() == BO_EQ) {
1337        Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
1338      } else {
1339        Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1340      }
1341      return Success(Result, E);
1342    }
1343  }
1344  if (!LHSTy->isIntegralOrEnumerationType() ||
1345      !RHSTy->isIntegralOrEnumerationType()) {
1346    // We can't continue from here for non-integral types, and they
1347    // could potentially confuse the following operations.
1348    return false;
1349  }
1350
1351  // The LHS of a constant expr is always evaluated and needed.
1352  if (!Visit(E->getLHS()))
1353    return false; // error in subexpression.
1354
1355  APValue RHSVal;
1356  if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1357    return false;
1358
1359  // Handle cases like (unsigned long)&a + 4.
1360  if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1361    CharUnits Offset = Result.getLValueOffset();
1362    CharUnits AdditionalOffset = CharUnits::fromQuantity(
1363                                     RHSVal.getInt().getZExtValue());
1364    if (E->getOpcode() == BO_Add)
1365      Offset += AdditionalOffset;
1366    else
1367      Offset -= AdditionalOffset;
1368    Result = APValue(Result.getLValueBase(), Offset);
1369    return true;
1370  }
1371
1372  // Handle cases like 4 + (unsigned long)&a
1373  if (E->getOpcode() == BO_Add &&
1374        RHSVal.isLValue() && Result.isInt()) {
1375    CharUnits Offset = RHSVal.getLValueOffset();
1376    Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1377    Result = APValue(RHSVal.getLValueBase(), Offset);
1378    return true;
1379  }
1380
1381  // All the following cases expect both operands to be an integer
1382  if (!Result.isInt() || !RHSVal.isInt())
1383    return false;
1384
1385  APSInt& RHS = RHSVal.getInt();
1386
1387  switch (E->getOpcode()) {
1388  default:
1389    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1390  case BO_Mul: return Success(Result.getInt() * RHS, E);
1391  case BO_Add: return Success(Result.getInt() + RHS, E);
1392  case BO_Sub: return Success(Result.getInt() - RHS, E);
1393  case BO_And: return Success(Result.getInt() & RHS, E);
1394  case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1395  case BO_Or:  return Success(Result.getInt() | RHS, E);
1396  case BO_Div:
1397    if (RHS == 0)
1398      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1399    return Success(Result.getInt() / RHS, E);
1400  case BO_Rem:
1401    if (RHS == 0)
1402      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1403    return Success(Result.getInt() % RHS, E);
1404  case BO_Shl: {
1405    // FIXME: Warn about out of range shift amounts!
1406    unsigned SA =
1407      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1408    return Success(Result.getInt() << SA, E);
1409  }
1410  case BO_Shr: {
1411    unsigned SA =
1412      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1413    return Success(Result.getInt() >> SA, E);
1414  }
1415
1416  case BO_LT: return Success(Result.getInt() < RHS, E);
1417  case BO_GT: return Success(Result.getInt() > RHS, E);
1418  case BO_LE: return Success(Result.getInt() <= RHS, E);
1419  case BO_GE: return Success(Result.getInt() >= RHS, E);
1420  case BO_EQ: return Success(Result.getInt() == RHS, E);
1421  case BO_NE: return Success(Result.getInt() != RHS, E);
1422  }
1423}
1424
1425bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1426  bool Cond;
1427  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1428    return false;
1429
1430  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1431}
1432
1433CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
1434  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1435  //   the result is the size of the referenced type."
1436  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1437  //   result shall be the alignment of the referenced type."
1438  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1439    T = Ref->getPointeeType();
1440
1441  // Get information about the alignment.
1442  unsigned CharSize = Info.Ctx.Target.getCharWidth();
1443
1444  // __alignof is defined to return the preferred alignment.
1445  return CharUnits::fromQuantity(
1446      Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
1447}
1448
1449CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1450  E = E->IgnoreParens();
1451
1452  // alignof decl is always accepted, even if it doesn't make sense: we default
1453  // to 1 in those cases.
1454  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1455    return Info.Ctx.getDeclAlign(DRE->getDecl(),
1456                                 /*RefAsPointee*/true);
1457
1458  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1459    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1460                                 /*RefAsPointee*/true);
1461
1462  return GetAlignOfType(E->getType());
1463}
1464
1465
1466/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1467/// expression's type.
1468bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1469  // Handle alignof separately.
1470  if (!E->isSizeOf()) {
1471    if (E->isArgumentType())
1472      return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
1473    else
1474      return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
1475  }
1476
1477  QualType SrcTy = E->getTypeOfArgument();
1478  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1479  //   the result is the size of the referenced type."
1480  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1481  //   result shall be the alignment of the referenced type."
1482  if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1483    SrcTy = Ref->getPointeeType();
1484
1485  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1486  // extension.
1487  if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1488    return Success(1, E);
1489
1490  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1491  if (!SrcTy->isConstantSizeType())
1492    return false;
1493
1494  // Get information about the size.
1495  return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
1496}
1497
1498bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1499  CharUnits Result;
1500  unsigned n = E->getNumComponents();
1501  OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1502  if (n == 0)
1503    return false;
1504  QualType CurrentType = E->getTypeSourceInfo()->getType();
1505  for (unsigned i = 0; i != n; ++i) {
1506    OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1507    switch (ON.getKind()) {
1508    case OffsetOfExpr::OffsetOfNode::Array: {
1509      Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1510      APSInt IdxResult;
1511      if (!EvaluateInteger(Idx, IdxResult, Info))
1512        return false;
1513      const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1514      if (!AT)
1515        return false;
1516      CurrentType = AT->getElementType();
1517      CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1518      Result += IdxResult.getSExtValue() * ElementSize;
1519        break;
1520    }
1521
1522    case OffsetOfExpr::OffsetOfNode::Field: {
1523      FieldDecl *MemberDecl = ON.getField();
1524      const RecordType *RT = CurrentType->getAs<RecordType>();
1525      if (!RT)
1526        return false;
1527      RecordDecl *RD = RT->getDecl();
1528      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1529      unsigned i = 0;
1530      // FIXME: It would be nice if we didn't have to loop here!
1531      for (RecordDecl::field_iterator Field = RD->field_begin(),
1532                                      FieldEnd = RD->field_end();
1533           Field != FieldEnd; (void)++Field, ++i) {
1534        if (*Field == MemberDecl)
1535          break;
1536      }
1537      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1538      Result += CharUnits::fromQuantity(
1539                           RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
1540      CurrentType = MemberDecl->getType().getNonReferenceType();
1541      break;
1542    }
1543
1544    case OffsetOfExpr::OffsetOfNode::Identifier:
1545      llvm_unreachable("dependent __builtin_offsetof");
1546      return false;
1547
1548    case OffsetOfExpr::OffsetOfNode::Base: {
1549      CXXBaseSpecifier *BaseSpec = ON.getBase();
1550      if (BaseSpec->isVirtual())
1551        return false;
1552
1553      // Find the layout of the class whose base we are looking into.
1554      const RecordType *RT = CurrentType->getAs<RecordType>();
1555      if (!RT)
1556        return false;
1557      RecordDecl *RD = RT->getDecl();
1558      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1559
1560      // Find the base class itself.
1561      CurrentType = BaseSpec->getType();
1562      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1563      if (!BaseRT)
1564        return false;
1565
1566      // Add the offset to the base.
1567      Result += CharUnits::fromQuantity(
1568                RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1569                                        / Info.Ctx.getCharWidth());
1570      break;
1571    }
1572    }
1573  }
1574  return Success(Result.getQuantity(), E);
1575}
1576
1577bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1578  if (E->getOpcode() == UO_LNot) {
1579    // LNot's operand isn't necessarily an integer, so we handle it specially.
1580    bool bres;
1581    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1582      return false;
1583    return Success(!bres, E);
1584  }
1585
1586  // Only handle integral operations...
1587  if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
1588    return false;
1589
1590  // Get the operand value into 'Result'.
1591  if (!Visit(E->getSubExpr()))
1592    return false;
1593
1594  switch (E->getOpcode()) {
1595  default:
1596    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1597    // See C99 6.6p3.
1598    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1599  case UO_Extension:
1600    // FIXME: Should extension allow i-c-e extension expressions in its scope?
1601    // If so, we could clear the diagnostic ID.
1602    return true;
1603  case UO_Plus:
1604    // The result is always just the subexpr.
1605    return true;
1606  case UO_Minus:
1607    if (!Result.isInt()) return false;
1608    return Success(-Result.getInt(), E);
1609  case UO_Not:
1610    if (!Result.isInt()) return false;
1611    return Success(~Result.getInt(), E);
1612  }
1613}
1614
1615/// HandleCast - This is used to evaluate implicit or explicit casts where the
1616/// result type is integer.
1617bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1618  Expr *SubExpr = E->getSubExpr();
1619  QualType DestType = E->getType();
1620  QualType SrcType = SubExpr->getType();
1621
1622  if (DestType->isBooleanType()) {
1623    bool BoolResult;
1624    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1625      return false;
1626    return Success(BoolResult, E);
1627  }
1628
1629  // Handle simple integer->integer casts.
1630  if (SrcType->isIntegralOrEnumerationType()) {
1631    if (!Visit(SubExpr))
1632      return false;
1633
1634    if (!Result.isInt()) {
1635      // Only allow casts of lvalues if they are lossless.
1636      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1637    }
1638
1639    return Success(HandleIntToIntCast(DestType, SrcType,
1640                                      Result.getInt(), Info.Ctx), E);
1641  }
1642
1643  // FIXME: Clean this up!
1644  if (SrcType->isPointerType()) {
1645    LValue LV;
1646    if (!EvaluatePointer(SubExpr, LV, Info))
1647      return false;
1648
1649    if (LV.getLValueBase()) {
1650      // Only allow based lvalue casts if they are lossless.
1651      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1652        return false;
1653
1654      LV.moveInto(Result);
1655      return true;
1656    }
1657
1658    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1659                                         SrcType);
1660    return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1661  }
1662
1663  if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1664    // This handles double-conversion cases, where there's both
1665    // an l-value promotion and an implicit conversion to int.
1666    LValue LV;
1667    if (!EvaluateLValue(SubExpr, LV, Info))
1668      return false;
1669
1670    if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1671      return false;
1672
1673    LV.moveInto(Result);
1674    return true;
1675  }
1676
1677  if (SrcType->isAnyComplexType()) {
1678    ComplexValue C;
1679    if (!EvaluateComplex(SubExpr, C, Info))
1680      return false;
1681    if (C.isComplexFloat())
1682      return Success(HandleFloatToIntCast(DestType, SrcType,
1683                                          C.getComplexFloatReal(), Info.Ctx),
1684                     E);
1685    else
1686      return Success(HandleIntToIntCast(DestType, SrcType,
1687                                        C.getComplexIntReal(), Info.Ctx), E);
1688  }
1689  // FIXME: Handle vectors
1690
1691  if (!SrcType->isRealFloatingType())
1692    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1693
1694  APFloat F(0.0);
1695  if (!EvaluateFloat(SubExpr, F, Info))
1696    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1697
1698  return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1699}
1700
1701bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1702  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1703    ComplexValue LV;
1704    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1705      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1706    return Success(LV.getComplexIntReal(), E);
1707  }
1708
1709  return Visit(E->getSubExpr());
1710}
1711
1712bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1713  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1714    ComplexValue LV;
1715    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1716      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1717    return Success(LV.getComplexIntImag(), E);
1718  }
1719
1720  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1721    Info.EvalResult.HasSideEffects = true;
1722  return Success(0, E);
1723}
1724
1725//===----------------------------------------------------------------------===//
1726// Float Evaluation
1727//===----------------------------------------------------------------------===//
1728
1729namespace {
1730class FloatExprEvaluator
1731  : public StmtVisitor<FloatExprEvaluator, bool> {
1732  EvalInfo &Info;
1733  APFloat &Result;
1734public:
1735  FloatExprEvaluator(EvalInfo &info, APFloat &result)
1736    : Info(info), Result(result) {}
1737
1738  bool VisitStmt(Stmt *S) {
1739    return false;
1740  }
1741
1742  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1743  bool VisitCallExpr(const CallExpr *E);
1744
1745  bool VisitUnaryOperator(const UnaryOperator *E);
1746  bool VisitBinaryOperator(const BinaryOperator *E);
1747  bool VisitFloatingLiteral(const FloatingLiteral *E);
1748  bool VisitCastExpr(CastExpr *E);
1749  bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1750  bool VisitConditionalOperator(ConditionalOperator *E);
1751
1752  bool VisitChooseExpr(const ChooseExpr *E)
1753    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1754  bool VisitUnaryExtension(const UnaryOperator *E)
1755    { return Visit(E->getSubExpr()); }
1756  bool VisitUnaryReal(const UnaryOperator *E);
1757  bool VisitUnaryImag(const UnaryOperator *E);
1758
1759  // FIXME: Missing: array subscript of vector, member of vector,
1760  //                 ImplicitValueInitExpr
1761};
1762} // end anonymous namespace
1763
1764static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1765  assert(E->getType()->isRealFloatingType());
1766  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1767}
1768
1769static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1770                                  QualType ResultTy,
1771                                  const Expr *Arg,
1772                                  bool SNaN,
1773                                  llvm::APFloat &Result) {
1774  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1775  if (!S) return false;
1776
1777  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1778
1779  llvm::APInt fill;
1780
1781  // Treat empty strings as if they were zero.
1782  if (S->getString().empty())
1783    fill = llvm::APInt(32, 0);
1784  else if (S->getString().getAsInteger(0, fill))
1785    return false;
1786
1787  if (SNaN)
1788    Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1789  else
1790    Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1791  return true;
1792}
1793
1794bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1795  switch (E->isBuiltinCall(Info.Ctx)) {
1796  default: return false;
1797  case Builtin::BI__builtin_huge_val:
1798  case Builtin::BI__builtin_huge_valf:
1799  case Builtin::BI__builtin_huge_vall:
1800  case Builtin::BI__builtin_inf:
1801  case Builtin::BI__builtin_inff:
1802  case Builtin::BI__builtin_infl: {
1803    const llvm::fltSemantics &Sem =
1804      Info.Ctx.getFloatTypeSemantics(E->getType());
1805    Result = llvm::APFloat::getInf(Sem);
1806    return true;
1807  }
1808
1809  case Builtin::BI__builtin_nans:
1810  case Builtin::BI__builtin_nansf:
1811  case Builtin::BI__builtin_nansl:
1812    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1813                                 true, Result);
1814
1815  case Builtin::BI__builtin_nan:
1816  case Builtin::BI__builtin_nanf:
1817  case Builtin::BI__builtin_nanl:
1818    // If this is __builtin_nan() turn this into a nan, otherwise we
1819    // can't constant fold it.
1820    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1821                                 false, Result);
1822
1823  case Builtin::BI__builtin_fabs:
1824  case Builtin::BI__builtin_fabsf:
1825  case Builtin::BI__builtin_fabsl:
1826    if (!EvaluateFloat(E->getArg(0), Result, Info))
1827      return false;
1828
1829    if (Result.isNegative())
1830      Result.changeSign();
1831    return true;
1832
1833  case Builtin::BI__builtin_copysign:
1834  case Builtin::BI__builtin_copysignf:
1835  case Builtin::BI__builtin_copysignl: {
1836    APFloat RHS(0.);
1837    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1838        !EvaluateFloat(E->getArg(1), RHS, Info))
1839      return false;
1840    Result.copySign(RHS);
1841    return true;
1842  }
1843  }
1844}
1845
1846bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1847  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1848    ComplexValue CV;
1849    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1850      return false;
1851    Result = CV.FloatReal;
1852    return true;
1853  }
1854
1855  return Visit(E->getSubExpr());
1856}
1857
1858bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1859  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1860    ComplexValue CV;
1861    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1862      return false;
1863    Result = CV.FloatImag;
1864    return true;
1865  }
1866
1867  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1868    Info.EvalResult.HasSideEffects = true;
1869  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
1870  Result = llvm::APFloat::getZero(Sem);
1871  return true;
1872}
1873
1874bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1875  if (E->getOpcode() == UO_Deref)
1876    return false;
1877
1878  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1879    return false;
1880
1881  switch (E->getOpcode()) {
1882  default: return false;
1883  case UO_Plus:
1884    return true;
1885  case UO_Minus:
1886    Result.changeSign();
1887    return true;
1888  }
1889}
1890
1891bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1892  if (E->getOpcode() == BO_Comma) {
1893    if (!EvaluateFloat(E->getRHS(), Result, Info))
1894      return false;
1895
1896    // If we can't evaluate the LHS, it might have side effects;
1897    // conservatively mark it.
1898    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1899      Info.EvalResult.HasSideEffects = true;
1900
1901    return true;
1902  }
1903
1904  // FIXME: Diagnostics?  I really don't understand how the warnings
1905  // and errors are supposed to work.
1906  APFloat RHS(0.0);
1907  if (!EvaluateFloat(E->getLHS(), Result, Info))
1908    return false;
1909  if (!EvaluateFloat(E->getRHS(), RHS, Info))
1910    return false;
1911
1912  switch (E->getOpcode()) {
1913  default: return false;
1914  case BO_Mul:
1915    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1916    return true;
1917  case BO_Add:
1918    Result.add(RHS, APFloat::rmNearestTiesToEven);
1919    return true;
1920  case BO_Sub:
1921    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1922    return true;
1923  case BO_Div:
1924    Result.divide(RHS, APFloat::rmNearestTiesToEven);
1925    return true;
1926  }
1927}
1928
1929bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1930  Result = E->getValue();
1931  return true;
1932}
1933
1934bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1935  Expr* SubExpr = E->getSubExpr();
1936
1937  if (SubExpr->getType()->isIntegralOrEnumerationType()) {
1938    APSInt IntResult;
1939    if (!EvaluateInteger(SubExpr, IntResult, Info))
1940      return false;
1941    Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1942                                  IntResult, Info.Ctx);
1943    return true;
1944  }
1945  if (SubExpr->getType()->isRealFloatingType()) {
1946    if (!Visit(SubExpr))
1947      return false;
1948    Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1949                                    Result, Info.Ctx);
1950    return true;
1951  }
1952  // FIXME: Handle complex types
1953
1954  return false;
1955}
1956
1957bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
1958  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1959  return true;
1960}
1961
1962bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1963  bool Cond;
1964  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1965    return false;
1966
1967  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1968}
1969
1970//===----------------------------------------------------------------------===//
1971// Complex Evaluation (for float and integer)
1972//===----------------------------------------------------------------------===//
1973
1974namespace {
1975class ComplexExprEvaluator
1976  : public StmtVisitor<ComplexExprEvaluator, bool> {
1977  EvalInfo &Info;
1978  ComplexValue &Result;
1979
1980public:
1981  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
1982    : Info(info), Result(Result) {}
1983
1984  //===--------------------------------------------------------------------===//
1985  //                            Visitor Methods
1986  //===--------------------------------------------------------------------===//
1987
1988  bool VisitStmt(Stmt *S) {
1989    return false;
1990  }
1991
1992  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1993
1994  bool VisitImaginaryLiteral(ImaginaryLiteral *E);
1995
1996  bool VisitCastExpr(CastExpr *E);
1997
1998  bool VisitBinaryOperator(const BinaryOperator *E);
1999  bool VisitChooseExpr(const ChooseExpr *E)
2000    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
2001  bool VisitUnaryExtension(const UnaryOperator *E)
2002    { return Visit(E->getSubExpr()); }
2003  // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
2004  //                conditional ?:, comma
2005};
2006} // end anonymous namespace
2007
2008static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2009                            EvalInfo &Info) {
2010  assert(E->getType()->isAnyComplexType());
2011  return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
2012}
2013
2014bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2015  Expr* SubExpr = E->getSubExpr();
2016
2017  if (SubExpr->getType()->isRealFloatingType()) {
2018    Result.makeComplexFloat();
2019    APFloat &Imag = Result.FloatImag;
2020    if (!EvaluateFloat(SubExpr, Imag, Info))
2021      return false;
2022
2023    Result.FloatReal = APFloat(Imag.getSemantics());
2024    return true;
2025  } else {
2026    assert(SubExpr->getType()->isIntegerType() &&
2027           "Unexpected imaginary literal.");
2028
2029    Result.makeComplexInt();
2030    APSInt &Imag = Result.IntImag;
2031    if (!EvaluateInteger(SubExpr, Imag, Info))
2032      return false;
2033
2034    Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2035    return true;
2036  }
2037}
2038
2039bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
2040  Expr* SubExpr = E->getSubExpr();
2041  QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
2042  QualType SubType = SubExpr->getType();
2043
2044  if (SubType->isRealFloatingType()) {
2045    APFloat &Real = Result.FloatReal;
2046    if (!EvaluateFloat(SubExpr, Real, Info))
2047      return false;
2048
2049    if (EltType->isRealFloatingType()) {
2050      Result.makeComplexFloat();
2051      Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
2052      Result.FloatImag = APFloat(Real.getSemantics());
2053      return true;
2054    } else {
2055      Result.makeComplexInt();
2056      Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
2057      Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
2058                              !Result.IntReal.isSigned());
2059      return true;
2060    }
2061  } else if (SubType->isIntegerType()) {
2062    APSInt &Real = Result.IntReal;
2063    if (!EvaluateInteger(SubExpr, Real, Info))
2064      return false;
2065
2066    if (EltType->isRealFloatingType()) {
2067      Result.makeComplexFloat();
2068      Result.FloatReal
2069        = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
2070      Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
2071      return true;
2072    } else {
2073      Result.makeComplexInt();
2074      Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
2075      Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2076      return true;
2077    }
2078  } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
2079    if (!Visit(SubExpr))
2080      return false;
2081
2082    QualType SrcType = CT->getElementType();
2083
2084    if (Result.isComplexFloat()) {
2085      if (EltType->isRealFloatingType()) {
2086        Result.makeComplexFloat();
2087        Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
2088                                                  Result.FloatReal,
2089                                                  Info.Ctx);
2090        Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
2091                                                  Result.FloatImag,
2092                                                  Info.Ctx);
2093        return true;
2094      } else {
2095        Result.makeComplexInt();
2096        Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
2097                                              Result.FloatReal,
2098                                              Info.Ctx);
2099        Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
2100                                              Result.FloatImag,
2101                                              Info.Ctx);
2102        return true;
2103      }
2104    } else {
2105      assert(Result.isComplexInt() && "Invalid evaluate result.");
2106      if (EltType->isRealFloatingType()) {
2107        Result.makeComplexFloat();
2108        Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
2109                                                Result.IntReal,
2110                                                Info.Ctx);
2111        Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2112                                                Result.IntImag,
2113                                                Info.Ctx);
2114        return true;
2115      } else {
2116        Result.makeComplexInt();
2117        Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2118                                            Result.IntReal,
2119                                            Info.Ctx);
2120        Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2121                                            Result.IntImag,
2122                                            Info.Ctx);
2123        return true;
2124      }
2125    }
2126  }
2127
2128  // FIXME: Handle more casts.
2129  return false;
2130}
2131
2132bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2133  if (!Visit(E->getLHS()))
2134    return false;
2135
2136  ComplexValue RHS;
2137  if (!EvaluateComplex(E->getRHS(), RHS, Info))
2138    return false;
2139
2140  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2141         "Invalid operands to binary operator.");
2142  switch (E->getOpcode()) {
2143  default: return false;
2144  case BO_Add:
2145    if (Result.isComplexFloat()) {
2146      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2147                                       APFloat::rmNearestTiesToEven);
2148      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2149                                       APFloat::rmNearestTiesToEven);
2150    } else {
2151      Result.getComplexIntReal() += RHS.getComplexIntReal();
2152      Result.getComplexIntImag() += RHS.getComplexIntImag();
2153    }
2154    break;
2155  case BO_Sub:
2156    if (Result.isComplexFloat()) {
2157      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2158                                            APFloat::rmNearestTiesToEven);
2159      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2160                                            APFloat::rmNearestTiesToEven);
2161    } else {
2162      Result.getComplexIntReal() -= RHS.getComplexIntReal();
2163      Result.getComplexIntImag() -= RHS.getComplexIntImag();
2164    }
2165    break;
2166  case BO_Mul:
2167    if (Result.isComplexFloat()) {
2168      ComplexValue LHS = Result;
2169      APFloat &LHS_r = LHS.getComplexFloatReal();
2170      APFloat &LHS_i = LHS.getComplexFloatImag();
2171      APFloat &RHS_r = RHS.getComplexFloatReal();
2172      APFloat &RHS_i = RHS.getComplexFloatImag();
2173
2174      APFloat Tmp = LHS_r;
2175      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2176      Result.getComplexFloatReal() = Tmp;
2177      Tmp = LHS_i;
2178      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2179      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2180
2181      Tmp = LHS_r;
2182      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2183      Result.getComplexFloatImag() = Tmp;
2184      Tmp = LHS_i;
2185      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2186      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2187    } else {
2188      ComplexValue LHS = Result;
2189      Result.getComplexIntReal() =
2190        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2191         LHS.getComplexIntImag() * RHS.getComplexIntImag());
2192      Result.getComplexIntImag() =
2193        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2194         LHS.getComplexIntImag() * RHS.getComplexIntReal());
2195    }
2196    break;
2197  }
2198
2199  return true;
2200}
2201
2202//===----------------------------------------------------------------------===//
2203// Top level Expr::Evaluate method.
2204//===----------------------------------------------------------------------===//
2205
2206/// Evaluate - Return true if this is a constant which we can fold using
2207/// any crazy technique (that has nothing to do with language standards) that
2208/// we want to.  If this function returns true, it returns the folded constant
2209/// in Result.
2210bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2211  const Expr *E = this;
2212  EvalInfo Info(Ctx, Result);
2213  if (E->getType()->isVectorType()) {
2214    if (!EvaluateVector(E, Info.EvalResult.Val, Info))
2215      return false;
2216  } else if (E->getType()->isIntegerType()) {
2217    if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
2218      return false;
2219    if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2220      return false;
2221  } else if (E->getType()->hasPointerRepresentation()) {
2222    LValue LV;
2223    if (!EvaluatePointer(E, LV, Info))
2224      return false;
2225    if (!IsGlobalLValue(LV.Base))
2226      return false;
2227    LV.moveInto(Info.EvalResult.Val);
2228  } else if (E->getType()->isRealFloatingType()) {
2229    llvm::APFloat F(0.0);
2230    if (!EvaluateFloat(E, F, Info))
2231      return false;
2232
2233    Info.EvalResult.Val = APValue(F);
2234  } else if (E->getType()->isAnyComplexType()) {
2235    ComplexValue C;
2236    if (!EvaluateComplex(E, C, Info))
2237      return false;
2238    C.moveInto(Info.EvalResult.Val);
2239  } else
2240    return false;
2241
2242  return true;
2243}
2244
2245bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2246  EvalResult Scratch;
2247  EvalInfo Info(Ctx, Scratch);
2248
2249  return HandleConversionToBool(this, Result, Info);
2250}
2251
2252bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2253  EvalInfo Info(Ctx, Result);
2254
2255  LValue LV;
2256  if (EvaluateLValue(this, LV, Info) &&
2257      !Result.HasSideEffects &&
2258      IsGlobalLValue(LV.Base)) {
2259    LV.moveInto(Result.Val);
2260    return true;
2261  }
2262  return false;
2263}
2264
2265bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2266  EvalInfo Info(Ctx, Result);
2267
2268  LValue LV;
2269  if (EvaluateLValue(this, LV, Info)) {
2270    LV.moveInto(Result.Val);
2271    return true;
2272  }
2273  return false;
2274}
2275
2276/// isEvaluatable - Call Evaluate to see if this expression can be constant
2277/// folded, but discard the result.
2278bool Expr::isEvaluatable(ASTContext &Ctx) const {
2279  EvalResult Result;
2280  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
2281}
2282
2283bool Expr::HasSideEffects(ASTContext &Ctx) const {
2284  Expr::EvalResult Result;
2285  EvalInfo Info(Ctx, Result);
2286  return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2287}
2288
2289APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
2290  EvalResult EvalResult;
2291  bool Result = Evaluate(EvalResult, Ctx);
2292  Result = Result;
2293  assert(Result && "Could not evaluate expression");
2294  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
2295
2296  return EvalResult.Val.getInt();
2297}
2298
2299 bool Expr::EvalResult::isGlobalLValue() const {
2300   assert(Val.isLValue());
2301   return IsGlobalLValue(Val.getLValueBase());
2302 }
2303
2304
2305/// isIntegerConstantExpr - this recursive routine will test if an expression is
2306/// an integer constant expression.
2307
2308/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2309/// comma, etc
2310///
2311/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
2312/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
2313/// cast+dereference.
2314
2315// CheckICE - This function does the fundamental ICE checking: the returned
2316// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2317// Note that to reduce code duplication, this helper does no evaluation
2318// itself; the caller checks whether the expression is evaluatable, and
2319// in the rare cases where CheckICE actually cares about the evaluated
2320// value, it calls into Evalute.
2321//
2322// Meanings of Val:
2323// 0: This expression is an ICE if it can be evaluated by Evaluate.
2324// 1: This expression is not an ICE, but if it isn't evaluated, it's
2325//    a legal subexpression for an ICE. This return value is used to handle
2326//    the comma operator in C99 mode.
2327// 2: This expression is not an ICE, and is not a legal subexpression for one.
2328
2329namespace {
2330
2331struct ICEDiag {
2332  unsigned Val;
2333  SourceLocation Loc;
2334
2335  public:
2336  ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2337  ICEDiag() : Val(0) {}
2338};
2339
2340}
2341
2342static ICEDiag NoDiag() { return ICEDiag(); }
2343
2344static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2345  Expr::EvalResult EVResult;
2346  if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2347      !EVResult.Val.isInt()) {
2348    return ICEDiag(2, E->getLocStart());
2349  }
2350  return NoDiag();
2351}
2352
2353static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2354  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2355  if (!E->getType()->isIntegralOrEnumerationType()) {
2356    return ICEDiag(2, E->getLocStart());
2357  }
2358
2359  switch (E->getStmtClass()) {
2360#define STMT(Node, Base) case Expr::Node##Class:
2361#define EXPR(Node, Base)
2362#include "clang/AST/StmtNodes.inc"
2363  case Expr::PredefinedExprClass:
2364  case Expr::FloatingLiteralClass:
2365  case Expr::ImaginaryLiteralClass:
2366  case Expr::StringLiteralClass:
2367  case Expr::ArraySubscriptExprClass:
2368  case Expr::MemberExprClass:
2369  case Expr::CompoundAssignOperatorClass:
2370  case Expr::CompoundLiteralExprClass:
2371  case Expr::ExtVectorElementExprClass:
2372  case Expr::InitListExprClass:
2373  case Expr::DesignatedInitExprClass:
2374  case Expr::ImplicitValueInitExprClass:
2375  case Expr::ParenListExprClass:
2376  case Expr::VAArgExprClass:
2377  case Expr::AddrLabelExprClass:
2378  case Expr::StmtExprClass:
2379  case Expr::CXXMemberCallExprClass:
2380  case Expr::CXXDynamicCastExprClass:
2381  case Expr::CXXTypeidExprClass:
2382  case Expr::CXXUuidofExprClass:
2383  case Expr::CXXNullPtrLiteralExprClass:
2384  case Expr::CXXThisExprClass:
2385  case Expr::CXXThrowExprClass:
2386  case Expr::CXXNewExprClass:
2387  case Expr::CXXDeleteExprClass:
2388  case Expr::CXXPseudoDestructorExprClass:
2389  case Expr::UnresolvedLookupExprClass:
2390  case Expr::DependentScopeDeclRefExprClass:
2391  case Expr::CXXConstructExprClass:
2392  case Expr::CXXBindTemporaryExprClass:
2393  case Expr::CXXExprWithTemporariesClass:
2394  case Expr::CXXTemporaryObjectExprClass:
2395  case Expr::CXXUnresolvedConstructExprClass:
2396  case Expr::CXXDependentScopeMemberExprClass:
2397  case Expr::UnresolvedMemberExprClass:
2398  case Expr::ObjCStringLiteralClass:
2399  case Expr::ObjCEncodeExprClass:
2400  case Expr::ObjCMessageExprClass:
2401  case Expr::ObjCSelectorExprClass:
2402  case Expr::ObjCProtocolExprClass:
2403  case Expr::ObjCIvarRefExprClass:
2404  case Expr::ObjCPropertyRefExprClass:
2405  case Expr::ObjCImplicitSetterGetterRefExprClass:
2406  case Expr::ObjCSuperExprClass:
2407  case Expr::ObjCIsaExprClass:
2408  case Expr::ShuffleVectorExprClass:
2409  case Expr::BlockExprClass:
2410  case Expr::BlockDeclRefExprClass:
2411  case Expr::NoStmtClass:
2412    return ICEDiag(2, E->getLocStart());
2413
2414  case Expr::GNUNullExprClass:
2415    // GCC considers the GNU __null value to be an integral constant expression.
2416    return NoDiag();
2417
2418  case Expr::ParenExprClass:
2419    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2420  case Expr::IntegerLiteralClass:
2421  case Expr::CharacterLiteralClass:
2422  case Expr::CXXBoolLiteralExprClass:
2423  case Expr::CXXScalarValueInitExprClass:
2424  case Expr::TypesCompatibleExprClass:
2425  case Expr::UnaryTypeTraitExprClass:
2426    return NoDiag();
2427  case Expr::CallExprClass:
2428  case Expr::CXXOperatorCallExprClass: {
2429    const CallExpr *CE = cast<CallExpr>(E);
2430    if (CE->isBuiltinCall(Ctx))
2431      return CheckEvalInICE(E, Ctx);
2432    return ICEDiag(2, E->getLocStart());
2433  }
2434  case Expr::DeclRefExprClass:
2435    if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2436      return NoDiag();
2437    if (Ctx.getLangOptions().CPlusPlus &&
2438        E->getType().getCVRQualifiers() == Qualifiers::Const) {
2439      const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2440
2441      // Parameter variables are never constants.  Without this check,
2442      // getAnyInitializer() can find a default argument, which leads
2443      // to chaos.
2444      if (isa<ParmVarDecl>(D))
2445        return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2446
2447      // C++ 7.1.5.1p2
2448      //   A variable of non-volatile const-qualified integral or enumeration
2449      //   type initialized by an ICE can be used in ICEs.
2450      if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2451        Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2452        if (Quals.hasVolatile() || !Quals.hasConst())
2453          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2454
2455        // Look for a declaration of this variable that has an initializer.
2456        const VarDecl *ID = 0;
2457        const Expr *Init = Dcl->getAnyInitializer(ID);
2458        if (Init) {
2459          if (ID->isInitKnownICE()) {
2460            // We have already checked whether this subexpression is an
2461            // integral constant expression.
2462            if (ID->isInitICE())
2463              return NoDiag();
2464            else
2465              return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2466          }
2467
2468          // It's an ICE whether or not the definition we found is
2469          // out-of-line.  See DR 721 and the discussion in Clang PR
2470          // 6206 for details.
2471
2472          if (Dcl->isCheckingICE()) {
2473            return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2474          }
2475
2476          Dcl->setCheckingICE();
2477          ICEDiag Result = CheckICE(Init, Ctx);
2478          // Cache the result of the ICE test.
2479          Dcl->setInitKnownICE(Result.Val == 0);
2480          return Result;
2481        }
2482      }
2483    }
2484    return ICEDiag(2, E->getLocStart());
2485  case Expr::UnaryOperatorClass: {
2486    const UnaryOperator *Exp = cast<UnaryOperator>(E);
2487    switch (Exp->getOpcode()) {
2488    case UO_PostInc:
2489    case UO_PostDec:
2490    case UO_PreInc:
2491    case UO_PreDec:
2492    case UO_AddrOf:
2493    case UO_Deref:
2494      return ICEDiag(2, E->getLocStart());
2495    case UO_Extension:
2496    case UO_LNot:
2497    case UO_Plus:
2498    case UO_Minus:
2499    case UO_Not:
2500    case UO_Real:
2501    case UO_Imag:
2502      return CheckICE(Exp->getSubExpr(), Ctx);
2503    }
2504
2505    // OffsetOf falls through here.
2506  }
2507  case Expr::OffsetOfExprClass: {
2508      // Note that per C99, offsetof must be an ICE. And AFAIK, using
2509      // Evaluate matches the proposed gcc behavior for cases like
2510      // "offsetof(struct s{int x[4];}, x[!.0])".  This doesn't affect
2511      // compliance: we should warn earlier for offsetof expressions with
2512      // array subscripts that aren't ICEs, and if the array subscripts
2513      // are ICEs, the value of the offsetof must be an integer constant.
2514      return CheckEvalInICE(E, Ctx);
2515  }
2516  case Expr::SizeOfAlignOfExprClass: {
2517    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2518    if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2519      return ICEDiag(2, E->getLocStart());
2520    return NoDiag();
2521  }
2522  case Expr::BinaryOperatorClass: {
2523    const BinaryOperator *Exp = cast<BinaryOperator>(E);
2524    switch (Exp->getOpcode()) {
2525    case BO_PtrMemD:
2526    case BO_PtrMemI:
2527    case BO_Assign:
2528    case BO_MulAssign:
2529    case BO_DivAssign:
2530    case BO_RemAssign:
2531    case BO_AddAssign:
2532    case BO_SubAssign:
2533    case BO_ShlAssign:
2534    case BO_ShrAssign:
2535    case BO_AndAssign:
2536    case BO_XorAssign:
2537    case BO_OrAssign:
2538      return ICEDiag(2, E->getLocStart());
2539
2540    case BO_Mul:
2541    case BO_Div:
2542    case BO_Rem:
2543    case BO_Add:
2544    case BO_Sub:
2545    case BO_Shl:
2546    case BO_Shr:
2547    case BO_LT:
2548    case BO_GT:
2549    case BO_LE:
2550    case BO_GE:
2551    case BO_EQ:
2552    case BO_NE:
2553    case BO_And:
2554    case BO_Xor:
2555    case BO_Or:
2556    case BO_Comma: {
2557      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2558      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2559      if (Exp->getOpcode() == BO_Div ||
2560          Exp->getOpcode() == BO_Rem) {
2561        // Evaluate gives an error for undefined Div/Rem, so make sure
2562        // we don't evaluate one.
2563        if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2564          llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2565          if (REval == 0)
2566            return ICEDiag(1, E->getLocStart());
2567          if (REval.isSigned() && REval.isAllOnesValue()) {
2568            llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2569            if (LEval.isMinSignedValue())
2570              return ICEDiag(1, E->getLocStart());
2571          }
2572        }
2573      }
2574      if (Exp->getOpcode() == BO_Comma) {
2575        if (Ctx.getLangOptions().C99) {
2576          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2577          // if it isn't evaluated.
2578          if (LHSResult.Val == 0 && RHSResult.Val == 0)
2579            return ICEDiag(1, E->getLocStart());
2580        } else {
2581          // In both C89 and C++, commas in ICEs are illegal.
2582          return ICEDiag(2, E->getLocStart());
2583        }
2584      }
2585      if (LHSResult.Val >= RHSResult.Val)
2586        return LHSResult;
2587      return RHSResult;
2588    }
2589    case BO_LAnd:
2590    case BO_LOr: {
2591      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2592      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2593      if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2594        // Rare case where the RHS has a comma "side-effect"; we need
2595        // to actually check the condition to see whether the side
2596        // with the comma is evaluated.
2597        if ((Exp->getOpcode() == BO_LAnd) !=
2598            (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2599          return RHSResult;
2600        return NoDiag();
2601      }
2602
2603      if (LHSResult.Val >= RHSResult.Val)
2604        return LHSResult;
2605      return RHSResult;
2606    }
2607    }
2608  }
2609  case Expr::ImplicitCastExprClass:
2610  case Expr::CStyleCastExprClass:
2611  case Expr::CXXFunctionalCastExprClass:
2612  case Expr::CXXStaticCastExprClass:
2613  case Expr::CXXReinterpretCastExprClass:
2614  case Expr::CXXConstCastExprClass: {
2615    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2616    if (SubExpr->getType()->isIntegralOrEnumerationType())
2617      return CheckICE(SubExpr, Ctx);
2618    if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2619      return NoDiag();
2620    return ICEDiag(2, E->getLocStart());
2621  }
2622  case Expr::ConditionalOperatorClass: {
2623    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2624    // If the condition (ignoring parens) is a __builtin_constant_p call,
2625    // then only the true side is actually considered in an integer constant
2626    // expression, and it is fully evaluated.  This is an important GNU
2627    // extension.  See GCC PR38377 for discussion.
2628    if (const CallExpr *CallCE
2629        = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2630      if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2631        Expr::EvalResult EVResult;
2632        if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2633            !EVResult.Val.isInt()) {
2634          return ICEDiag(2, E->getLocStart());
2635        }
2636        return NoDiag();
2637      }
2638    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2639    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2640    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2641    if (CondResult.Val == 2)
2642      return CondResult;
2643    if (TrueResult.Val == 2)
2644      return TrueResult;
2645    if (FalseResult.Val == 2)
2646      return FalseResult;
2647    if (CondResult.Val == 1)
2648      return CondResult;
2649    if (TrueResult.Val == 0 && FalseResult.Val == 0)
2650      return NoDiag();
2651    // Rare case where the diagnostics depend on which side is evaluated
2652    // Note that if we get here, CondResult is 0, and at least one of
2653    // TrueResult and FalseResult is non-zero.
2654    if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2655      return FalseResult;
2656    }
2657    return TrueResult;
2658  }
2659  case Expr::CXXDefaultArgExprClass:
2660    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2661  case Expr::ChooseExprClass: {
2662    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2663  }
2664  }
2665
2666  // Silence a GCC warning
2667  return ICEDiag(2, E->getLocStart());
2668}
2669
2670bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2671                                 SourceLocation *Loc, bool isEvaluated) const {
2672  ICEDiag d = CheckICE(this, Ctx);
2673  if (d.Val != 0) {
2674    if (Loc) *Loc = d.Loc;
2675    return false;
2676  }
2677  EvalResult EvalResult;
2678  if (!Evaluate(EvalResult, Ctx))
2679    llvm_unreachable("ICE cannot be evaluated!");
2680  assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2681  assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2682  Result = EvalResult.Val.getInt();
2683  return true;
2684}
2685