ExprConstant.cpp revision c9f5eac5c940cc542c7f26560653cfeecd264545
1//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/RecordLayout.h"
17#include "clang/AST/StmtVisitor.h"
18#include "clang/AST/ASTDiagnostic.h"
19#include "clang/Basic/Builtins.h"
20#include "clang/Basic/TargetInfo.h"
21#include "llvm/ADT/SmallString.h"
22#include "llvm/Support/Compiler.h"
23#include <cstring>
24
25using namespace clang;
26using llvm::APSInt;
27using llvm::APFloat;
28
29/// EvalInfo - This is a private struct used by the evaluator to capture
30/// information about a subexpression as it is folded.  It retains information
31/// about the AST context, but also maintains information about the folded
32/// expression.
33///
34/// If an expression could be evaluated, it is still possible it is not a C
35/// "integer constant expression" or constant expression.  If not, this struct
36/// captures information about how and why not.
37///
38/// One bit of information passed *into* the request for constant folding
39/// indicates whether the subexpression is "evaluated" or not according to C
40/// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
41/// evaluate the expression regardless of what the RHS is, but C only allows
42/// certain things in certain situations.
43struct EvalInfo {
44  ASTContext &Ctx;
45
46  /// EvalResult - Contains information about the evaluation.
47  Expr::EvalResult &EvalResult;
48
49  /// AnyLValue - Stack based LValue results are not discarded.
50  bool AnyLValue;
51
52  EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult,
53           bool anylvalue = false)
54    : Ctx(ctx), EvalResult(evalresult), AnyLValue(anylvalue) {}
55};
56
57
58static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
59static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
60static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
61static bool EvaluateIntegerOrLValue(const Expr *E, APValue  &Result,
62                                    EvalInfo &Info);
63static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
64static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
65
66//===----------------------------------------------------------------------===//
67// Misc utilities
68//===----------------------------------------------------------------------===//
69
70static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
71  // FIXME: Is this accurate for all kinds of bases?  If not, what would
72  // the check look like?
73  Result = Value.getLValueBase() || Value.getLValueOffset();
74  return true;
75}
76
77static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
78  if (E->getType()->isIntegralType()) {
79    APSInt IntResult;
80    if (!EvaluateInteger(E, IntResult, Info))
81      return false;
82    Result = IntResult != 0;
83    return true;
84  } else if (E->getType()->isRealFloatingType()) {
85    APFloat FloatResult(0.0);
86    if (!EvaluateFloat(E, FloatResult, Info))
87      return false;
88    Result = !FloatResult.isZero();
89    return true;
90  } else if (E->getType()->hasPointerRepresentation()) {
91    APValue PointerResult;
92    if (!EvaluatePointer(E, PointerResult, Info))
93      return false;
94    return EvalPointerValueAsBool(PointerResult, Result);
95  } else if (E->getType()->isAnyComplexType()) {
96    APValue ComplexResult;
97    if (!EvaluateComplex(E, ComplexResult, Info))
98      return false;
99    if (ComplexResult.isComplexFloat()) {
100      Result = !ComplexResult.getComplexFloatReal().isZero() ||
101               !ComplexResult.getComplexFloatImag().isZero();
102    } else {
103      Result = ComplexResult.getComplexIntReal().getBoolValue() ||
104               ComplexResult.getComplexIntImag().getBoolValue();
105    }
106    return true;
107  }
108
109  return false;
110}
111
112static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
113                                   APFloat &Value, ASTContext &Ctx) {
114  unsigned DestWidth = Ctx.getIntWidth(DestType);
115  // Determine whether we are converting to unsigned or signed.
116  bool DestSigned = DestType->isSignedIntegerType();
117
118  // FIXME: Warning for overflow.
119  uint64_t Space[4];
120  bool ignored;
121  (void)Value.convertToInteger(Space, DestWidth, DestSigned,
122                               llvm::APFloat::rmTowardZero, &ignored);
123  return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
124}
125
126static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
127                                      APFloat &Value, ASTContext &Ctx) {
128  bool ignored;
129  APFloat Result = Value;
130  Result.convert(Ctx.getFloatTypeSemantics(DestType),
131                 APFloat::rmNearestTiesToEven, &ignored);
132  return Result;
133}
134
135static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
136                                 APSInt &Value, ASTContext &Ctx) {
137  unsigned DestWidth = Ctx.getIntWidth(DestType);
138  APSInt Result = Value;
139  // Figure out if this is a truncate, extend or noop cast.
140  // If the input is signed, do a sign extend, noop, or truncate.
141  Result.extOrTrunc(DestWidth);
142  Result.setIsUnsigned(DestType->isUnsignedIntegerType());
143  return Result;
144}
145
146static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
147                                    APSInt &Value, ASTContext &Ctx) {
148
149  APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
150  Result.convertFromAPInt(Value, Value.isSigned(),
151                          APFloat::rmNearestTiesToEven);
152  return Result;
153}
154
155namespace {
156class VISIBILITY_HIDDEN HasSideEffect
157  : public StmtVisitor<HasSideEffect, bool> {
158  EvalInfo &Info;
159public:
160
161  HasSideEffect(EvalInfo &info) : Info(info) {}
162
163  // Unhandled nodes conservatively default to having side effects.
164  bool VisitStmt(Stmt *S) {
165    return true;
166  }
167
168  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
169  bool VisitDeclRefExpr(DeclRefExpr *E) {
170    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
171      return true;
172    return false;
173  }
174  // We don't want to evaluate BlockExprs multiple times, as they generate
175  // a ton of code.
176  bool VisitBlockExpr(BlockExpr *E) { return true; }
177  bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
178  bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
179    { return Visit(E->getInitializer()); }
180  bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
181  bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
182  bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
183  bool VisitStringLiteral(StringLiteral *E) { return false; }
184  bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
185  bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
186  bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
187    { return Visit(E->getLHS()) || Visit(E->getRHS()); }
188  bool VisitChooseExpr(ChooseExpr *E)
189    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
190  bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
191  bool VisitBinAssign(BinaryOperator *E) { return true; }
192  bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
193  bool VisitBinaryOperator(BinaryOperator *E)
194  { return Visit(E->getLHS()) || Visit(E->getRHS()); }
195  bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
196  bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
197  bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
198  bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
199  bool VisitUnaryDeref(UnaryOperator *E) {
200    if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
201      return true;
202    return Visit(E->getSubExpr());
203  }
204  bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
205};
206
207bool HasSideEffects(const Expr* E, ASTContext &Ctx) {
208  Expr::EvalResult Result;
209  EvalInfo Info(Ctx, Result);
210
211  return HasSideEffect(Info).Visit(const_cast<Expr*>(E));
212}
213
214} // end anonymous namespace
215
216//===----------------------------------------------------------------------===//
217// LValue Evaluation
218//===----------------------------------------------------------------------===//
219namespace {
220class VISIBILITY_HIDDEN LValueExprEvaluator
221  : public StmtVisitor<LValueExprEvaluator, APValue> {
222  EvalInfo &Info;
223public:
224
225  LValueExprEvaluator(EvalInfo &info) : Info(info) {}
226
227  APValue VisitStmt(Stmt *S) {
228    return APValue();
229  }
230
231  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
232  APValue VisitDeclRefExpr(DeclRefExpr *E);
233  APValue VisitBlockExpr(BlockExpr *E);
234  APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
235  APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
236  APValue VisitMemberExpr(MemberExpr *E);
237  APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
238  APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E, 0); }
239  APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
240  APValue VisitUnaryDeref(UnaryOperator *E);
241  APValue VisitUnaryExtension(const UnaryOperator *E)
242    { return Visit(E->getSubExpr()); }
243  APValue VisitChooseExpr(const ChooseExpr *E)
244    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
245
246  APValue VisitCastExpr(CastExpr *E) {
247    switch (E->getCastKind()) {
248    default:
249      return APValue();
250
251    case CastExpr::CK_NoOp:
252      return Visit(E->getSubExpr());
253    }
254  }
255  // FIXME: Missing: __real__, __imag__
256};
257} // end anonymous namespace
258
259static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
260  Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
261  return Result.isLValue();
262}
263
264APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
265  if (isa<FunctionDecl>(E->getDecl())) {
266    return APValue(E, 0);
267  } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
268    if (!Info.AnyLValue && !VD->hasGlobalStorage())
269      return APValue();
270    if (!VD->getType()->isReferenceType())
271      return APValue(E, 0);
272    // FIXME: Check whether VD might be overridden!
273    const VarDecl *Def = 0;
274    if (const Expr *Init = VD->getDefinition(Def))
275      return Visit(const_cast<Expr *>(Init));
276  }
277
278  return APValue();
279}
280
281APValue LValueExprEvaluator::VisitBlockExpr(BlockExpr *E) {
282  if (E->hasBlockDeclRefExprs())
283    return APValue();
284
285  return APValue(E, 0);
286}
287
288APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
289  if (!Info.AnyLValue && !E->isFileScope())
290    return APValue();
291  return APValue(E, 0);
292}
293
294APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
295  APValue result;
296  QualType Ty;
297  if (E->isArrow()) {
298    if (!EvaluatePointer(E->getBase(), result, Info))
299      return APValue();
300    Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
301  } else {
302    result = Visit(E->getBase());
303    if (result.isUninit())
304      return APValue();
305    Ty = E->getBase()->getType();
306  }
307
308  RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
309  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
310
311  FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
312  if (!FD) // FIXME: deal with other kinds of member expressions
313    return APValue();
314
315  if (FD->getType()->isReferenceType())
316    return APValue();
317
318  // FIXME: This is linear time.
319  unsigned i = 0;
320  for (RecordDecl::field_iterator Field = RD->field_begin(),
321                               FieldEnd = RD->field_end();
322       Field != FieldEnd; (void)++Field, ++i) {
323    if (*Field == FD)
324      break;
325  }
326
327  result.setLValue(result.getLValueBase(),
328                   result.getLValueOffset() + RL.getFieldOffset(i) / 8);
329
330  return result;
331}
332
333APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
334  APValue Result;
335
336  if (!EvaluatePointer(E->getBase(), Result, Info))
337    return APValue();
338
339  APSInt Index;
340  if (!EvaluateInteger(E->getIdx(), Index, Info))
341    return APValue();
342
343  uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
344
345  uint64_t Offset = Index.getSExtValue() * ElementSize;
346  Result.setLValue(Result.getLValueBase(),
347                   Result.getLValueOffset() + Offset);
348  return Result;
349}
350
351APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
352  APValue Result;
353  if (!EvaluatePointer(E->getSubExpr(), Result, Info))
354    return APValue();
355  return Result;
356}
357
358//===----------------------------------------------------------------------===//
359// Pointer Evaluation
360//===----------------------------------------------------------------------===//
361
362namespace {
363class VISIBILITY_HIDDEN PointerExprEvaluator
364  : public StmtVisitor<PointerExprEvaluator, APValue> {
365  EvalInfo &Info;
366public:
367
368  PointerExprEvaluator(EvalInfo &info) : Info(info) {}
369
370  APValue VisitStmt(Stmt *S) {
371    return APValue();
372  }
373
374  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
375
376  APValue VisitBinaryOperator(const BinaryOperator *E);
377  APValue VisitCastExpr(const CastExpr* E);
378  APValue VisitUnaryExtension(const UnaryOperator *E)
379      { return Visit(E->getSubExpr()); }
380  APValue VisitUnaryAddrOf(const UnaryOperator *E);
381  APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
382      { return APValue(E, 0); }
383  APValue VisitAddrLabelExpr(AddrLabelExpr *E)
384      { return APValue(E, 0); }
385  APValue VisitCallExpr(CallExpr *E);
386  APValue VisitBlockExpr(BlockExpr *E) {
387    if (!E->hasBlockDeclRefExprs())
388      return APValue(E, 0);
389    return APValue();
390  }
391  APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
392      { return APValue((Expr*)0, 0); }
393  APValue VisitConditionalOperator(ConditionalOperator *E);
394  APValue VisitChooseExpr(ChooseExpr *E)
395      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
396  APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
397      { return APValue((Expr*)0, 0); }
398  // FIXME: Missing: @protocol, @selector
399};
400} // end anonymous namespace
401
402static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
403  if (!E->getType()->hasPointerRepresentation())
404    return false;
405  Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
406  return Result.isLValue();
407}
408
409APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
410  if (E->getOpcode() != BinaryOperator::Add &&
411      E->getOpcode() != BinaryOperator::Sub)
412    return APValue();
413
414  const Expr *PExp = E->getLHS();
415  const Expr *IExp = E->getRHS();
416  if (IExp->getType()->isPointerType())
417    std::swap(PExp, IExp);
418
419  APValue ResultLValue;
420  if (!EvaluatePointer(PExp, ResultLValue, Info))
421    return APValue();
422
423  llvm::APSInt AdditionalOffset(32);
424  if (!EvaluateInteger(IExp, AdditionalOffset, Info))
425    return APValue();
426
427  QualType PointeeType = PExp->getType()->getAs<PointerType>()->getPointeeType();
428  uint64_t SizeOfPointee;
429
430  // Explicitly handle GNU void* and function pointer arithmetic extensions.
431  if (PointeeType->isVoidType() || PointeeType->isFunctionType())
432    SizeOfPointee = 1;
433  else
434    SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
435
436  uint64_t Offset = ResultLValue.getLValueOffset();
437
438  if (E->getOpcode() == BinaryOperator::Add)
439    Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
440  else
441    Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
442
443  return APValue(ResultLValue.getLValueBase(), Offset);
444}
445
446APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
447  APValue result;
448  if (EvaluateLValue(E->getSubExpr(), result, Info))
449    return result;
450  return APValue();
451}
452
453
454APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
455  const Expr* SubExpr = E->getSubExpr();
456
457   // Check for pointer->pointer cast
458  if (SubExpr->getType()->isPointerType() ||
459      SubExpr->getType()->isObjCObjectPointerType() ||
460      SubExpr->getType()->isNullPtrType()) {
461    APValue Result;
462    if (EvaluatePointer(SubExpr, Result, Info))
463      return Result;
464    return APValue();
465  }
466
467  if (SubExpr->getType()->isIntegralType()) {
468    APValue Result;
469    if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
470      return APValue();
471
472    if (Result.isInt()) {
473      Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
474      return APValue(0, Result.getInt().getZExtValue());
475    }
476
477    // Cast is of an lvalue, no need to change value.
478    return Result;
479  }
480
481  if (SubExpr->getType()->isFunctionType() ||
482      SubExpr->getType()->isBlockPointerType() ||
483      SubExpr->getType()->isArrayType()) {
484    APValue Result;
485    if (EvaluateLValue(SubExpr, Result, Info))
486      return Result;
487    return APValue();
488  }
489
490  return APValue();
491}
492
493APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
494  if (E->isBuiltinCall(Info.Ctx) ==
495        Builtin::BI__builtin___CFStringMakeConstantString)
496    return APValue(E, 0);
497  return APValue();
498}
499
500APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
501  bool BoolResult;
502  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
503    return APValue();
504
505  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
506
507  APValue Result;
508  if (EvaluatePointer(EvalExpr, Result, Info))
509    return Result;
510  return APValue();
511}
512
513//===----------------------------------------------------------------------===//
514// Vector Evaluation
515//===----------------------------------------------------------------------===//
516
517namespace {
518  class VISIBILITY_HIDDEN VectorExprEvaluator
519  : public StmtVisitor<VectorExprEvaluator, APValue> {
520    EvalInfo &Info;
521    APValue GetZeroVector(QualType VecType);
522  public:
523
524    VectorExprEvaluator(EvalInfo &info) : Info(info) {}
525
526    APValue VisitStmt(Stmt *S) {
527      return APValue();
528    }
529
530    APValue VisitParenExpr(ParenExpr *E)
531        { return Visit(E->getSubExpr()); }
532    APValue VisitUnaryExtension(const UnaryOperator *E)
533      { return Visit(E->getSubExpr()); }
534    APValue VisitUnaryPlus(const UnaryOperator *E)
535      { return Visit(E->getSubExpr()); }
536    APValue VisitUnaryReal(const UnaryOperator *E)
537      { return Visit(E->getSubExpr()); }
538    APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
539      { return GetZeroVector(E->getType()); }
540    APValue VisitCastExpr(const CastExpr* E);
541    APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
542    APValue VisitInitListExpr(const InitListExpr *E);
543    APValue VisitConditionalOperator(const ConditionalOperator *E);
544    APValue VisitChooseExpr(const ChooseExpr *E)
545      { return Visit(E->getChosenSubExpr(Info.Ctx)); }
546    APValue VisitUnaryImag(const UnaryOperator *E);
547    // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
548    //                 binary comparisons, binary and/or/xor,
549    //                 shufflevector, ExtVectorElementExpr
550    //        (Note that these require implementing conversions
551    //         between vector types.)
552  };
553} // end anonymous namespace
554
555static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
556  if (!E->getType()->isVectorType())
557    return false;
558  Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
559  return !Result.isUninit();
560}
561
562APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
563  const VectorType *VTy = E->getType()->getAs<VectorType>();
564  QualType EltTy = VTy->getElementType();
565  unsigned NElts = VTy->getNumElements();
566  unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
567
568  const Expr* SE = E->getSubExpr();
569  QualType SETy = SE->getType();
570  APValue Result = APValue();
571
572  // Check for vector->vector bitcast and scalar->vector splat.
573  if (SETy->isVectorType()) {
574    return this->Visit(const_cast<Expr*>(SE));
575  } else if (SETy->isIntegerType()) {
576    APSInt IntResult;
577    if (!EvaluateInteger(SE, IntResult, Info))
578      return APValue();
579    Result = APValue(IntResult);
580  } else if (SETy->isRealFloatingType()) {
581    APFloat F(0.0);
582    if (!EvaluateFloat(SE, F, Info))
583      return APValue();
584    Result = APValue(F);
585  } else
586    return APValue();
587
588  // For casts of a scalar to ExtVector, convert the scalar to the element type
589  // and splat it to all elements.
590  if (E->getType()->isExtVectorType()) {
591    if (EltTy->isIntegerType() && Result.isInt())
592      Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
593                                          Info.Ctx));
594    else if (EltTy->isIntegerType())
595      Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
596                                            Info.Ctx));
597    else if (EltTy->isRealFloatingType() && Result.isInt())
598      Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
599                                            Info.Ctx));
600    else if (EltTy->isRealFloatingType())
601      Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
602                                              Info.Ctx));
603    else
604      return APValue();
605
606    // Splat and create vector APValue.
607    llvm::SmallVector<APValue, 4> Elts(NElts, Result);
608    return APValue(&Elts[0], Elts.size());
609  }
610
611  // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
612  // to the vector. To construct the APValue vector initializer, bitcast the
613  // initializing value to an APInt, and shift out the bits pertaining to each
614  // element.
615  APSInt Init;
616  Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
617
618  llvm::SmallVector<APValue, 4> Elts;
619  for (unsigned i = 0; i != NElts; ++i) {
620    APSInt Tmp = Init;
621    Tmp.extOrTrunc(EltWidth);
622
623    if (EltTy->isIntegerType())
624      Elts.push_back(APValue(Tmp));
625    else if (EltTy->isRealFloatingType())
626      Elts.push_back(APValue(APFloat(Tmp)));
627    else
628      return APValue();
629
630    Init >>= EltWidth;
631  }
632  return APValue(&Elts[0], Elts.size());
633}
634
635APValue
636VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
637  return this->Visit(const_cast<Expr*>(E->getInitializer()));
638}
639
640APValue
641VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
642  const VectorType *VT = E->getType()->getAs<VectorType>();
643  unsigned NumInits = E->getNumInits();
644  unsigned NumElements = VT->getNumElements();
645
646  QualType EltTy = VT->getElementType();
647  llvm::SmallVector<APValue, 4> Elements;
648
649  for (unsigned i = 0; i < NumElements; i++) {
650    if (EltTy->isIntegerType()) {
651      llvm::APSInt sInt(32);
652      if (i < NumInits) {
653        if (!EvaluateInteger(E->getInit(i), sInt, Info))
654          return APValue();
655      } else {
656        sInt = Info.Ctx.MakeIntValue(0, EltTy);
657      }
658      Elements.push_back(APValue(sInt));
659    } else {
660      llvm::APFloat f(0.0);
661      if (i < NumInits) {
662        if (!EvaluateFloat(E->getInit(i), f, Info))
663          return APValue();
664      } else {
665        f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
666      }
667      Elements.push_back(APValue(f));
668    }
669  }
670  return APValue(&Elements[0], Elements.size());
671}
672
673APValue
674VectorExprEvaluator::GetZeroVector(QualType T) {
675  const VectorType *VT = T->getAs<VectorType>();
676  QualType EltTy = VT->getElementType();
677  APValue ZeroElement;
678  if (EltTy->isIntegerType())
679    ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
680  else
681    ZeroElement =
682        APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
683
684  llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
685  return APValue(&Elements[0], Elements.size());
686}
687
688APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
689  bool BoolResult;
690  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
691    return APValue();
692
693  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
694
695  APValue Result;
696  if (EvaluateVector(EvalExpr, Result, Info))
697    return Result;
698  return APValue();
699}
700
701APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
702  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
703    Info.EvalResult.HasSideEffects = true;
704  return GetZeroVector(E->getType());
705}
706
707//===----------------------------------------------------------------------===//
708// Integer Evaluation
709//===----------------------------------------------------------------------===//
710
711namespace {
712class VISIBILITY_HIDDEN IntExprEvaluator
713  : public StmtVisitor<IntExprEvaluator, bool> {
714  EvalInfo &Info;
715  APValue &Result;
716public:
717  IntExprEvaluator(EvalInfo &info, APValue &result)
718    : Info(info), Result(result) {}
719
720  bool Success(const llvm::APSInt &SI, const Expr *E) {
721    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
722    assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
723           "Invalid evaluation result.");
724    assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
725           "Invalid evaluation result.");
726    Result = APValue(SI);
727    return true;
728  }
729
730  bool Success(const llvm::APInt &I, const Expr *E) {
731    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
732    assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
733           "Invalid evaluation result.");
734    Result = APValue(APSInt(I));
735    Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
736    return true;
737  }
738
739  bool Success(uint64_t Value, const Expr *E) {
740    assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
741    Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
742    return true;
743  }
744
745  bool Error(SourceLocation L, diag::kind D, const Expr *E) {
746    // Take the first error.
747    if (Info.EvalResult.Diag == 0) {
748      Info.EvalResult.DiagLoc = L;
749      Info.EvalResult.Diag = D;
750      Info.EvalResult.DiagExpr = E;
751    }
752    return false;
753  }
754
755  //===--------------------------------------------------------------------===//
756  //                            Visitor Methods
757  //===--------------------------------------------------------------------===//
758
759  bool VisitStmt(Stmt *) {
760    assert(0 && "This should be called on integers, stmts are not integers");
761    return false;
762  }
763
764  bool VisitExpr(Expr *E) {
765    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
766  }
767
768  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
769
770  bool VisitIntegerLiteral(const IntegerLiteral *E) {
771    return Success(E->getValue(), E);
772  }
773  bool VisitCharacterLiteral(const CharacterLiteral *E) {
774    return Success(E->getValue(), E);
775  }
776  bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
777    // Per gcc docs "this built-in function ignores top level
778    // qualifiers".  We need to use the canonical version to properly
779    // be able to strip CRV qualifiers from the type.
780    QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
781    QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
782    return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
783                                               T1.getUnqualifiedType()),
784                   E);
785  }
786  bool VisitDeclRefExpr(const DeclRefExpr *E);
787  bool VisitCallExpr(const CallExpr *E);
788  bool VisitBinaryOperator(const BinaryOperator *E);
789  bool VisitUnaryOperator(const UnaryOperator *E);
790  bool VisitConditionalOperator(const ConditionalOperator *E);
791
792  bool VisitCastExpr(CastExpr* E);
793  bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
794
795  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
796    return Success(E->getValue(), E);
797  }
798
799  bool VisitGNUNullExpr(const GNUNullExpr *E) {
800    return Success(0, E);
801  }
802
803  bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
804    return Success(0, E);
805  }
806
807  bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
808    return Success(0, E);
809  }
810
811  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
812    return Success(E->EvaluateTrait(Info.Ctx), E);
813  }
814
815  bool VisitChooseExpr(const ChooseExpr *E) {
816    return Visit(E->getChosenSubExpr(Info.Ctx));
817  }
818
819  bool VisitUnaryReal(const UnaryOperator *E);
820  bool VisitUnaryImag(const UnaryOperator *E);
821
822private:
823  unsigned GetAlignOfExpr(const Expr *E);
824  unsigned GetAlignOfType(QualType T);
825  // FIXME: Missing: array subscript of vector, member of vector
826};
827} // end anonymous namespace
828
829static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
830  if (!E->getType()->isIntegralType())
831    return false;
832
833  return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
834}
835
836static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
837  APValue Val;
838  if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
839    return false;
840  Result = Val.getInt();
841  return true;
842}
843
844bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
845  // Enums are integer constant exprs.
846  if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
847    // FIXME: This is an ugly hack around the fact that enums don't set their
848    // signedness consistently; see PR3173.
849    APSInt SI = D->getInitVal();
850    SI.setIsUnsigned(!E->getType()->isSignedIntegerType());
851    // FIXME: This is an ugly hack around the fact that enums don't
852    // set their width (!?!) consistently; see PR3173.
853    SI.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
854    return Success(SI, E);
855  }
856
857  // In C++, const, non-volatile integers initialized with ICEs are ICEs.
858  // In C, they can also be folded, although they are not ICEs.
859  if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
860                                                        == Qualifiers::Const) {
861    if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
862      const VarDecl *Def = 0;
863      if (const Expr *Init = D->getDefinition(Def)) {
864        if (APValue *V = D->getEvaluatedValue())
865          return Success(V->getInt(), E);
866
867        if (Visit(const_cast<Expr*>(Init))) {
868          // Cache the evaluated value in the variable declaration.
869          D->setEvaluatedValue(Info.Ctx, Result);
870          return true;
871        }
872
873        return false;
874      }
875    }
876  }
877
878  // Otherwise, random variable references are not constants.
879  return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
880}
881
882/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
883/// as GCC.
884static int EvaluateBuiltinClassifyType(const CallExpr *E) {
885  // The following enum mimics the values returned by GCC.
886  // FIXME: Does GCC differ between lvalue and rvalue references here?
887  enum gcc_type_class {
888    no_type_class = -1,
889    void_type_class, integer_type_class, char_type_class,
890    enumeral_type_class, boolean_type_class,
891    pointer_type_class, reference_type_class, offset_type_class,
892    real_type_class, complex_type_class,
893    function_type_class, method_type_class,
894    record_type_class, union_type_class,
895    array_type_class, string_type_class,
896    lang_type_class
897  };
898
899  // If no argument was supplied, default to "no_type_class". This isn't
900  // ideal, however it is what gcc does.
901  if (E->getNumArgs() == 0)
902    return no_type_class;
903
904  QualType ArgTy = E->getArg(0)->getType();
905  if (ArgTy->isVoidType())
906    return void_type_class;
907  else if (ArgTy->isEnumeralType())
908    return enumeral_type_class;
909  else if (ArgTy->isBooleanType())
910    return boolean_type_class;
911  else if (ArgTy->isCharType())
912    return string_type_class; // gcc doesn't appear to use char_type_class
913  else if (ArgTy->isIntegerType())
914    return integer_type_class;
915  else if (ArgTy->isPointerType())
916    return pointer_type_class;
917  else if (ArgTy->isReferenceType())
918    return reference_type_class;
919  else if (ArgTy->isRealType())
920    return real_type_class;
921  else if (ArgTy->isComplexType())
922    return complex_type_class;
923  else if (ArgTy->isFunctionType())
924    return function_type_class;
925  else if (ArgTy->isStructureType())
926    return record_type_class;
927  else if (ArgTy->isUnionType())
928    return union_type_class;
929  else if (ArgTy->isArrayType())
930    return array_type_class;
931  else if (ArgTy->isUnionType())
932    return union_type_class;
933  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
934    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
935  return -1;
936}
937
938bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
939  switch (E->isBuiltinCall(Info.Ctx)) {
940  default:
941    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
942
943  case Builtin::BI__builtin_object_size: {
944    const Expr *Arg = E->getArg(0)->IgnoreParens();
945    Expr::EvalResult Base;
946    if (Arg->EvaluateAsAny(Base, Info.Ctx)
947        && Base.Val.getKind() == APValue::LValue
948        && !Base.HasSideEffects)
949      if (const Expr *LVBase = Base.Val.getLValueBase())
950        if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) {
951          if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
952            if (!VD->getType()->isIncompleteType()
953                && VD->getType()->isObjectType()
954                && !VD->getType()->isVariablyModifiedType()
955                && !VD->getType()->isDependentType()) {
956              uint64_t Size = Info.Ctx.getTypeSize(VD->getType()) / 8;
957              uint64_t Offset = Base.Val.getLValueOffset();
958              if (Offset <= Size)
959                Size -= Base.Val.getLValueOffset();
960              else
961                Size = 0;
962              return Success(Size, E);
963            }
964          }
965        }
966
967    if (HasSideEffects(E->getArg(0), Info.Ctx)) {
968      if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() < 2)
969        return Success(-1ULL, E);
970      return Success(0, E);
971    }
972
973    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
974  }
975
976  case Builtin::BI__builtin_classify_type:
977    return Success(EvaluateBuiltinClassifyType(E), E);
978
979  case Builtin::BI__builtin_constant_p:
980    // __builtin_constant_p always has one operand: it returns true if that
981    // operand can be folded, false otherwise.
982    return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
983
984  case Builtin::BI__builtin_eh_return_data_regno: {
985    int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
986    Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
987    return Success(Operand, E);
988  }
989  }
990}
991
992bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
993  if (E->getOpcode() == BinaryOperator::Comma) {
994    if (!Visit(E->getRHS()))
995      return false;
996
997    // If we can't evaluate the LHS, it might have side effects;
998    // conservatively mark it.
999    if (!E->getLHS()->isEvaluatable(Info.Ctx))
1000      Info.EvalResult.HasSideEffects = true;
1001
1002    return true;
1003  }
1004
1005  if (E->isLogicalOp()) {
1006    // These need to be handled specially because the operands aren't
1007    // necessarily integral
1008    bool lhsResult, rhsResult;
1009
1010    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
1011      // We were able to evaluate the LHS, see if we can get away with not
1012      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
1013      if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
1014        return Success(lhsResult, E);
1015
1016      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1017        if (E->getOpcode() == BinaryOperator::LOr)
1018          return Success(lhsResult || rhsResult, E);
1019        else
1020          return Success(lhsResult && rhsResult, E);
1021      }
1022    } else {
1023      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
1024        // We can't evaluate the LHS; however, sometimes the result
1025        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
1026        if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
1027            !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
1028          // Since we weren't able to evaluate the left hand side, it
1029          // must have had side effects.
1030          Info.EvalResult.HasSideEffects = true;
1031
1032          return Success(rhsResult, E);
1033        }
1034      }
1035    }
1036
1037    return false;
1038  }
1039
1040  QualType LHSTy = E->getLHS()->getType();
1041  QualType RHSTy = E->getRHS()->getType();
1042
1043  if (LHSTy->isAnyComplexType()) {
1044    assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1045    APValue LHS, RHS;
1046
1047    if (!EvaluateComplex(E->getLHS(), LHS, Info))
1048      return false;
1049
1050    if (!EvaluateComplex(E->getRHS(), RHS, Info))
1051      return false;
1052
1053    if (LHS.isComplexFloat()) {
1054      APFloat::cmpResult CR_r =
1055        LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
1056      APFloat::cmpResult CR_i =
1057        LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1058
1059      if (E->getOpcode() == BinaryOperator::EQ)
1060        return Success((CR_r == APFloat::cmpEqual &&
1061                        CR_i == APFloat::cmpEqual), E);
1062      else {
1063        assert(E->getOpcode() == BinaryOperator::NE &&
1064               "Invalid complex comparison.");
1065        return Success(((CR_r == APFloat::cmpGreaterThan ||
1066                         CR_r == APFloat::cmpLessThan) &&
1067                        (CR_i == APFloat::cmpGreaterThan ||
1068                         CR_i == APFloat::cmpLessThan)), E);
1069      }
1070    } else {
1071      if (E->getOpcode() == BinaryOperator::EQ)
1072        return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1073                        LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1074      else {
1075        assert(E->getOpcode() == BinaryOperator::NE &&
1076               "Invalid compex comparison.");
1077        return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1078                        LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1079      }
1080    }
1081  }
1082
1083  if (LHSTy->isRealFloatingType() &&
1084      RHSTy->isRealFloatingType()) {
1085    APFloat RHS(0.0), LHS(0.0);
1086
1087    if (!EvaluateFloat(E->getRHS(), RHS, Info))
1088      return false;
1089
1090    if (!EvaluateFloat(E->getLHS(), LHS, Info))
1091      return false;
1092
1093    APFloat::cmpResult CR = LHS.compare(RHS);
1094
1095    switch (E->getOpcode()) {
1096    default:
1097      assert(0 && "Invalid binary operator!");
1098    case BinaryOperator::LT:
1099      return Success(CR == APFloat::cmpLessThan, E);
1100    case BinaryOperator::GT:
1101      return Success(CR == APFloat::cmpGreaterThan, E);
1102    case BinaryOperator::LE:
1103      return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
1104    case BinaryOperator::GE:
1105      return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
1106                     E);
1107    case BinaryOperator::EQ:
1108      return Success(CR == APFloat::cmpEqual, E);
1109    case BinaryOperator::NE:
1110      return Success(CR == APFloat::cmpGreaterThan
1111                     || CR == APFloat::cmpLessThan, E);
1112    }
1113  }
1114
1115  if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1116    if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
1117      APValue LHSValue;
1118      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1119        return false;
1120
1121      APValue RHSValue;
1122      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1123        return false;
1124
1125      // Reject any bases from the normal codepath; we special-case comparisons
1126      // to null.
1127      if (LHSValue.getLValueBase()) {
1128        if (!E->isEqualityOp())
1129          return false;
1130        if (RHSValue.getLValueBase() || RHSValue.getLValueOffset())
1131          return false;
1132        bool bres;
1133        if (!EvalPointerValueAsBool(LHSValue, bres))
1134          return false;
1135        return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1136      } else if (RHSValue.getLValueBase()) {
1137        if (!E->isEqualityOp())
1138          return false;
1139        if (LHSValue.getLValueBase() || LHSValue.getLValueOffset())
1140          return false;
1141        bool bres;
1142        if (!EvalPointerValueAsBool(RHSValue, bres))
1143          return false;
1144        return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1145      }
1146
1147      if (E->getOpcode() == BinaryOperator::Sub) {
1148        const QualType Type = E->getLHS()->getType();
1149        const QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
1150
1151        uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
1152        if (!ElementType->isVoidType() && !ElementType->isFunctionType())
1153          D /= Info.Ctx.getTypeSize(ElementType) / 8;
1154
1155        return Success(D, E);
1156      }
1157      bool Result;
1158      if (E->getOpcode() == BinaryOperator::EQ) {
1159        Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
1160      } else {
1161        Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1162      }
1163      return Success(Result, E);
1164    }
1165  }
1166  if (!LHSTy->isIntegralType() ||
1167      !RHSTy->isIntegralType()) {
1168    // We can't continue from here for non-integral types, and they
1169    // could potentially confuse the following operations.
1170    return false;
1171  }
1172
1173  // The LHS of a constant expr is always evaluated and needed.
1174  if (!Visit(E->getLHS()))
1175    return false; // error in subexpression.
1176
1177  APValue RHSVal;
1178  if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
1179    return false;
1180
1181  // Handle cases like (unsigned long)&a + 4.
1182  if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
1183    uint64_t offset = Result.getLValueOffset();
1184    if (E->getOpcode() == BinaryOperator::Add)
1185      offset += RHSVal.getInt().getZExtValue();
1186    else
1187      offset -= RHSVal.getInt().getZExtValue();
1188    Result = APValue(Result.getLValueBase(), offset);
1189    return true;
1190  }
1191
1192  // Handle cases like 4 + (unsigned long)&a
1193  if (E->getOpcode() == BinaryOperator::Add &&
1194        RHSVal.isLValue() && Result.isInt()) {
1195    uint64_t offset = RHSVal.getLValueOffset();
1196    offset += Result.getInt().getZExtValue();
1197    Result = APValue(RHSVal.getLValueBase(), offset);
1198    return true;
1199  }
1200
1201  // All the following cases expect both operands to be an integer
1202  if (!Result.isInt() || !RHSVal.isInt())
1203    return false;
1204
1205  APSInt& RHS = RHSVal.getInt();
1206
1207  switch (E->getOpcode()) {
1208  default:
1209    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1210  case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1211  case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1212  case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1213  case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1214  case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1215  case BinaryOperator::Or:  return Success(Result.getInt() | RHS, E);
1216  case BinaryOperator::Div:
1217    if (RHS == 0)
1218      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1219    return Success(Result.getInt() / RHS, E);
1220  case BinaryOperator::Rem:
1221    if (RHS == 0)
1222      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
1223    return Success(Result.getInt() % RHS, E);
1224  case BinaryOperator::Shl: {
1225    // FIXME: Warn about out of range shift amounts!
1226    unsigned SA =
1227      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1228    return Success(Result.getInt() << SA, E);
1229  }
1230  case BinaryOperator::Shr: {
1231    unsigned SA =
1232      (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1233    return Success(Result.getInt() >> SA, E);
1234  }
1235
1236  case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1237  case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1238  case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1239  case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1240  case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1241  case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
1242  }
1243}
1244
1245bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
1246  bool Cond;
1247  if (!HandleConversionToBool(E->getCond(), Cond, Info))
1248    return false;
1249
1250  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1251}
1252
1253unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
1254  // Get information about the alignment.
1255  unsigned CharSize = Info.Ctx.Target.getCharWidth();
1256
1257  // __alignof is defined to return the preferred alignment.
1258  return Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize;
1259}
1260
1261unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
1262  E = E->IgnoreParens();
1263
1264  // alignof decl is always accepted, even if it doesn't make sense: we default
1265  // to 1 in those cases.
1266  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1267    return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
1268
1269  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
1270    return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
1271
1272  return GetAlignOfType(E->getType());
1273}
1274
1275
1276/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1277/// expression's type.
1278bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1279  QualType DstTy = E->getType();
1280
1281  // Handle alignof separately.
1282  if (!E->isSizeOf()) {
1283    if (E->isArgumentType())
1284      return Success(GetAlignOfType(E->getArgumentType()), E);
1285    else
1286      return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
1287  }
1288
1289  QualType SrcTy = E->getTypeOfArgument();
1290
1291  // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1292  // extension.
1293  if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1294    return Success(1, E);
1295
1296  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1297  if (!SrcTy->isConstantSizeType())
1298    return false;
1299
1300  // Get information about the size.
1301  unsigned BitWidth = Info.Ctx.getTypeSize(SrcTy);
1302  return Success(BitWidth / Info.Ctx.Target.getCharWidth(), E);
1303}
1304
1305bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1306  // Special case unary operators that do not need their subexpression
1307  // evaluated.  offsetof/sizeof/alignof are all special.
1308  if (E->isOffsetOfOp()) {
1309    // The AST for offsetof is defined in such a way that we can just
1310    // directly Evaluate it as an l-value.
1311    APValue LV;
1312    if (!EvaluateLValue(E->getSubExpr(), LV, Info))
1313      return false;
1314    if (LV.getLValueBase())
1315      return false;
1316    return Success(LV.getLValueOffset(), E);
1317  }
1318
1319  if (E->getOpcode() == UnaryOperator::LNot) {
1320    // LNot's operand isn't necessarily an integer, so we handle it specially.
1321    bool bres;
1322    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1323      return false;
1324    return Success(!bres, E);
1325  }
1326
1327  // Only handle integral operations...
1328  if (!E->getSubExpr()->getType()->isIntegralType())
1329    return false;
1330
1331  // Get the operand value into 'Result'.
1332  if (!Visit(E->getSubExpr()))
1333    return false;
1334
1335  switch (E->getOpcode()) {
1336  default:
1337    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1338    // See C99 6.6p3.
1339    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1340  case UnaryOperator::Extension:
1341    // FIXME: Should extension allow i-c-e extension expressions in its scope?
1342    // If so, we could clear the diagnostic ID.
1343    return true;
1344  case UnaryOperator::Plus:
1345    // The result is always just the subexpr.
1346    return true;
1347  case UnaryOperator::Minus:
1348    if (!Result.isInt()) return false;
1349    return Success(-Result.getInt(), E);
1350  case UnaryOperator::Not:
1351    if (!Result.isInt()) return false;
1352    return Success(~Result.getInt(), E);
1353  }
1354}
1355
1356/// HandleCast - This is used to evaluate implicit or explicit casts where the
1357/// result type is integer.
1358bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
1359  Expr *SubExpr = E->getSubExpr();
1360  QualType DestType = E->getType();
1361  QualType SrcType = SubExpr->getType();
1362
1363  if (DestType->isBooleanType()) {
1364    bool BoolResult;
1365    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1366      return false;
1367    return Success(BoolResult, E);
1368  }
1369
1370  // Handle simple integer->integer casts.
1371  if (SrcType->isIntegralType()) {
1372    if (!Visit(SubExpr))
1373      return false;
1374
1375    if (!Result.isInt()) {
1376      // Only allow casts of lvalues if they are lossless.
1377      return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1378    }
1379
1380    return Success(HandleIntToIntCast(DestType, SrcType,
1381                                      Result.getInt(), Info.Ctx), E);
1382  }
1383
1384  // FIXME: Clean this up!
1385  if (SrcType->isPointerType()) {
1386    APValue LV;
1387    if (!EvaluatePointer(SubExpr, LV, Info))
1388      return false;
1389
1390    if (LV.getLValueBase()) {
1391      // Only allow based lvalue casts if they are lossless.
1392      if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1393        return false;
1394
1395      Result = LV;
1396      return true;
1397    }
1398
1399    APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset(), SrcType);
1400    return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
1401  }
1402
1403  if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1404    // This handles double-conversion cases, where there's both
1405    // an l-value promotion and an implicit conversion to int.
1406    APValue LV;
1407    if (!EvaluateLValue(SubExpr, LV, Info))
1408      return false;
1409
1410    if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1411      return false;
1412
1413    Result = LV;
1414    return true;
1415  }
1416
1417  if (SrcType->isAnyComplexType()) {
1418    APValue C;
1419    if (!EvaluateComplex(SubExpr, C, Info))
1420      return false;
1421    if (C.isComplexFloat())
1422      return Success(HandleFloatToIntCast(DestType, SrcType,
1423                                          C.getComplexFloatReal(), Info.Ctx),
1424                     E);
1425    else
1426      return Success(HandleIntToIntCast(DestType, SrcType,
1427                                        C.getComplexIntReal(), Info.Ctx), E);
1428  }
1429  // FIXME: Handle vectors
1430
1431  if (!SrcType->isRealFloatingType())
1432    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1433
1434  APFloat F(0.0);
1435  if (!EvaluateFloat(SubExpr, F, Info))
1436    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1437
1438  return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1439}
1440
1441bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1442  if (E->getSubExpr()->getType()->isAnyComplexType()) {
1443    APValue LV;
1444    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1445      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1446    return Success(LV.getComplexIntReal(), E);
1447  }
1448
1449  return Visit(E->getSubExpr());
1450}
1451
1452bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1453  if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1454    APValue LV;
1455    if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1456      return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1457    return Success(LV.getComplexIntImag(), E);
1458  }
1459
1460  if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1461    Info.EvalResult.HasSideEffects = true;
1462  return Success(0, E);
1463}
1464
1465//===----------------------------------------------------------------------===//
1466// Float Evaluation
1467//===----------------------------------------------------------------------===//
1468
1469namespace {
1470class VISIBILITY_HIDDEN FloatExprEvaluator
1471  : public StmtVisitor<FloatExprEvaluator, bool> {
1472  EvalInfo &Info;
1473  APFloat &Result;
1474public:
1475  FloatExprEvaluator(EvalInfo &info, APFloat &result)
1476    : Info(info), Result(result) {}
1477
1478  bool VisitStmt(Stmt *S) {
1479    return false;
1480  }
1481
1482  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1483  bool VisitCallExpr(const CallExpr *E);
1484
1485  bool VisitUnaryOperator(const UnaryOperator *E);
1486  bool VisitBinaryOperator(const BinaryOperator *E);
1487  bool VisitFloatingLiteral(const FloatingLiteral *E);
1488  bool VisitCastExpr(CastExpr *E);
1489  bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
1490
1491  bool VisitChooseExpr(const ChooseExpr *E)
1492    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1493  bool VisitUnaryExtension(const UnaryOperator *E)
1494    { return Visit(E->getSubExpr()); }
1495
1496  // FIXME: Missing: __real__/__imag__, array subscript of vector,
1497  //                 member of vector, ImplicitValueInitExpr,
1498  //                 conditional ?:, comma
1499};
1500} // end anonymous namespace
1501
1502static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1503  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1504}
1505
1506bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1507  switch (E->isBuiltinCall(Info.Ctx)) {
1508  default: return false;
1509  case Builtin::BI__builtin_huge_val:
1510  case Builtin::BI__builtin_huge_valf:
1511  case Builtin::BI__builtin_huge_vall:
1512  case Builtin::BI__builtin_inf:
1513  case Builtin::BI__builtin_inff:
1514  case Builtin::BI__builtin_infl: {
1515    const llvm::fltSemantics &Sem =
1516      Info.Ctx.getFloatTypeSemantics(E->getType());
1517    Result = llvm::APFloat::getInf(Sem);
1518    return true;
1519  }
1520
1521  case Builtin::BI__builtin_nan:
1522  case Builtin::BI__builtin_nanf:
1523  case Builtin::BI__builtin_nanl:
1524    // If this is __builtin_nan() turn this into a nan, otherwise we
1525    // can't constant fold it.
1526    if (const StringLiteral *S =
1527        dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1528      if (!S->isWide()) {
1529        const llvm::fltSemantics &Sem =
1530          Info.Ctx.getFloatTypeSemantics(E->getType());
1531        llvm::SmallString<16> s;
1532        s.append(S->getStrData(), S->getStrData() + S->getByteLength());
1533        s += '\0';
1534        long l;
1535        char *endp;
1536        l = strtol(&s[0], &endp, 0);
1537        if (endp != s.end()-1)
1538          return false;
1539        unsigned type = (unsigned int)l;;
1540        Result = llvm::APFloat::getNaN(Sem, false, type);
1541        return true;
1542      }
1543    }
1544    return false;
1545
1546  case Builtin::BI__builtin_fabs:
1547  case Builtin::BI__builtin_fabsf:
1548  case Builtin::BI__builtin_fabsl:
1549    if (!EvaluateFloat(E->getArg(0), Result, Info))
1550      return false;
1551
1552    if (Result.isNegative())
1553      Result.changeSign();
1554    return true;
1555
1556  case Builtin::BI__builtin_copysign:
1557  case Builtin::BI__builtin_copysignf:
1558  case Builtin::BI__builtin_copysignl: {
1559    APFloat RHS(0.);
1560    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1561        !EvaluateFloat(E->getArg(1), RHS, Info))
1562      return false;
1563    Result.copySign(RHS);
1564    return true;
1565  }
1566  }
1567}
1568
1569bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1570  if (E->getOpcode() == UnaryOperator::Deref)
1571    return false;
1572
1573  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1574    return false;
1575
1576  switch (E->getOpcode()) {
1577  default: return false;
1578  case UnaryOperator::Plus:
1579    return true;
1580  case UnaryOperator::Minus:
1581    Result.changeSign();
1582    return true;
1583  }
1584}
1585
1586bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1587  // FIXME: Diagnostics?  I really don't understand how the warnings
1588  // and errors are supposed to work.
1589  APFloat RHS(0.0);
1590  if (!EvaluateFloat(E->getLHS(), Result, Info))
1591    return false;
1592  if (!EvaluateFloat(E->getRHS(), RHS, Info))
1593    return false;
1594
1595  switch (E->getOpcode()) {
1596  default: return false;
1597  case BinaryOperator::Mul:
1598    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1599    return true;
1600  case BinaryOperator::Add:
1601    Result.add(RHS, APFloat::rmNearestTiesToEven);
1602    return true;
1603  case BinaryOperator::Sub:
1604    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1605    return true;
1606  case BinaryOperator::Div:
1607    Result.divide(RHS, APFloat::rmNearestTiesToEven);
1608    return true;
1609  }
1610}
1611
1612bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1613  Result = E->getValue();
1614  return true;
1615}
1616
1617bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1618  Expr* SubExpr = E->getSubExpr();
1619
1620  if (SubExpr->getType()->isIntegralType()) {
1621    APSInt IntResult;
1622    if (!EvaluateInteger(SubExpr, IntResult, Info))
1623      return false;
1624    Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1625                                  IntResult, Info.Ctx);
1626    return true;
1627  }
1628  if (SubExpr->getType()->isRealFloatingType()) {
1629    if (!Visit(SubExpr))
1630      return false;
1631    Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1632                                    Result, Info.Ctx);
1633    return true;
1634  }
1635  // FIXME: Handle complex types
1636
1637  return false;
1638}
1639
1640bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1641  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1642  return true;
1643}
1644
1645//===----------------------------------------------------------------------===//
1646// Complex Evaluation (for float and integer)
1647//===----------------------------------------------------------------------===//
1648
1649namespace {
1650class VISIBILITY_HIDDEN ComplexExprEvaluator
1651  : public StmtVisitor<ComplexExprEvaluator, APValue> {
1652  EvalInfo &Info;
1653
1654public:
1655  ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
1656
1657  //===--------------------------------------------------------------------===//
1658  //                            Visitor Methods
1659  //===--------------------------------------------------------------------===//
1660
1661  APValue VisitStmt(Stmt *S) {
1662    return APValue();
1663  }
1664
1665  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1666
1667  APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1668    Expr* SubExpr = E->getSubExpr();
1669
1670    if (SubExpr->getType()->isRealFloatingType()) {
1671      APFloat Result(0.0);
1672
1673      if (!EvaluateFloat(SubExpr, Result, Info))
1674        return APValue();
1675
1676      return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
1677                     Result);
1678    } else {
1679      assert(SubExpr->getType()->isIntegerType() &&
1680             "Unexpected imaginary literal.");
1681
1682      llvm::APSInt Result;
1683      if (!EvaluateInteger(SubExpr, Result, Info))
1684        return APValue();
1685
1686      llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1687      Zero = 0;
1688      return APValue(Zero, Result);
1689    }
1690  }
1691
1692  APValue VisitCastExpr(CastExpr *E) {
1693    Expr* SubExpr = E->getSubExpr();
1694    QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
1695    QualType SubType = SubExpr->getType();
1696
1697    if (SubType->isRealFloatingType()) {
1698      APFloat Result(0.0);
1699
1700      if (!EvaluateFloat(SubExpr, Result, Info))
1701        return APValue();
1702
1703      if (EltType->isRealFloatingType()) {
1704        Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
1705        return APValue(Result,
1706                       APFloat(Result.getSemantics(), APFloat::fcZero, false));
1707      } else {
1708        llvm::APSInt IResult;
1709        IResult = HandleFloatToIntCast(EltType, SubType, Result, Info.Ctx);
1710        llvm::APSInt Zero(IResult.getBitWidth(), !IResult.isSigned());
1711        Zero = 0;
1712        return APValue(IResult, Zero);
1713      }
1714    } else if (SubType->isIntegerType()) {
1715      APSInt Result;
1716
1717      if (!EvaluateInteger(SubExpr, Result, Info))
1718        return APValue();
1719
1720      if (EltType->isRealFloatingType()) {
1721        APFloat FResult =
1722            HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx);
1723        return APValue(FResult,
1724                       APFloat(FResult.getSemantics(), APFloat::fcZero, false));
1725      } else {
1726        Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
1727        llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1728        Zero = 0;
1729        return APValue(Result, Zero);
1730      }
1731    } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
1732      APValue Src;
1733
1734      if (!EvaluateComplex(SubExpr, Src, Info))
1735        return APValue();
1736
1737      QualType SrcType = CT->getElementType();
1738
1739      if (Src.isComplexFloat()) {
1740        if (EltType->isRealFloatingType()) {
1741          return APValue(HandleFloatToFloatCast(EltType, SrcType,
1742                                                Src.getComplexFloatReal(),
1743                                                Info.Ctx),
1744                         HandleFloatToFloatCast(EltType, SrcType,
1745                                                Src.getComplexFloatImag(),
1746                                                Info.Ctx));
1747        } else {
1748          return APValue(HandleFloatToIntCast(EltType, SrcType,
1749                                              Src.getComplexFloatReal(),
1750                                              Info.Ctx),
1751                         HandleFloatToIntCast(EltType, SrcType,
1752                                              Src.getComplexFloatImag(),
1753                                              Info.Ctx));
1754        }
1755      } else {
1756        assert(Src.isComplexInt() && "Invalid evaluate result.");
1757        if (EltType->isRealFloatingType()) {
1758          return APValue(HandleIntToFloatCast(EltType, SrcType,
1759                                              Src.getComplexIntReal(),
1760                                              Info.Ctx),
1761                         HandleIntToFloatCast(EltType, SrcType,
1762                                              Src.getComplexIntImag(),
1763                                              Info.Ctx));
1764        } else {
1765          return APValue(HandleIntToIntCast(EltType, SrcType,
1766                                            Src.getComplexIntReal(),
1767                                            Info.Ctx),
1768                         HandleIntToIntCast(EltType, SrcType,
1769                                            Src.getComplexIntImag(),
1770                                            Info.Ctx));
1771        }
1772      }
1773    }
1774
1775    // FIXME: Handle more casts.
1776    return APValue();
1777  }
1778
1779  APValue VisitBinaryOperator(const BinaryOperator *E);
1780  APValue VisitChooseExpr(const ChooseExpr *E)
1781    { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1782  APValue VisitUnaryExtension(const UnaryOperator *E)
1783    { return Visit(E->getSubExpr()); }
1784  // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
1785  //                conditional ?:, comma
1786};
1787} // end anonymous namespace
1788
1789static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) {
1790  Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1791  assert((!Result.isComplexFloat() ||
1792          (&Result.getComplexFloatReal().getSemantics() ==
1793           &Result.getComplexFloatImag().getSemantics())) &&
1794         "Invalid complex evaluation.");
1795  return Result.isComplexFloat() || Result.isComplexInt();
1796}
1797
1798APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1799  APValue Result, RHS;
1800
1801  if (!EvaluateComplex(E->getLHS(), Result, Info))
1802    return APValue();
1803
1804  if (!EvaluateComplex(E->getRHS(), RHS, Info))
1805    return APValue();
1806
1807  assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1808         "Invalid operands to binary operator.");
1809  switch (E->getOpcode()) {
1810  default: return APValue();
1811  case BinaryOperator::Add:
1812    if (Result.isComplexFloat()) {
1813      Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1814                                       APFloat::rmNearestTiesToEven);
1815      Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1816                                       APFloat::rmNearestTiesToEven);
1817    } else {
1818      Result.getComplexIntReal() += RHS.getComplexIntReal();
1819      Result.getComplexIntImag() += RHS.getComplexIntImag();
1820    }
1821    break;
1822  case BinaryOperator::Sub:
1823    if (Result.isComplexFloat()) {
1824      Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1825                                            APFloat::rmNearestTiesToEven);
1826      Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1827                                            APFloat::rmNearestTiesToEven);
1828    } else {
1829      Result.getComplexIntReal() -= RHS.getComplexIntReal();
1830      Result.getComplexIntImag() -= RHS.getComplexIntImag();
1831    }
1832    break;
1833  case BinaryOperator::Mul:
1834    if (Result.isComplexFloat()) {
1835      APValue LHS = Result;
1836      APFloat &LHS_r = LHS.getComplexFloatReal();
1837      APFloat &LHS_i = LHS.getComplexFloatImag();
1838      APFloat &RHS_r = RHS.getComplexFloatReal();
1839      APFloat &RHS_i = RHS.getComplexFloatImag();
1840
1841      APFloat Tmp = LHS_r;
1842      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1843      Result.getComplexFloatReal() = Tmp;
1844      Tmp = LHS_i;
1845      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1846      Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1847
1848      Tmp = LHS_r;
1849      Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1850      Result.getComplexFloatImag() = Tmp;
1851      Tmp = LHS_i;
1852      Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1853      Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1854    } else {
1855      APValue LHS = Result;
1856      Result.getComplexIntReal() =
1857        (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1858         LHS.getComplexIntImag() * RHS.getComplexIntImag());
1859      Result.getComplexIntImag() =
1860        (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1861         LHS.getComplexIntImag() * RHS.getComplexIntReal());
1862    }
1863    break;
1864  }
1865
1866  return Result;
1867}
1868
1869//===----------------------------------------------------------------------===//
1870// Top level Expr::Evaluate method.
1871//===----------------------------------------------------------------------===//
1872
1873/// Evaluate - Return true if this is a constant which we can fold using
1874/// any crazy technique (that has nothing to do with language standards) that
1875/// we want to.  If this function returns true, it returns the folded constant
1876/// in Result.
1877bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1878  EvalInfo Info(Ctx, Result);
1879
1880  if (getType()->isVectorType()) {
1881    if (!EvaluateVector(this, Result.Val, Info))
1882      return false;
1883  } else if (getType()->isIntegerType()) {
1884    if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
1885      return false;
1886  } else if (getType()->hasPointerRepresentation()) {
1887    if (!EvaluatePointer(this, Result.Val, Info))
1888      return false;
1889  } else if (getType()->isRealFloatingType()) {
1890    llvm::APFloat f(0.0);
1891    if (!EvaluateFloat(this, f, Info))
1892      return false;
1893
1894    Result.Val = APValue(f);
1895  } else if (getType()->isAnyComplexType()) {
1896    if (!EvaluateComplex(this, Result.Val, Info))
1897      return false;
1898  } else
1899    return false;
1900
1901  return true;
1902}
1903
1904bool Expr::EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const {
1905  EvalInfo Info(Ctx, Result, true);
1906
1907  if (getType()->isVectorType()) {
1908    if (!EvaluateVector(this, Result.Val, Info))
1909      return false;
1910  } else if (getType()->isIntegerType()) {
1911    if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
1912      return false;
1913  } else if (getType()->hasPointerRepresentation()) {
1914    if (!EvaluatePointer(this, Result.Val, Info))
1915      return false;
1916  } else if (getType()->isRealFloatingType()) {
1917    llvm::APFloat f(0.0);
1918    if (!EvaluateFloat(this, f, Info))
1919      return false;
1920
1921    Result.Val = APValue(f);
1922  } else if (getType()->isAnyComplexType()) {
1923    if (!EvaluateComplex(this, Result.Val, Info))
1924      return false;
1925  } else
1926    return false;
1927
1928  return true;
1929}
1930
1931bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
1932  EvalInfo Info(Ctx, Result);
1933
1934  return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
1935}
1936
1937bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
1938  EvalInfo Info(Ctx, Result, true);
1939
1940  return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
1941}
1942
1943/// isEvaluatable - Call Evaluate to see if this expression can be constant
1944/// folded, but discard the result.
1945bool Expr::isEvaluatable(ASTContext &Ctx) const {
1946  EvalResult Result;
1947  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
1948}
1949
1950APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1951  EvalResult EvalResult;
1952  bool Result = Evaluate(EvalResult, Ctx);
1953  Result = Result;
1954  assert(Result && "Could not evaluate expression");
1955  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
1956
1957  return EvalResult.Val.getInt();
1958}
1959