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