ExprConstant.cpp revision 4765fa05b5652fcc4356371c2f481d0ea9a1b007
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_NoOp:
536  case CK_BitCast:
537  case CK_LValueBitCast:
538  case CK_AnyPointerToObjCPointerCast:
539  case CK_AnyPointerToBlockPointerCast:
540    return Visit(SubExpr);
541
542  case CK_DerivedToBase:
543  case CK_UncheckedDerivedToBase: {
544    LValue BaseLV;
545    if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
546      return false;
547
548    // Now figure out the necessary offset to add to the baseLV to get from
549    // the derived class to the base class.
550    uint64_t Offset = 0;
551
552    QualType Ty = E->getSubExpr()->getType();
553    const CXXRecordDecl *DerivedDecl =
554      Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
555
556    for (CastExpr::path_const_iterator PathI = E->path_begin(),
557         PathE = E->path_end(); PathI != PathE; ++PathI) {
558      const CXXBaseSpecifier *Base = *PathI;
559
560      // FIXME: If the base is virtual, we'd need to determine the type of the
561      // most derived class and we don't support that right now.
562      if (Base->isVirtual())
563        return false;
564
565      const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
566      const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
567
568      Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
569      DerivedDecl = BaseDecl;
570    }
571
572    Result.Base = BaseLV.getLValueBase();
573    Result.Offset = BaseLV.getLValueOffset() +
574      CharUnits::fromQuantity(Offset / Info.Ctx.getCharWidth());
575    return true;
576  }
577
578  case CK_NullToPointer: {
579    Result.Base = 0;
580    Result.Offset = CharUnits::Zero();
581    return true;
582  }
583
584  case CK_IntegralToPointer: {
585    APValue Value;
586    if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
587      break;
588
589    if (Value.isInt()) {
590      Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
591      Result.Base = 0;
592      Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
593      return true;
594    } else {
595      // Cast is of an lvalue, no need to change value.
596      Result.Base = Value.getLValueBase();
597      Result.Offset = Value.getLValueOffset();
598      return true;
599    }
600  }
601  case CK_ArrayToPointerDecay:
602  case CK_FunctionToPointerDecay:
603    return EvaluateLValue(SubExpr, Result, Info);
604  }
605
606  return false;
607}
608
609bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
610  if (E->isBuiltinCall(Info.Ctx) ==
611        Builtin::BI__builtin___CFStringMakeConstantString ||
612      E->isBuiltinCall(Info.Ctx) ==
613        Builtin::BI__builtin___NSStringMakeConstantString)
614    return Success(E);
615  return false;
616}
617
618bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
619  bool BoolResult;
620  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
621    return false;
622
623  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
624  return Visit(EvalExpr);
625}
626
627//===----------------------------------------------------------------------===//
628// Vector Evaluation
629//===----------------------------------------------------------------------===//
630
631namespace {
632  class VectorExprEvaluator
633  : public StmtVisitor<VectorExprEvaluator, APValue> {
634    EvalInfo &Info;
635    APValue GetZeroVector(QualType VecType);
636  public:
637
638    VectorExprEvaluator(EvalInfo &info) : Info(info) {}
639
640    APValue VisitStmt(Stmt *S) {
641      return APValue();
642    }
643
644    APValue VisitParenExpr(ParenExpr *E)
645        { return Visit(E->getSubExpr()); }
646    APValue VisitUnaryExtension(const UnaryOperator *E)
647      { return Visit(E->getSubExpr()); }
648    APValue VisitUnaryPlus(const UnaryOperator *E)
649      { return Visit(E->getSubExpr()); }
650    APValue VisitUnaryReal(const UnaryOperator *E)
651      { return Visit(E->getSubExpr()); }
652    APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
653      { return GetZeroVector(E->getType()); }
654    APValue VisitCastExpr(const CastExpr* E);
655    APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
656    APValue VisitInitListExpr(const InitListExpr *E);
657    APValue VisitConditionalOperator(const ConditionalOperator *E);
658    APValue VisitChooseExpr(const ChooseExpr *E)
659      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
660    APValue VisitUnaryImag(const UnaryOperator *E);
661    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
662    //                 binary comparisons, binary and/or/xor,
663    //                 shufflevector, ExtVectorElementExpr
664    //        (Note that these require implementing conversions
665    //         between vector types.)
666  };
667} // end anonymous namespace
668
669static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
670  if (!E->getType()->isVectorType())
671    return false;
672  Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
673  return !Result.isUninit();
674}
675
676APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
677  const VectorType *VTy = E->getType()->getAs<VectorType>();
678  QualType EltTy = VTy->getElementType();
679  unsigned NElts = VTy->getNumElements();
680  unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
681
682  const Expr* SE = E->getSubExpr();
683  QualType SETy = SE->getType();
684  APValue Result = APValue();
685
686  // Check for vector->vector bitcast and scalar->vector splat.
687  if (SETy->isVectorType()) {
688    return this->Visit(const_cast<Expr*>(SE));
689  } else if (SETy->isIntegerType()) {
690    APSInt IntResult;
691    if (!EvaluateInteger(SE, IntResult, Info))
692      return APValue();
693    Result = APValue(IntResult);
694  } else if (SETy->isRealFloatingType()) {
695    APFloat F(0.0);
696    if (!EvaluateFloat(SE, F, Info))
697      return APValue();
698    Result = APValue(F);
699  } else
700    return APValue();
701
702  // For casts of a scalar to ExtVector, convert the scalar to the element type
703  // and splat it to all elements.
704  if (E->getType()->isExtVectorType()) {
705    if (EltTy->isIntegerType() && Result.isInt())
706      Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
707                                          Info.Ctx));
708    else if (EltTy->isIntegerType())
709      Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
710                                            Info.Ctx));
711    else if (EltTy->isRealFloatingType() && Result.isInt())
712      Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
713                                            Info.Ctx));
714    else if (EltTy->isRealFloatingType())
715      Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
716                                              Info.Ctx));
717    else
718      return APValue();
719
720    // Splat and create vector APValue.
721    llvm::SmallVector<APValue, 4> Elts(NElts, Result);
722    return APValue(&Elts[0], Elts.size());
723  }
724
725  // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
726  // to the vector. To construct the APValue vector initializer, bitcast the
727  // initializing value to an APInt, and shift out the bits pertaining to each
728  // element.
729  APSInt Init;
730  Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
731
732  llvm::SmallVector<APValue, 4> Elts;
733  for (unsigned i = 0; i != NElts; ++i) {
734    APSInt Tmp = Init;
735    Tmp.extOrTrunc(EltWidth);
736
737    if (EltTy->isIntegerType())
738      Elts.push_back(APValue(Tmp));
739    else if (EltTy->isRealFloatingType())
740      Elts.push_back(APValue(APFloat(Tmp)));
741    else
742      return APValue();
743
744    Init >>= EltWidth;
745  }
746  return APValue(&Elts[0], Elts.size());
747}
748
749APValue
750VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
751  return this->Visit(const_cast<Expr*>(E->getInitializer()));
752}
753
754APValue
755VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
756  const VectorType *VT = E->getType()->getAs<VectorType>();
757  unsigned NumInits = E->getNumInits();
758  unsigned NumElements = VT->getNumElements();
759
760  QualType EltTy = VT->getElementType();
761  llvm::SmallVector<APValue, 4> Elements;
762
763  // If a vector is initialized with a single element, that value
764  // becomes every element of the vector, not just the first.
765  // This is the behavior described in the IBM AltiVec documentation.
766  if (NumInits == 1) {
767    APValue InitValue;
768    if (EltTy->isIntegerType()) {
769      llvm::APSInt sInt(32);
770      if (!EvaluateInteger(E->getInit(0), sInt, Info))
771        return APValue();
772      InitValue = APValue(sInt);
773    } else {
774      llvm::APFloat f(0.0);
775      if (!EvaluateFloat(E->getInit(0), f, Info))
776        return APValue();
777      InitValue = APValue(f);
778    }
779    for (unsigned i = 0; i < NumElements; i++) {
780      Elements.push_back(InitValue);
781    }
782  } else {
783    for (unsigned i = 0; i < NumElements; i++) {
784      if (EltTy->isIntegerType()) {
785        llvm::APSInt sInt(32);
786        if (i < NumInits) {
787          if (!EvaluateInteger(E->getInit(i), sInt, Info))
788            return APValue();
789        } else {
790          sInt = Info.Ctx.MakeIntValue(0, EltTy);
791        }
792        Elements.push_back(APValue(sInt));
793      } else {
794        llvm::APFloat f(0.0);
795        if (i < NumInits) {
796          if (!EvaluateFloat(E->getInit(i), f, Info))
797            return APValue();
798        } else {
799          f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
800        }
801        Elements.push_back(APValue(f));
802      }
803    }
804  }
805  return APValue(&Elements[0], Elements.size());
806}
807
808APValue
809VectorExprEvaluator::GetZeroVector(QualType T) {
810  const VectorType *VT = T->getAs<VectorType>();
811  QualType EltTy = VT->getElementType();
812  APValue ZeroElement;
813  if (EltTy->isIntegerType())
814    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
815  else
816    ZeroElement =
817        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
818
819  llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
820  return APValue(&Elements[0], Elements.size());
821}
822
823APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
824  bool BoolResult;
825  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
826    return APValue();
827
828  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
829
830  APValue Result;
831  if (EvaluateVector(EvalExpr, Result, Info))
832    return Result;
833  return APValue();
834}
835
836APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
837  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
838    Info.EvalResult.HasSideEffects = true;
839  return GetZeroVector(E->getType());
840}
841
842//===----------------------------------------------------------------------===//
843// Integer Evaluation
844//===----------------------------------------------------------------------===//
845
846namespace {
847class IntExprEvaluator
848  : public StmtVisitor<IntExprEvaluator, bool> {
849  EvalInfo &Info;
850  APValue &Result;
851public:
852  IntExprEvaluator(EvalInfo &info, APValue &result)
853    : Info(info), Result(result) {}
854
855  bool Success(const llvm::APSInt &SI, const Expr *E) {
856    assert(E->getType()->isIntegralOrEnumerationType() &&
857           "Invalid evaluation result.");
858    assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
859           "Invalid evaluation result.");
860    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
861           "Invalid evaluation result.");
862    Result = APValue(SI);
863    return true;
864  }
865
866  bool Success(const llvm::APInt &I, const Expr *E) {
867    assert(E->getType()->isIntegralOrEnumerationType() &&
868           "Invalid evaluation result.");
869    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
870           "Invalid evaluation result.");
871    Result = APValue(APSInt(I));
872    Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
873    return true;
874  }
875
876  bool Success(uint64_t Value, const Expr *E) {
877    assert(E->getType()->isIntegralOrEnumerationType() &&
878           "Invalid evaluation result.");
879    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
880    return true;
881  }
882
883  bool Error(SourceLocation L, diag::kind D, const Expr *E) {
884    // Take the first error.
885    if (Info.EvalResult.Diag == 0) {
886      Info.EvalResult.DiagLoc = L;
887      Info.EvalResult.Diag = D;
888      Info.EvalResult.DiagExpr = E;
889    }
890    return false;
891  }
892
893  //===--------------------------------------------------------------------===//
894  //                            Visitor Methods
895  //===--------------------------------------------------------------------===//
896
897  bool VisitStmt(Stmt *) {
898    assert(0 && "This should be called on integers, stmts are not integers");
899    return false;
900  }
901
902  bool VisitExpr(Expr *E) {
903    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
904  }
905
906  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
907
908  bool VisitIntegerLiteral(const IntegerLiteral *E) {
909    return Success(E->getValue(), E);
910  }
911  bool VisitCharacterLiteral(const CharacterLiteral *E) {
912    return Success(E->getValue(), E);
913  }
914  bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
915    // Per gcc docs "this built-in function ignores top level
916    // qualifiers".  We need to use the canonical version to properly
917    // be able to strip CRV qualifiers from the type.
918    QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
919    QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
920    return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
921                                               T1.getUnqualifiedType()),
922                   E);
923  }
924
925  bool CheckReferencedDecl(const Expr *E, const Decl *D);
926  bool VisitDeclRefExpr(const DeclRefExpr *E) {
927    return CheckReferencedDecl(E, E->getDecl());
928  }
929  bool VisitMemberExpr(const MemberExpr *E) {
930    if (CheckReferencedDecl(E, E->getMemberDecl())) {
931      // Conservatively assume a MemberExpr will have side-effects
932      Info.EvalResult.HasSideEffects = true;
933      return true;
934    }
935    return false;
936  }
937
938  bool VisitCallExpr(CallExpr *E);
939  bool VisitBinaryOperator(const BinaryOperator *E);
940  bool VisitOffsetOfExpr(const OffsetOfExpr *E);
941  bool VisitUnaryOperator(const UnaryOperator *E);
942  bool VisitConditionalOperator(const ConditionalOperator *E);
943
944  bool VisitCastExpr(CastExpr* E);
945  bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
946
947  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
948    return Success(E->getValue(), E);
949  }
950
951  bool VisitGNUNullExpr(const GNUNullExpr *E) {
952    return Success(0, E);
953  }
954
955  bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
956    return Success(0, E);
957  }
958
959  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
960    return Success(0, E);
961  }
962
963  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
964    return Success(E->getValue(), E);
965  }
966
967  bool VisitChooseExpr(const ChooseExpr *E) {
968    return Visit(E->getChosenSubExpr(Info.Ctx));
969  }
970
971  bool VisitUnaryReal(const UnaryOperator *E);
972  bool VisitUnaryImag(const UnaryOperator *E);
973
974  bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
975
976private:
977  CharUnits GetAlignOfExpr(const Expr *E);
978  CharUnits GetAlignOfType(QualType T);
979  static QualType GetObjectType(const Expr *E);
980  bool TryEvaluateBuiltinObjectSize(CallExpr *E);
981  // FIXME: Missing: array subscript of vector, member of vector
982};
983} // end anonymous namespace
984
985static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
986  assert(E->getType()->isIntegralOrEnumerationType());
987  return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
988}
989
990static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
991  assert(E->getType()->isIntegralOrEnumerationType());
992
993  APValue Val;
994  if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
995    return false;
996  Result = Val.getInt();
997  return true;
998}
999
1000bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
1001  // Enums are integer constant exprs.
1002  if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1003    return Success(ECD->getInitVal(), E);
1004
1005  // In C++, const, non-volatile integers initialized with ICEs are ICEs.
1006  // In C, they can also be folded, although they are not ICEs.
1007  if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1008                                                        == Qualifiers::Const) {
1009
1010    if (isa<ParmVarDecl>(D))
1011      return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1012
1013    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1014      if (const Expr *Init = VD->getAnyInitializer()) {
1015        if (APValue *V = VD->getEvaluatedValue()) {
1016          if (V->isInt())
1017            return Success(V->getInt(), E);
1018          return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1019        }
1020
1021        if (VD->isEvaluatingValue())
1022          return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1023
1024        VD->setEvaluatingValue();
1025
1026        Expr::EvalResult EResult;
1027        if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1028            EResult.Val.isInt()) {
1029          // Cache the evaluated value in the variable declaration.
1030          Result = EResult.Val;
1031          VD->setEvaluatedValue(Result);
1032          return true;
1033        }
1034
1035        VD->setEvaluatedValue(APValue());
1036      }
1037    }
1038  }
1039
1040  // Otherwise, random variable references are not constants.
1041  return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1042}
1043
1044/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1045/// as GCC.
1046static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1047  // The following enum mimics the values returned by GCC.
1048  // FIXME: Does GCC differ between lvalue and rvalue references here?
1049  enum gcc_type_class {
1050    no_type_class = -1,
1051    void_type_class, integer_type_class, char_type_class,
1052    enumeral_type_class, boolean_type_class,
1053    pointer_type_class, reference_type_class, offset_type_class,
1054    real_type_class, complex_type_class,
1055    function_type_class, method_type_class,
1056    record_type_class, union_type_class,
1057    array_type_class, string_type_class,
1058    lang_type_class
1059  };
1060
1061  // If no argument was supplied, default to "no_type_class". This isn't
1062  // ideal, however it is what gcc does.
1063  if (E->getNumArgs() == 0)
1064    return no_type_class;
1065
1066  QualType ArgTy = E->getArg(0)->getType();
1067  if (ArgTy->isVoidType())
1068    return void_type_class;
1069  else if (ArgTy->isEnumeralType())
1070    return enumeral_type_class;
1071  else if (ArgTy->isBooleanType())
1072    return boolean_type_class;
1073  else if (ArgTy->isCharType())
1074    return string_type_class; // gcc doesn't appear to use char_type_class
1075  else if (ArgTy->isIntegerType())
1076    return integer_type_class;
1077  else if (ArgTy->isPointerType())
1078    return pointer_type_class;
1079  else if (ArgTy->isReferenceType())
1080    return reference_type_class;
1081  else if (ArgTy->isRealType())
1082    return real_type_class;
1083  else if (ArgTy->isComplexType())
1084    return complex_type_class;
1085  else if (ArgTy->isFunctionType())
1086    return function_type_class;
1087  else if (ArgTy->isStructureOrClassType())
1088    return record_type_class;
1089  else if (ArgTy->isUnionType())
1090    return union_type_class;
1091  else if (ArgTy->isArrayType())
1092    return array_type_class;
1093  else if (ArgTy->isUnionType())
1094    return union_type_class;
1095  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
1096    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1097  return -1;
1098}
1099
1100/// Retrieves the "underlying object type" of the given expression,
1101/// as used by __builtin_object_size.
1102QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1103  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1104    if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1105      return VD->getType();
1106  } else if (isa<CompoundLiteralExpr>(E)) {
1107    return E->getType();
1108  }
1109
1110  return QualType();
1111}
1112
1113bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1114  // TODO: Perhaps we should let LLVM lower this?
1115  LValue Base;
1116  if (!EvaluatePointer(E->getArg(0), Base, Info))
1117    return false;
1118
1119  // If we can prove the base is null, lower to zero now.
1120  const Expr *LVBase = Base.getLValueBase();
1121  if (!LVBase) return Success(0, E);
1122
1123  QualType T = GetObjectType(LVBase);
1124  if (T.isNull() ||
1125      T->isIncompleteType() ||
1126      T->isFunctionType() ||
1127      T->isVariablyModifiedType() ||
1128      T->isDependentType())
1129    return false;
1130
1131  CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1132  CharUnits Offset = Base.getLValueOffset();
1133
1134  if (!Offset.isNegative() && Offset <= Size)
1135    Size -= Offset;
1136  else
1137    Size = CharUnits::Zero();
1138  return Success(Size.getQuantity(), E);
1139}
1140
1141bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
1142  switch (E->isBuiltinCall(Info.Ctx)) {
1143  default:
1144    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1145
1146  case Builtin::BI__builtin_object_size: {
1147    if (TryEvaluateBuiltinObjectSize(E))
1148      return true;
1149
1150    // If evaluating the argument has side-effects we can't determine
1151    // the size of the object and lower it to unknown now.
1152    if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
1153      if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
1154        return Success(-1ULL, E);
1155      return Success(0, E);
1156    }
1157
1158    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1159  }
1160
1161  case Builtin::BI__builtin_classify_type:
1162    return Success(EvaluateBuiltinClassifyType(E), E);
1163
1164  case Builtin::BI__builtin_constant_p:
1165    // __builtin_constant_p always has one operand: it returns true if that
1166    // operand can be folded, false otherwise.
1167    return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
1168
1169  case Builtin::BI__builtin_eh_return_data_regno: {
1170    int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1171    Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1172    return Success(Operand, E);
1173  }
1174
1175  case Builtin::BI__builtin_expect:
1176    return Visit(E->getArg(0));
1177
1178  case Builtin::BIstrlen:
1179  case Builtin::BI__builtin_strlen:
1180    // As an extension, we support strlen() and __builtin_strlen() as constant
1181    // expressions when the argument is a string literal.
1182    if (StringLiteral *S
1183               = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1184      // The string literal may have embedded null characters. Find the first
1185      // one and truncate there.
1186      llvm::StringRef Str = S->getString();
1187      llvm::StringRef::size_type Pos = Str.find(0);
1188      if (Pos != llvm::StringRef::npos)
1189        Str = Str.substr(0, Pos);
1190
1191      return Success(Str.size(), E);
1192    }
1193
1194    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1195  }
1196}
1197
1198bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1199  if (E->getOpcode() == BO_Comma) {
1200    if (!Visit(E->getRHS()))
1201      return false;
1202
1203    // If we can't evaluate the LHS, it might have side effects;
1204    // conservatively mark it.
1205    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1206      Info.EvalResult.HasSideEffects = true;
1207
1208    return true;
1209  }
1210
1211  if (E->isLogicalOp()) {
1212    // These need to be handled specially because the operands aren't
1213    // necessarily integral
1214    bool lhsResult, rhsResult;
1215
1216    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
1217      // We were able to evaluate the LHS, see if we can get away with not
1218      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1219      if (lhsResult == (E->getOpcode() == BO_LOr))
1220        return Success(lhsResult, E);
1221
1222      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1223        if (E->getOpcode() == BO_LOr)
1224          return Success(lhsResult || rhsResult, E);
1225        else
1226          return Success(lhsResult && rhsResult, E);
1227      }
1228    } else {
1229      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1230        // We can't evaluate the LHS; however, sometimes the result
1231        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1232        if (rhsResult == (E->getOpcode() == BO_LOr) ||
1233            !rhsResult == (E->getOpcode() == BO_LAnd)) {
1234          // Since we weren't able to evaluate the left hand side, it
1235          // must have had side effects.
1236          Info.EvalResult.HasSideEffects = true;
1237
1238          return Success(rhsResult, E);
1239        }
1240      }
1241    }
1242
1243    return false;
1244  }
1245
1246  QualType LHSTy = E->getLHS()->getType();
1247  QualType RHSTy = E->getRHS()->getType();
1248
1249  if (LHSTy->isAnyComplexType()) {
1250    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1251    ComplexValue LHS, RHS;
1252
1253    if (!EvaluateComplex(E->getLHS(), LHS, Info))
1254      return false;
1255
1256    if (!EvaluateComplex(E->getRHS(), RHS, Info))
1257      return false;
1258
1259    if (LHS.isComplexFloat()) {
1260      APFloat::cmpResult CR_r =
1261        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
1262      APFloat::cmpResult CR_i =
1263        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1264
1265      if (E->getOpcode() == BO_EQ)
1266        return Success((CR_r == APFloat::cmpEqual &&
1267                        CR_i == APFloat::cmpEqual), E);
1268      else {
1269        assert(E->getOpcode() == BO_NE &&
1270               "Invalid complex comparison.");
1271        return Success(((CR_r == APFloat::cmpGreaterThan ||
1272                         CR_r == APFloat::cmpLessThan ||
1273                         CR_r == APFloat::cmpUnordered) ||
1274                        (CR_i == APFloat::cmpGreaterThan ||
1275                         CR_i == APFloat::cmpLessThan ||
1276                         CR_i == APFloat::cmpUnordered)), E);
1277      }
1278    } else {
1279      if (E->getOpcode() == BO_EQ)
1280        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1281                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1282      else {
1283        assert(E->getOpcode() == BO_NE &&
1284               "Invalid compex comparison.");
1285        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1286                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1287      }
1288    }
1289  }
1290
1291  if (LHSTy->isRealFloatingType() &&
1292      RHSTy->isRealFloatingType()) {
1293    APFloat RHS(0.0), LHS(0.0);
1294
1295    if (!EvaluateFloat(E->getRHS(), RHS, Info))
1296      return false;
1297
1298    if (!EvaluateFloat(E->getLHS(), LHS, Info))
1299      return false;
1300
1301    APFloat::cmpResult CR = LHS.compare(RHS);
1302
1303    switch (E->getOpcode()) {
1304    default:
1305      assert(0 && "Invalid binary operator!");
1306    case BO_LT:
1307      return Success(CR == APFloat::cmpLessThan, E);
1308    case BO_GT:
1309      return Success(CR == APFloat::cmpGreaterThan, E);
1310    case BO_LE:
1311      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
1312    case BO_GE:
1313      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
1314                     E);
1315    case BO_EQ:
1316      return Success(CR == APFloat::cmpEqual, E);
1317    case BO_NE:
1318      return Success(CR == APFloat::cmpGreaterThan
1319                     || CR == APFloat::cmpLessThan
1320                     || CR == APFloat::cmpUnordered, E);
1321    }
1322  }
1323
1324  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1325    if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
1326      LValue LHSValue;
1327      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1328        return false;
1329
1330      LValue RHSValue;
1331      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1332        return false;
1333
1334      // Reject any bases from the normal codepath; we special-case comparisons
1335      // to null.
1336      if (LHSValue.getLValueBase()) {
1337        if (!E->isEqualityOp())
1338          return false;
1339        if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
1340          return false;
1341        bool bres;
1342        if (!EvalPointerValueAsBool(LHSValue, bres))
1343          return false;
1344        return Success(bres ^ (E->getOpcode() == BO_EQ), E);
1345      } else if (RHSValue.getLValueBase()) {
1346        if (!E->isEqualityOp())
1347          return false;
1348        if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
1349          return false;
1350        bool bres;
1351        if (!EvalPointerValueAsBool(RHSValue, bres))
1352          return false;
1353        return Success(bres ^ (E->getOpcode() == BO_EQ), E);
1354      }
1355
1356      if (E->getOpcode() == BO_Sub) {
1357        QualType Type = E->getLHS()->getType();
1358        QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
1359
1360        CharUnits ElementSize = CharUnits::One();
1361        if (!ElementType->isVoidType() && !ElementType->isFunctionType())
1362          ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
1363
1364        CharUnits Diff = LHSValue.getLValueOffset() -
1365                             RHSValue.getLValueOffset();
1366        return Success(Diff / ElementSize, E);
1367      }
1368      bool Result;
1369      if (E->getOpcode() == BO_EQ) {
1370        Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
1371      } else {
1372        Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1373      }
1374      return Success(Result, E);
1375    }
1376  }
1377  if (!LHSTy->isIntegralOrEnumerationType() ||
1378      !RHSTy->isIntegralOrEnumerationType()) {
1379    // We can't continue from here for non-integral types, and they
1380    // could potentially confuse the following operations.
1381    return false;
1382  }
1383
1384  // The LHS of a constant expr is always evaluated and needed.
1385  if (!Visit(E->getLHS()))
1386    return false; // error in subexpression.
1387
1388  APValue RHSVal;
1389  if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1390    return false;
1391
1392  // Handle cases like (unsigned long)&a + 4.
1393  if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1394    CharUnits Offset = Result.getLValueOffset();
1395    CharUnits AdditionalOffset = CharUnits::fromQuantity(
1396                                     RHSVal.getInt().getZExtValue());
1397    if (E->getOpcode() == BO_Add)
1398      Offset += AdditionalOffset;
1399    else
1400      Offset -= AdditionalOffset;
1401    Result = APValue(Result.getLValueBase(), Offset);
1402    return true;
1403  }
1404
1405  // Handle cases like 4 + (unsigned long)&a
1406  if (E->getOpcode() == BO_Add &&
1407        RHSVal.isLValue() && Result.isInt()) {
1408    CharUnits Offset = RHSVal.getLValueOffset();
1409    Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1410    Result = APValue(RHSVal.getLValueBase(), Offset);
1411    return true;
1412  }
1413
1414  // All the following cases expect both operands to be an integer
1415  if (!Result.isInt() || !RHSVal.isInt())
1416    return false;
1417
1418  APSInt& RHS = RHSVal.getInt();
1419
1420  switch (E->getOpcode()) {
1421  default:
1422    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1423  case BO_Mul: return Success(Result.getInt() * RHS, E);
1424  case BO_Add: return Success(Result.getInt() + RHS, E);
1425  case BO_Sub: return Success(Result.getInt() - RHS, E);
1426  case BO_And: return Success(Result.getInt() & RHS, E);
1427  case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1428  case BO_Or:  return Success(Result.getInt() | RHS, E);
1429  case BO_Div:
1430    if (RHS == 0)
1431      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1432    return Success(Result.getInt() / RHS, E);
1433  case BO_Rem:
1434    if (RHS == 0)
1435      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1436    return Success(Result.getInt() % RHS, E);
1437  case BO_Shl: {
1438    // During constant-folding, a negative shift is an opposite shift.
1439    if (RHS.isSigned() && RHS.isNegative()) {
1440      RHS = -RHS;
1441      goto shift_right;
1442    }
1443
1444  shift_left:
1445    unsigned SA
1446      = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1447    return Success(Result.getInt() << SA, E);
1448  }
1449  case BO_Shr: {
1450    // During constant-folding, a negative shift is an opposite shift.
1451    if (RHS.isSigned() && RHS.isNegative()) {
1452      RHS = -RHS;
1453      goto shift_left;
1454    }
1455
1456  shift_right:
1457    unsigned SA =
1458      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1459    return Success(Result.getInt() >> SA, E);
1460  }
1461
1462  case BO_LT: return Success(Result.getInt() < RHS, E);
1463  case BO_GT: return Success(Result.getInt() > RHS, E);
1464  case BO_LE: return Success(Result.getInt() <= RHS, E);
1465  case BO_GE: return Success(Result.getInt() >= RHS, E);
1466  case BO_EQ: return Success(Result.getInt() == RHS, E);
1467  case BO_NE: return Success(Result.getInt() != RHS, E);
1468  }
1469}
1470
1471bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1472  bool Cond;
1473  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1474    return false;
1475
1476  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1477}
1478
1479CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
1480  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1481  //   the result is the size of the referenced type."
1482  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1483  //   result shall be the alignment of the referenced type."
1484  if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1485    T = Ref->getPointeeType();
1486
1487  // Get information about the alignment.
1488  unsigned CharSize = Info.Ctx.Target.getCharWidth();
1489
1490  // __alignof is defined to return the preferred alignment.
1491  return CharUnits::fromQuantity(
1492      Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
1493}
1494
1495CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1496  E = E->IgnoreParens();
1497
1498  // alignof decl is always accepted, even if it doesn't make sense: we default
1499  // to 1 in those cases.
1500  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1501    return Info.Ctx.getDeclAlign(DRE->getDecl(),
1502                                 /*RefAsPointee*/true);
1503
1504  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1505    return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1506                                 /*RefAsPointee*/true);
1507
1508  return GetAlignOfType(E->getType());
1509}
1510
1511
1512/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1513/// expression's type.
1514bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1515  // Handle alignof separately.
1516  if (!E->isSizeOf()) {
1517    if (E->isArgumentType())
1518      return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
1519    else
1520      return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
1521  }
1522
1523  QualType SrcTy = E->getTypeOfArgument();
1524  // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1525  //   the result is the size of the referenced type."
1526  // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1527  //   result shall be the alignment of the referenced type."
1528  if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1529    SrcTy = Ref->getPointeeType();
1530
1531  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1532  // extension.
1533  if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1534    return Success(1, E);
1535
1536  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1537  if (!SrcTy->isConstantSizeType())
1538    return false;
1539
1540  // Get information about the size.
1541  return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
1542}
1543
1544bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1545  CharUnits Result;
1546  unsigned n = E->getNumComponents();
1547  OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1548  if (n == 0)
1549    return false;
1550  QualType CurrentType = E->getTypeSourceInfo()->getType();
1551  for (unsigned i = 0; i != n; ++i) {
1552    OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1553    switch (ON.getKind()) {
1554    case OffsetOfExpr::OffsetOfNode::Array: {
1555      Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1556      APSInt IdxResult;
1557      if (!EvaluateInteger(Idx, IdxResult, Info))
1558        return false;
1559      const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1560      if (!AT)
1561        return false;
1562      CurrentType = AT->getElementType();
1563      CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1564      Result += IdxResult.getSExtValue() * ElementSize;
1565        break;
1566    }
1567
1568    case OffsetOfExpr::OffsetOfNode::Field: {
1569      FieldDecl *MemberDecl = ON.getField();
1570      const RecordType *RT = CurrentType->getAs<RecordType>();
1571      if (!RT)
1572        return false;
1573      RecordDecl *RD = RT->getDecl();
1574      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1575      unsigned i = 0;
1576      // FIXME: It would be nice if we didn't have to loop here!
1577      for (RecordDecl::field_iterator Field = RD->field_begin(),
1578                                      FieldEnd = RD->field_end();
1579           Field != FieldEnd; (void)++Field, ++i) {
1580        if (*Field == MemberDecl)
1581          break;
1582      }
1583      assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1584      Result += CharUnits::fromQuantity(
1585                           RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
1586      CurrentType = MemberDecl->getType().getNonReferenceType();
1587      break;
1588    }
1589
1590    case OffsetOfExpr::OffsetOfNode::Identifier:
1591      llvm_unreachable("dependent __builtin_offsetof");
1592      return false;
1593
1594    case OffsetOfExpr::OffsetOfNode::Base: {
1595      CXXBaseSpecifier *BaseSpec = ON.getBase();
1596      if (BaseSpec->isVirtual())
1597        return false;
1598
1599      // Find the layout of the class whose base we are looking into.
1600      const RecordType *RT = CurrentType->getAs<RecordType>();
1601      if (!RT)
1602        return false;
1603      RecordDecl *RD = RT->getDecl();
1604      const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1605
1606      // Find the base class itself.
1607      CurrentType = BaseSpec->getType();
1608      const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1609      if (!BaseRT)
1610        return false;
1611
1612      // Add the offset to the base.
1613      Result += CharUnits::fromQuantity(
1614             RL.getBaseClassOffsetInBits(cast<CXXRecordDecl>(BaseRT->getDecl()))
1615                                        / Info.Ctx.getCharWidth());
1616      break;
1617    }
1618    }
1619  }
1620  return Success(Result.getQuantity(), E);
1621}
1622
1623bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1624  if (E->getOpcode() == UO_LNot) {
1625    // LNot's operand isn't necessarily an integer, so we handle it specially.
1626    bool bres;
1627    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1628      return false;
1629    return Success(!bres, E);
1630  }
1631
1632  // Only handle integral operations...
1633  if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
1634    return false;
1635
1636  // Get the operand value into 'Result'.
1637  if (!Visit(E->getSubExpr()))
1638    return false;
1639
1640  switch (E->getOpcode()) {
1641  default:
1642    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1643    // See C99 6.6p3.
1644    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1645  case UO_Extension:
1646    // FIXME: Should extension allow i-c-e extension expressions in its scope?
1647    // If so, we could clear the diagnostic ID.
1648    return true;
1649  case UO_Plus:
1650    // The result is always just the subexpr.
1651    return true;
1652  case UO_Minus:
1653    if (!Result.isInt()) return false;
1654    return Success(-Result.getInt(), E);
1655  case UO_Not:
1656    if (!Result.isInt()) return false;
1657    return Success(~Result.getInt(), E);
1658  }
1659}
1660
1661/// HandleCast - This is used to evaluate implicit or explicit casts where the
1662/// result type is integer.
1663bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1664  Expr *SubExpr = E->getSubExpr();
1665  QualType DestType = E->getType();
1666  QualType SrcType = SubExpr->getType();
1667
1668  if (DestType->isBooleanType()) {
1669    bool BoolResult;
1670    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1671      return false;
1672    return Success(BoolResult, E);
1673  }
1674
1675  // Handle simple integer->integer casts.
1676  if (SrcType->isIntegralOrEnumerationType()) {
1677    if (!Visit(SubExpr))
1678      return false;
1679
1680    if (!Result.isInt()) {
1681      // Only allow casts of lvalues if they are lossless.
1682      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1683    }
1684
1685    return Success(HandleIntToIntCast(DestType, SrcType,
1686                                      Result.getInt(), Info.Ctx), E);
1687  }
1688
1689  // FIXME: Clean this up!
1690  if (SrcType->isPointerType()) {
1691    LValue LV;
1692    if (!EvaluatePointer(SubExpr, LV, Info))
1693      return false;
1694
1695    if (LV.getLValueBase()) {
1696      // Only allow based lvalue casts if they are lossless.
1697      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1698        return false;
1699
1700      LV.moveInto(Result);
1701      return true;
1702    }
1703
1704    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1705                                         SrcType);
1706    return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1707  }
1708
1709  if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1710    // This handles double-conversion cases, where there's both
1711    // an l-value promotion and an implicit conversion to int.
1712    LValue LV;
1713    if (!EvaluateLValue(SubExpr, LV, Info))
1714      return false;
1715
1716    if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1717      return false;
1718
1719    LV.moveInto(Result);
1720    return true;
1721  }
1722
1723  if (SrcType->isAnyComplexType()) {
1724    ComplexValue C;
1725    if (!EvaluateComplex(SubExpr, C, Info))
1726      return false;
1727    if (C.isComplexFloat())
1728      return Success(HandleFloatToIntCast(DestType, SrcType,
1729                                          C.getComplexFloatReal(), Info.Ctx),
1730                     E);
1731    else
1732      return Success(HandleIntToIntCast(DestType, SrcType,
1733                                        C.getComplexIntReal(), Info.Ctx), E);
1734  }
1735  // FIXME: Handle vectors
1736
1737  if (!SrcType->isRealFloatingType())
1738    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1739
1740  APFloat F(0.0);
1741  if (!EvaluateFloat(SubExpr, F, Info))
1742    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1743
1744  return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1745}
1746
1747bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1748  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1749    ComplexValue LV;
1750    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1751      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1752    return Success(LV.getComplexIntReal(), E);
1753  }
1754
1755  return Visit(E->getSubExpr());
1756}
1757
1758bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1759  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1760    ComplexValue LV;
1761    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1762      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1763    return Success(LV.getComplexIntImag(), E);
1764  }
1765
1766  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1767    Info.EvalResult.HasSideEffects = true;
1768  return Success(0, E);
1769}
1770
1771bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1772  return Success(E->getValue(), E);
1773}
1774
1775//===----------------------------------------------------------------------===//
1776// Float Evaluation
1777//===----------------------------------------------------------------------===//
1778
1779namespace {
1780class FloatExprEvaluator
1781  : public StmtVisitor<FloatExprEvaluator, bool> {
1782  EvalInfo &Info;
1783  APFloat &Result;
1784public:
1785  FloatExprEvaluator(EvalInfo &info, APFloat &result)
1786    : Info(info), Result(result) {}
1787
1788  bool VisitStmt(Stmt *S) {
1789    return false;
1790  }
1791
1792  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1793  bool VisitCallExpr(const CallExpr *E);
1794
1795  bool VisitUnaryOperator(const UnaryOperator *E);
1796  bool VisitBinaryOperator(const BinaryOperator *E);
1797  bool VisitFloatingLiteral(const FloatingLiteral *E);
1798  bool VisitCastExpr(CastExpr *E);
1799  bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
1800  bool VisitConditionalOperator(ConditionalOperator *E);
1801
1802  bool VisitChooseExpr(const ChooseExpr *E)
1803    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1804  bool VisitUnaryExtension(const UnaryOperator *E)
1805    { return Visit(E->getSubExpr()); }
1806  bool VisitUnaryReal(const UnaryOperator *E);
1807  bool VisitUnaryImag(const UnaryOperator *E);
1808
1809  bool VisitDeclRefExpr(const DeclRefExpr *E);
1810
1811  // FIXME: Missing: array subscript of vector, member of vector,
1812  //                 ImplicitValueInitExpr
1813};
1814} // end anonymous namespace
1815
1816static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1817  assert(E->getType()->isRealFloatingType());
1818  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1819}
1820
1821static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1822                                  QualType ResultTy,
1823                                  const Expr *Arg,
1824                                  bool SNaN,
1825                                  llvm::APFloat &Result) {
1826  const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1827  if (!S) return false;
1828
1829  const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1830
1831  llvm::APInt fill;
1832
1833  // Treat empty strings as if they were zero.
1834  if (S->getString().empty())
1835    fill = llvm::APInt(32, 0);
1836  else if (S->getString().getAsInteger(0, fill))
1837    return false;
1838
1839  if (SNaN)
1840    Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1841  else
1842    Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1843  return true;
1844}
1845
1846bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1847  switch (E->isBuiltinCall(Info.Ctx)) {
1848  default: return false;
1849  case Builtin::BI__builtin_huge_val:
1850  case Builtin::BI__builtin_huge_valf:
1851  case Builtin::BI__builtin_huge_vall:
1852  case Builtin::BI__builtin_inf:
1853  case Builtin::BI__builtin_inff:
1854  case Builtin::BI__builtin_infl: {
1855    const llvm::fltSemantics &Sem =
1856      Info.Ctx.getFloatTypeSemantics(E->getType());
1857    Result = llvm::APFloat::getInf(Sem);
1858    return true;
1859  }
1860
1861  case Builtin::BI__builtin_nans:
1862  case Builtin::BI__builtin_nansf:
1863  case Builtin::BI__builtin_nansl:
1864    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1865                                 true, Result);
1866
1867  case Builtin::BI__builtin_nan:
1868  case Builtin::BI__builtin_nanf:
1869  case Builtin::BI__builtin_nanl:
1870    // If this is __builtin_nan() turn this into a nan, otherwise we
1871    // can't constant fold it.
1872    return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1873                                 false, Result);
1874
1875  case Builtin::BI__builtin_fabs:
1876  case Builtin::BI__builtin_fabsf:
1877  case Builtin::BI__builtin_fabsl:
1878    if (!EvaluateFloat(E->getArg(0), Result, Info))
1879      return false;
1880
1881    if (Result.isNegative())
1882      Result.changeSign();
1883    return true;
1884
1885  case Builtin::BI__builtin_copysign:
1886  case Builtin::BI__builtin_copysignf:
1887  case Builtin::BI__builtin_copysignl: {
1888    APFloat RHS(0.);
1889    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1890        !EvaluateFloat(E->getArg(1), RHS, Info))
1891      return false;
1892    Result.copySign(RHS);
1893    return true;
1894  }
1895  }
1896}
1897
1898bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1899  const Decl *D = E->getDecl();
1900  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
1901  const VarDecl *VD = cast<VarDecl>(D);
1902
1903  // Require the qualifiers to be const and not volatile.
1904  CanQualType T = Info.Ctx.getCanonicalType(E->getType());
1905  if (!T.isConstQualified() || T.isVolatileQualified())
1906    return false;
1907
1908  const Expr *Init = VD->getAnyInitializer();
1909  if (!Init) return false;
1910
1911  if (APValue *V = VD->getEvaluatedValue()) {
1912    if (V->isFloat()) {
1913      Result = V->getFloat();
1914      return true;
1915    }
1916    return false;
1917  }
1918
1919  if (VD->isEvaluatingValue())
1920    return false;
1921
1922  VD->setEvaluatingValue();
1923
1924  Expr::EvalResult InitResult;
1925  if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
1926      InitResult.Val.isFloat()) {
1927    // Cache the evaluated value in the variable declaration.
1928    Result = InitResult.Val.getFloat();
1929    VD->setEvaluatedValue(InitResult.Val);
1930    return true;
1931  }
1932
1933  VD->setEvaluatedValue(APValue());
1934  return false;
1935}
1936
1937bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1938  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1939    ComplexValue CV;
1940    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1941      return false;
1942    Result = CV.FloatReal;
1943    return true;
1944  }
1945
1946  return Visit(E->getSubExpr());
1947}
1948
1949bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1950  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1951    ComplexValue CV;
1952    if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1953      return false;
1954    Result = CV.FloatImag;
1955    return true;
1956  }
1957
1958  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1959    Info.EvalResult.HasSideEffects = true;
1960  const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
1961  Result = llvm::APFloat::getZero(Sem);
1962  return true;
1963}
1964
1965bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1966  if (E->getOpcode() == UO_Deref)
1967    return false;
1968
1969  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1970    return false;
1971
1972  switch (E->getOpcode()) {
1973  default: return false;
1974  case UO_Plus:
1975    return true;
1976  case UO_Minus:
1977    Result.changeSign();
1978    return true;
1979  }
1980}
1981
1982bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1983  if (E->getOpcode() == BO_Comma) {
1984    if (!EvaluateFloat(E->getRHS(), Result, Info))
1985      return false;
1986
1987    // If we can't evaluate the LHS, it might have side effects;
1988    // conservatively mark it.
1989    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1990      Info.EvalResult.HasSideEffects = true;
1991
1992    return true;
1993  }
1994
1995  // We can't evaluate pointer-to-member operations.
1996  if (E->isPtrMemOp())
1997    return false;
1998
1999  // FIXME: Diagnostics?  I really don't understand how the warnings
2000  // and errors are supposed to work.
2001  APFloat RHS(0.0);
2002  if (!EvaluateFloat(E->getLHS(), Result, Info))
2003    return false;
2004  if (!EvaluateFloat(E->getRHS(), RHS, Info))
2005    return false;
2006
2007  switch (E->getOpcode()) {
2008  default: return false;
2009  case BO_Mul:
2010    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2011    return true;
2012  case BO_Add:
2013    Result.add(RHS, APFloat::rmNearestTiesToEven);
2014    return true;
2015  case BO_Sub:
2016    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2017    return true;
2018  case BO_Div:
2019    Result.divide(RHS, APFloat::rmNearestTiesToEven);
2020    return true;
2021  }
2022}
2023
2024bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2025  Result = E->getValue();
2026  return true;
2027}
2028
2029bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2030  Expr* SubExpr = E->getSubExpr();
2031
2032  if (SubExpr->getType()->isIntegralOrEnumerationType()) {
2033    APSInt IntResult;
2034    if (!EvaluateInteger(SubExpr, IntResult, Info))
2035      return false;
2036    Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
2037                                  IntResult, Info.Ctx);
2038    return true;
2039  }
2040  if (SubExpr->getType()->isRealFloatingType()) {
2041    if (!Visit(SubExpr))
2042      return false;
2043    Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2044                                    Result, Info.Ctx);
2045    return true;
2046  }
2047
2048  if (E->getCastKind() == CK_FloatingComplexToReal) {
2049    ComplexValue V;
2050    if (!EvaluateComplex(SubExpr, V, Info))
2051      return false;
2052    Result = V.getComplexFloatReal();
2053    return true;
2054  }
2055
2056  return false;
2057}
2058
2059bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
2060  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2061  return true;
2062}
2063
2064bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2065  bool Cond;
2066  if (!HandleConversionToBool(E->getCond(), Cond, Info))
2067    return false;
2068
2069  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2070}
2071
2072//===----------------------------------------------------------------------===//
2073// Complex Evaluation (for float and integer)
2074//===----------------------------------------------------------------------===//
2075
2076namespace {
2077class ComplexExprEvaluator
2078  : public StmtVisitor<ComplexExprEvaluator, bool> {
2079  EvalInfo &Info;
2080  ComplexValue &Result;
2081
2082public:
2083  ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2084    : Info(info), Result(Result) {}
2085
2086  //===--------------------------------------------------------------------===//
2087  //                            Visitor Methods
2088  //===--------------------------------------------------------------------===//
2089
2090  bool VisitStmt(Stmt *S) {
2091    return false;
2092  }
2093
2094  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
2095
2096  bool VisitImaginaryLiteral(ImaginaryLiteral *E);
2097
2098  bool VisitCastExpr(CastExpr *E);
2099
2100  bool VisitBinaryOperator(const BinaryOperator *E);
2101  bool VisitChooseExpr(const ChooseExpr *E)
2102    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
2103  bool VisitUnaryExtension(const UnaryOperator *E)
2104    { return Visit(E->getSubExpr()); }
2105  // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
2106  //                conditional ?:, comma
2107};
2108} // end anonymous namespace
2109
2110static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2111                            EvalInfo &Info) {
2112  assert(E->getType()->isAnyComplexType());
2113  return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
2114}
2115
2116bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2117  Expr* SubExpr = E->getSubExpr();
2118
2119  if (SubExpr->getType()->isRealFloatingType()) {
2120    Result.makeComplexFloat();
2121    APFloat &Imag = Result.FloatImag;
2122    if (!EvaluateFloat(SubExpr, Imag, Info))
2123      return false;
2124
2125    Result.FloatReal = APFloat(Imag.getSemantics());
2126    return true;
2127  } else {
2128    assert(SubExpr->getType()->isIntegerType() &&
2129           "Unexpected imaginary literal.");
2130
2131    Result.makeComplexInt();
2132    APSInt &Imag = Result.IntImag;
2133    if (!EvaluateInteger(SubExpr, Imag, Info))
2134      return false;
2135
2136    Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2137    return true;
2138  }
2139}
2140
2141bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
2142  Expr* SubExpr = E->getSubExpr();
2143  QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
2144  QualType SubType = SubExpr->getType();
2145
2146  // TODO: just trust CastKind
2147
2148  if (SubType->isRealFloatingType()) {
2149    APFloat &Real = Result.FloatReal;
2150    if (!EvaluateFloat(SubExpr, Real, Info))
2151      return false;
2152
2153    if (EltType->isRealFloatingType()) {
2154      Result.makeComplexFloat();
2155      Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
2156      Result.FloatImag = APFloat(Real.getSemantics());
2157      return true;
2158    } else {
2159      Result.makeComplexInt();
2160      Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
2161      Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
2162                              !Result.IntReal.isSigned());
2163      return true;
2164    }
2165  } else if (SubType->isIntegerType()) {
2166    APSInt &Real = Result.IntReal;
2167    if (!EvaluateInteger(SubExpr, Real, Info))
2168      return false;
2169
2170    if (EltType->isRealFloatingType()) {
2171      Result.makeComplexFloat();
2172      Result.FloatReal
2173        = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
2174      Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
2175      return true;
2176    } else {
2177      Result.makeComplexInt();
2178      Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
2179      Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2180      return true;
2181    }
2182  } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
2183    if (!Visit(SubExpr))
2184      return false;
2185
2186    QualType SrcType = CT->getElementType();
2187
2188    if (Result.isComplexFloat()) {
2189      if (EltType->isRealFloatingType()) {
2190        Result.makeComplexFloat();
2191        Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
2192                                                  Result.FloatReal,
2193                                                  Info.Ctx);
2194        Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
2195                                                  Result.FloatImag,
2196                                                  Info.Ctx);
2197        return true;
2198      } else {
2199        Result.makeComplexInt();
2200        Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
2201                                              Result.FloatReal,
2202                                              Info.Ctx);
2203        Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
2204                                              Result.FloatImag,
2205                                              Info.Ctx);
2206        return true;
2207      }
2208    } else {
2209      assert(Result.isComplexInt() && "Invalid evaluate result.");
2210      if (EltType->isRealFloatingType()) {
2211        Result.makeComplexFloat();
2212        Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
2213                                                Result.IntReal,
2214                                                Info.Ctx);
2215        Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2216                                                Result.IntImag,
2217                                                Info.Ctx);
2218        return true;
2219      } else {
2220        Result.makeComplexInt();
2221        Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2222                                            Result.IntReal,
2223                                            Info.Ctx);
2224        Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2225                                            Result.IntImag,
2226                                            Info.Ctx);
2227        return true;
2228      }
2229    }
2230  }
2231
2232  // FIXME: Handle more casts.
2233  return false;
2234}
2235
2236bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2237  if (!Visit(E->getLHS()))
2238    return false;
2239
2240  ComplexValue RHS;
2241  if (!EvaluateComplex(E->getRHS(), RHS, Info))
2242    return false;
2243
2244  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2245         "Invalid operands to binary operator.");
2246  switch (E->getOpcode()) {
2247  default: return false;
2248  case BO_Add:
2249    if (Result.isComplexFloat()) {
2250      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2251                                       APFloat::rmNearestTiesToEven);
2252      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2253                                       APFloat::rmNearestTiesToEven);
2254    } else {
2255      Result.getComplexIntReal() += RHS.getComplexIntReal();
2256      Result.getComplexIntImag() += RHS.getComplexIntImag();
2257    }
2258    break;
2259  case BO_Sub:
2260    if (Result.isComplexFloat()) {
2261      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2262                                            APFloat::rmNearestTiesToEven);
2263      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2264                                            APFloat::rmNearestTiesToEven);
2265    } else {
2266      Result.getComplexIntReal() -= RHS.getComplexIntReal();
2267      Result.getComplexIntImag() -= RHS.getComplexIntImag();
2268    }
2269    break;
2270  case BO_Mul:
2271    if (Result.isComplexFloat()) {
2272      ComplexValue LHS = Result;
2273      APFloat &LHS_r = LHS.getComplexFloatReal();
2274      APFloat &LHS_i = LHS.getComplexFloatImag();
2275      APFloat &RHS_r = RHS.getComplexFloatReal();
2276      APFloat &RHS_i = RHS.getComplexFloatImag();
2277
2278      APFloat Tmp = LHS_r;
2279      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2280      Result.getComplexFloatReal() = Tmp;
2281      Tmp = LHS_i;
2282      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2283      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2284
2285      Tmp = LHS_r;
2286      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2287      Result.getComplexFloatImag() = Tmp;
2288      Tmp = LHS_i;
2289      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2290      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2291    } else {
2292      ComplexValue LHS = Result;
2293      Result.getComplexIntReal() =
2294        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2295         LHS.getComplexIntImag() * RHS.getComplexIntImag());
2296      Result.getComplexIntImag() =
2297        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2298         LHS.getComplexIntImag() * RHS.getComplexIntReal());
2299    }
2300    break;
2301  }
2302
2303  return true;
2304}
2305
2306//===----------------------------------------------------------------------===//
2307// Top level Expr::Evaluate method.
2308//===----------------------------------------------------------------------===//
2309
2310/// Evaluate - Return true if this is a constant which we can fold using
2311/// any crazy technique (that has nothing to do with language standards) that
2312/// we want to.  If this function returns true, it returns the folded constant
2313/// in Result.
2314bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2315  const Expr *E = this;
2316  EvalInfo Info(Ctx, Result);
2317  if (E->getType()->isVectorType()) {
2318    if (!EvaluateVector(E, Info.EvalResult.Val, Info))
2319      return false;
2320  } else if (E->getType()->isIntegerType()) {
2321    if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
2322      return false;
2323    if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2324      return false;
2325  } else if (E->getType()->hasPointerRepresentation()) {
2326    LValue LV;
2327    if (!EvaluatePointer(E, LV, Info))
2328      return false;
2329    if (!IsGlobalLValue(LV.Base))
2330      return false;
2331    LV.moveInto(Info.EvalResult.Val);
2332  } else if (E->getType()->isRealFloatingType()) {
2333    llvm::APFloat F(0.0);
2334    if (!EvaluateFloat(E, F, Info))
2335      return false;
2336
2337    Info.EvalResult.Val = APValue(F);
2338  } else if (E->getType()->isAnyComplexType()) {
2339    ComplexValue C;
2340    if (!EvaluateComplex(E, C, Info))
2341      return false;
2342    C.moveInto(Info.EvalResult.Val);
2343  } else
2344    return false;
2345
2346  return true;
2347}
2348
2349bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2350  EvalResult Scratch;
2351  EvalInfo Info(Ctx, Scratch);
2352
2353  return HandleConversionToBool(this, Result, Info);
2354}
2355
2356bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2357  EvalInfo Info(Ctx, Result);
2358
2359  LValue LV;
2360  if (EvaluateLValue(this, LV, Info) &&
2361      !Result.HasSideEffects &&
2362      IsGlobalLValue(LV.Base)) {
2363    LV.moveInto(Result.Val);
2364    return true;
2365  }
2366  return false;
2367}
2368
2369bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2370  EvalInfo Info(Ctx, Result);
2371
2372  LValue LV;
2373  if (EvaluateLValue(this, LV, Info)) {
2374    LV.moveInto(Result.Val);
2375    return true;
2376  }
2377  return false;
2378}
2379
2380/// isEvaluatable - Call Evaluate to see if this expression can be constant
2381/// folded, but discard the result.
2382bool Expr::isEvaluatable(ASTContext &Ctx) const {
2383  EvalResult Result;
2384  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
2385}
2386
2387bool Expr::HasSideEffects(ASTContext &Ctx) const {
2388  Expr::EvalResult Result;
2389  EvalInfo Info(Ctx, Result);
2390  return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2391}
2392
2393APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
2394  EvalResult EvalResult;
2395  bool Result = Evaluate(EvalResult, Ctx);
2396  Result = Result;
2397  assert(Result && "Could not evaluate expression");
2398  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
2399
2400  return EvalResult.Val.getInt();
2401}
2402
2403 bool Expr::EvalResult::isGlobalLValue() const {
2404   assert(Val.isLValue());
2405   return IsGlobalLValue(Val.getLValueBase());
2406 }
2407
2408
2409/// isIntegerConstantExpr - this recursive routine will test if an expression is
2410/// an integer constant expression.
2411
2412/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2413/// comma, etc
2414///
2415/// FIXME: Handle offsetof.  Two things to do:  Handle GCC's __builtin_offsetof
2416/// to support gcc 4.0+  and handle the idiom GCC recognizes with a null pointer
2417/// cast+dereference.
2418
2419// CheckICE - This function does the fundamental ICE checking: the returned
2420// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2421// Note that to reduce code duplication, this helper does no evaluation
2422// itself; the caller checks whether the expression is evaluatable, and
2423// in the rare cases where CheckICE actually cares about the evaluated
2424// value, it calls into Evalute.
2425//
2426// Meanings of Val:
2427// 0: This expression is an ICE if it can be evaluated by Evaluate.
2428// 1: This expression is not an ICE, but if it isn't evaluated, it's
2429//    a legal subexpression for an ICE. This return value is used to handle
2430//    the comma operator in C99 mode.
2431// 2: This expression is not an ICE, and is not a legal subexpression for one.
2432
2433namespace {
2434
2435struct ICEDiag {
2436  unsigned Val;
2437  SourceLocation Loc;
2438
2439  public:
2440  ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2441  ICEDiag() : Val(0) {}
2442};
2443
2444}
2445
2446static ICEDiag NoDiag() { return ICEDiag(); }
2447
2448static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2449  Expr::EvalResult EVResult;
2450  if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2451      !EVResult.Val.isInt()) {
2452    return ICEDiag(2, E->getLocStart());
2453  }
2454  return NoDiag();
2455}
2456
2457static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2458  assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2459  if (!E->getType()->isIntegralOrEnumerationType()) {
2460    return ICEDiag(2, E->getLocStart());
2461  }
2462
2463  switch (E->getStmtClass()) {
2464#define STMT(Node, Base) case Expr::Node##Class:
2465#define EXPR(Node, Base)
2466#include "clang/AST/StmtNodes.inc"
2467  case Expr::PredefinedExprClass:
2468  case Expr::FloatingLiteralClass:
2469  case Expr::ImaginaryLiteralClass:
2470  case Expr::StringLiteralClass:
2471  case Expr::ArraySubscriptExprClass:
2472  case Expr::MemberExprClass:
2473  case Expr::CompoundAssignOperatorClass:
2474  case Expr::CompoundLiteralExprClass:
2475  case Expr::ExtVectorElementExprClass:
2476  case Expr::InitListExprClass:
2477  case Expr::DesignatedInitExprClass:
2478  case Expr::ImplicitValueInitExprClass:
2479  case Expr::ParenListExprClass:
2480  case Expr::VAArgExprClass:
2481  case Expr::AddrLabelExprClass:
2482  case Expr::StmtExprClass:
2483  case Expr::CXXMemberCallExprClass:
2484  case Expr::CXXDynamicCastExprClass:
2485  case Expr::CXXTypeidExprClass:
2486  case Expr::CXXUuidofExprClass:
2487  case Expr::CXXNullPtrLiteralExprClass:
2488  case Expr::CXXThisExprClass:
2489  case Expr::CXXThrowExprClass:
2490  case Expr::CXXNewExprClass:
2491  case Expr::CXXDeleteExprClass:
2492  case Expr::CXXPseudoDestructorExprClass:
2493  case Expr::UnresolvedLookupExprClass:
2494  case Expr::DependentScopeDeclRefExprClass:
2495  case Expr::CXXConstructExprClass:
2496  case Expr::CXXBindTemporaryExprClass:
2497  case Expr::ExprWithCleanupsClass:
2498  case Expr::CXXTemporaryObjectExprClass:
2499  case Expr::CXXUnresolvedConstructExprClass:
2500  case Expr::CXXDependentScopeMemberExprClass:
2501  case Expr::UnresolvedMemberExprClass:
2502  case Expr::ObjCStringLiteralClass:
2503  case Expr::ObjCEncodeExprClass:
2504  case Expr::ObjCMessageExprClass:
2505  case Expr::ObjCSelectorExprClass:
2506  case Expr::ObjCProtocolExprClass:
2507  case Expr::ObjCIvarRefExprClass:
2508  case Expr::ObjCPropertyRefExprClass:
2509  case Expr::ObjCIsaExprClass:
2510  case Expr::ShuffleVectorExprClass:
2511  case Expr::BlockExprClass:
2512  case Expr::BlockDeclRefExprClass:
2513  case Expr::NoStmtClass:
2514  case Expr::OpaqueValueExprClass:
2515    return ICEDiag(2, E->getLocStart());
2516
2517  case Expr::GNUNullExprClass:
2518    // GCC considers the GNU __null value to be an integral constant expression.
2519    return NoDiag();
2520
2521  case Expr::ParenExprClass:
2522    return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2523  case Expr::IntegerLiteralClass:
2524  case Expr::CharacterLiteralClass:
2525  case Expr::CXXBoolLiteralExprClass:
2526  case Expr::CXXScalarValueInitExprClass:
2527  case Expr::TypesCompatibleExprClass:
2528  case Expr::UnaryTypeTraitExprClass:
2529  case Expr::CXXNoexceptExprClass:
2530    return NoDiag();
2531  case Expr::CallExprClass:
2532  case Expr::CXXOperatorCallExprClass: {
2533    const CallExpr *CE = cast<CallExpr>(E);
2534    if (CE->isBuiltinCall(Ctx))
2535      return CheckEvalInICE(E, Ctx);
2536    return ICEDiag(2, E->getLocStart());
2537  }
2538  case Expr::DeclRefExprClass:
2539    if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2540      return NoDiag();
2541    if (Ctx.getLangOptions().CPlusPlus &&
2542        E->getType().getCVRQualifiers() == Qualifiers::Const) {
2543      const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2544
2545      // Parameter variables are never constants.  Without this check,
2546      // getAnyInitializer() can find a default argument, which leads
2547      // to chaos.
2548      if (isa<ParmVarDecl>(D))
2549        return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2550
2551      // C++ 7.1.5.1p2
2552      //   A variable of non-volatile const-qualified integral or enumeration
2553      //   type initialized by an ICE can be used in ICEs.
2554      if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2555        Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2556        if (Quals.hasVolatile() || !Quals.hasConst())
2557          return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2558
2559        // Look for a declaration of this variable that has an initializer.
2560        const VarDecl *ID = 0;
2561        const Expr *Init = Dcl->getAnyInitializer(ID);
2562        if (Init) {
2563          if (ID->isInitKnownICE()) {
2564            // We have already checked whether this subexpression is an
2565            // integral constant expression.
2566            if (ID->isInitICE())
2567              return NoDiag();
2568            else
2569              return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2570          }
2571
2572          // It's an ICE whether or not the definition we found is
2573          // out-of-line.  See DR 721 and the discussion in Clang PR
2574          // 6206 for details.
2575
2576          if (Dcl->isCheckingICE()) {
2577            return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2578          }
2579
2580          Dcl->setCheckingICE();
2581          ICEDiag Result = CheckICE(Init, Ctx);
2582          // Cache the result of the ICE test.
2583          Dcl->setInitKnownICE(Result.Val == 0);
2584          return Result;
2585        }
2586      }
2587    }
2588    return ICEDiag(2, E->getLocStart());
2589  case Expr::UnaryOperatorClass: {
2590    const UnaryOperator *Exp = cast<UnaryOperator>(E);
2591    switch (Exp->getOpcode()) {
2592    case UO_PostInc:
2593    case UO_PostDec:
2594    case UO_PreInc:
2595    case UO_PreDec:
2596    case UO_AddrOf:
2597    case UO_Deref:
2598      return ICEDiag(2, E->getLocStart());
2599    case UO_Extension:
2600    case UO_LNot:
2601    case UO_Plus:
2602    case UO_Minus:
2603    case UO_Not:
2604    case UO_Real:
2605    case UO_Imag:
2606      return CheckICE(Exp->getSubExpr(), Ctx);
2607    }
2608
2609    // OffsetOf falls through here.
2610  }
2611  case Expr::OffsetOfExprClass: {
2612      // Note that per C99, offsetof must be an ICE. And AFAIK, using
2613      // Evaluate matches the proposed gcc behavior for cases like
2614      // "offsetof(struct s{int x[4];}, x[!.0])".  This doesn't affect
2615      // compliance: we should warn earlier for offsetof expressions with
2616      // array subscripts that aren't ICEs, and if the array subscripts
2617      // are ICEs, the value of the offsetof must be an integer constant.
2618      return CheckEvalInICE(E, Ctx);
2619  }
2620  case Expr::SizeOfAlignOfExprClass: {
2621    const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2622    if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2623      return ICEDiag(2, E->getLocStart());
2624    return NoDiag();
2625  }
2626  case Expr::BinaryOperatorClass: {
2627    const BinaryOperator *Exp = cast<BinaryOperator>(E);
2628    switch (Exp->getOpcode()) {
2629    case BO_PtrMemD:
2630    case BO_PtrMemI:
2631    case BO_Assign:
2632    case BO_MulAssign:
2633    case BO_DivAssign:
2634    case BO_RemAssign:
2635    case BO_AddAssign:
2636    case BO_SubAssign:
2637    case BO_ShlAssign:
2638    case BO_ShrAssign:
2639    case BO_AndAssign:
2640    case BO_XorAssign:
2641    case BO_OrAssign:
2642      return ICEDiag(2, E->getLocStart());
2643
2644    case BO_Mul:
2645    case BO_Div:
2646    case BO_Rem:
2647    case BO_Add:
2648    case BO_Sub:
2649    case BO_Shl:
2650    case BO_Shr:
2651    case BO_LT:
2652    case BO_GT:
2653    case BO_LE:
2654    case BO_GE:
2655    case BO_EQ:
2656    case BO_NE:
2657    case BO_And:
2658    case BO_Xor:
2659    case BO_Or:
2660    case BO_Comma: {
2661      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2662      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2663      if (Exp->getOpcode() == BO_Div ||
2664          Exp->getOpcode() == BO_Rem) {
2665        // Evaluate gives an error for undefined Div/Rem, so make sure
2666        // we don't evaluate one.
2667        if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2668          llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2669          if (REval == 0)
2670            return ICEDiag(1, E->getLocStart());
2671          if (REval.isSigned() && REval.isAllOnesValue()) {
2672            llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2673            if (LEval.isMinSignedValue())
2674              return ICEDiag(1, E->getLocStart());
2675          }
2676        }
2677      }
2678      if (Exp->getOpcode() == BO_Comma) {
2679        if (Ctx.getLangOptions().C99) {
2680          // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2681          // if it isn't evaluated.
2682          if (LHSResult.Val == 0 && RHSResult.Val == 0)
2683            return ICEDiag(1, E->getLocStart());
2684        } else {
2685          // In both C89 and C++, commas in ICEs are illegal.
2686          return ICEDiag(2, E->getLocStart());
2687        }
2688      }
2689      if (LHSResult.Val >= RHSResult.Val)
2690        return LHSResult;
2691      return RHSResult;
2692    }
2693    case BO_LAnd:
2694    case BO_LOr: {
2695      ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2696      ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2697      if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2698        // Rare case where the RHS has a comma "side-effect"; we need
2699        // to actually check the condition to see whether the side
2700        // with the comma is evaluated.
2701        if ((Exp->getOpcode() == BO_LAnd) !=
2702            (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2703          return RHSResult;
2704        return NoDiag();
2705      }
2706
2707      if (LHSResult.Val >= RHSResult.Val)
2708        return LHSResult;
2709      return RHSResult;
2710    }
2711    }
2712  }
2713  case Expr::ImplicitCastExprClass:
2714  case Expr::CStyleCastExprClass:
2715  case Expr::CXXFunctionalCastExprClass:
2716  case Expr::CXXStaticCastExprClass:
2717  case Expr::CXXReinterpretCastExprClass:
2718  case Expr::CXXConstCastExprClass: {
2719    const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2720    if (SubExpr->getType()->isIntegralOrEnumerationType())
2721      return CheckICE(SubExpr, Ctx);
2722    if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2723      return NoDiag();
2724    return ICEDiag(2, E->getLocStart());
2725  }
2726  case Expr::ConditionalOperatorClass: {
2727    const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2728    // If the condition (ignoring parens) is a __builtin_constant_p call,
2729    // then only the true side is actually considered in an integer constant
2730    // expression, and it is fully evaluated.  This is an important GNU
2731    // extension.  See GCC PR38377 for discussion.
2732    if (const CallExpr *CallCE
2733        = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2734      if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2735        Expr::EvalResult EVResult;
2736        if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2737            !EVResult.Val.isInt()) {
2738          return ICEDiag(2, E->getLocStart());
2739        }
2740        return NoDiag();
2741      }
2742    ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2743    ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2744    ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2745    if (CondResult.Val == 2)
2746      return CondResult;
2747    if (TrueResult.Val == 2)
2748      return TrueResult;
2749    if (FalseResult.Val == 2)
2750      return FalseResult;
2751    if (CondResult.Val == 1)
2752      return CondResult;
2753    if (TrueResult.Val == 0 && FalseResult.Val == 0)
2754      return NoDiag();
2755    // Rare case where the diagnostics depend on which side is evaluated
2756    // Note that if we get here, CondResult is 0, and at least one of
2757    // TrueResult and FalseResult is non-zero.
2758    if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2759      return FalseResult;
2760    }
2761    return TrueResult;
2762  }
2763  case Expr::CXXDefaultArgExprClass:
2764    return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2765  case Expr::ChooseExprClass: {
2766    return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2767  }
2768  }
2769
2770  // Silence a GCC warning
2771  return ICEDiag(2, E->getLocStart());
2772}
2773
2774bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2775                                 SourceLocation *Loc, bool isEvaluated) const {
2776  ICEDiag d = CheckICE(this, Ctx);
2777  if (d.Val != 0) {
2778    if (Loc) *Loc = d.Loc;
2779    return false;
2780  }
2781  EvalResult EvalResult;
2782  if (!Evaluate(EvalResult, Ctx))
2783    llvm_unreachable("ICE cannot be evaluated!");
2784  assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2785  assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2786  Result = EvalResult.Val.getInt();
2787  return true;
2788}
2789