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