ExprConstant.cpp revision 67f4ac50cb22a1fffeb6ac8e7fe4f6dacdf2d317
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/Basic/Diagnostic.h"
19#include "clang/Basic/TargetInfo.h"
20#include "llvm/Support/Compiler.h"
21using namespace clang;
22using llvm::APSInt;
23using llvm::APFloat;
24
25/// EvalInfo - This is a private struct used by the evaluator to capture
26/// information about a subexpression as it is folded.  It retains information
27/// about the AST context, but also maintains information about the folded
28/// expression.
29///
30/// If an expression could be evaluated, it is still possible it is not a C
31/// "integer constant expression" or constant expression.  If not, this struct
32/// captures information about how and why not.
33///
34/// One bit of information passed *into* the request for constant folding
35/// indicates whether the subexpression is "evaluated" or not according to C
36/// rules.  For example, the RHS of (0 && foo()) is not evaluated.  We can
37/// evaluate the expression regardless of what the RHS is, but C only allows
38/// certain things in certain situations.
39struct EvalInfo {
40  ASTContext &Ctx;
41
42  /// EvalResult - Contains information about the evaluation.
43  Expr::EvalResult &EvalResult;
44
45  /// ShortCircuit - will be greater than zero if the current subexpression has
46  /// will not be evaluated because it's short-circuited (according to C rules).
47  unsigned ShortCircuit;
48
49  EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
50           EvalResult(evalresult), ShortCircuit(0) {}
51};
52
53
54static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
55static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
56static bool EvaluateInteger(const Expr *E, APSInt  &Result, EvalInfo &Info);
57static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
58static bool EvaluateComplexFloat(const Expr *E, APValue &Result,
59                                 EvalInfo &Info);
60
61//===----------------------------------------------------------------------===//
62// Misc utilities
63//===----------------------------------------------------------------------===//
64
65static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
66  if (E->getType()->isIntegralType()) {
67    APSInt IntResult;
68    if (!EvaluateInteger(E, IntResult, Info))
69      return false;
70    Result = IntResult != 0;
71    return true;
72  } else if (E->getType()->isRealFloatingType()) {
73    APFloat FloatResult(0.0);
74    if (!EvaluateFloat(E, FloatResult, Info))
75      return false;
76    Result = !FloatResult.isZero();
77    return true;
78  } else if (E->getType()->isPointerType()) {
79    APValue PointerResult;
80    if (!EvaluatePointer(E, PointerResult, Info))
81      return false;
82    // FIXME: Is this accurate for all kinds of bases?  If not, what would
83    // the check look like?
84    Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
85    return true;
86  }
87
88  return false;
89}
90
91//===----------------------------------------------------------------------===//
92// LValue Evaluation
93//===----------------------------------------------------------------------===//
94namespace {
95class VISIBILITY_HIDDEN LValueExprEvaluator
96  : public StmtVisitor<LValueExprEvaluator, APValue> {
97  EvalInfo &Info;
98public:
99
100  LValueExprEvaluator(EvalInfo &info) : Info(info) {}
101
102  APValue VisitStmt(Stmt *S) {
103#if 0
104    // FIXME: Remove this when we support more expressions.
105    printf("Unhandled pointer statement\n");
106    S->dump();
107#endif
108    return APValue();
109  }
110
111  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
112  APValue VisitDeclRefExpr(DeclRefExpr *E);
113  APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
114  APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
115  APValue VisitMemberExpr(MemberExpr *E);
116  APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
117  APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
118};
119} // end anonymous namespace
120
121static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
122  Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
123  return Result.isLValue();
124}
125
126APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
127{
128  if (!E->hasGlobalStorage())
129    return APValue();
130
131  return APValue(E, 0);
132}
133
134APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
135  if (E->isFileScope())
136    return APValue(E, 0);
137  return APValue();
138}
139
140APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
141  APValue result;
142  QualType Ty;
143  if (E->isArrow()) {
144    if (!EvaluatePointer(E->getBase(), result, Info))
145      return APValue();
146    Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
147  } else {
148    result = Visit(E->getBase());
149    if (result.isUninit())
150      return APValue();
151    Ty = E->getBase()->getType();
152  }
153
154  RecordDecl *RD = Ty->getAsRecordType()->getDecl();
155  const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
156
157  FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
158  if (!FD) // FIXME: deal with other kinds of member expressions
159    return APValue();
160
161  // FIXME: This is linear time.
162  unsigned i = 0;
163  for (RecordDecl::field_iterator Field = RD->field_begin(),
164                               FieldEnd = RD->field_end();
165       Field != FieldEnd; (void)++Field, ++i) {
166    if (*Field == FD)
167      break;
168  }
169
170  result.setLValue(result.getLValueBase(),
171                   result.getLValueOffset() + RL.getFieldOffset(i) / 8);
172
173  return result;
174}
175
176APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
177{
178  APValue Result;
179
180  if (!EvaluatePointer(E->getBase(), Result, Info))
181    return APValue();
182
183  APSInt Index;
184  if (!EvaluateInteger(E->getIdx(), Index, Info))
185    return APValue();
186
187  uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
188
189  uint64_t Offset = Index.getSExtValue() * ElementSize;
190  Result.setLValue(Result.getLValueBase(),
191                   Result.getLValueOffset() + Offset);
192  return Result;
193}
194
195//===----------------------------------------------------------------------===//
196// Pointer Evaluation
197//===----------------------------------------------------------------------===//
198
199namespace {
200class VISIBILITY_HIDDEN PointerExprEvaluator
201  : public StmtVisitor<PointerExprEvaluator, APValue> {
202  EvalInfo &Info;
203public:
204
205  PointerExprEvaluator(EvalInfo &info) : Info(info) {}
206
207  APValue VisitStmt(Stmt *S) {
208    return APValue();
209  }
210
211  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
212
213  APValue VisitBinaryOperator(const BinaryOperator *E);
214  APValue VisitCastExpr(const CastExpr* E);
215  APValue VisitUnaryOperator(const UnaryOperator *E);
216  APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
217      { return APValue(E, 0); }
218  APValue VisitAddrLabelExpr(AddrLabelExpr *E)
219      { return APValue(E, 0); }
220  APValue VisitCallExpr(CallExpr *E);
221  APValue VisitConditionalOperator(ConditionalOperator *E);
222};
223} // end anonymous namespace
224
225static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
226  if (!E->getType()->isPointerType())
227    return false;
228  Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
229  return Result.isLValue();
230}
231
232APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
233  if (E->getOpcode() != BinaryOperator::Add &&
234      E->getOpcode() != BinaryOperator::Sub)
235    return APValue();
236
237  const Expr *PExp = E->getLHS();
238  const Expr *IExp = E->getRHS();
239  if (IExp->getType()->isPointerType())
240    std::swap(PExp, IExp);
241
242  APValue ResultLValue;
243  if (!EvaluatePointer(PExp, ResultLValue, Info))
244    return APValue();
245
246  llvm::APSInt AdditionalOffset(32);
247  if (!EvaluateInteger(IExp, AdditionalOffset, Info))
248    return APValue();
249
250  QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
251  uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
252
253  uint64_t Offset = ResultLValue.getLValueOffset();
254
255  if (E->getOpcode() == BinaryOperator::Add)
256    Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
257  else
258    Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
259
260  return APValue(ResultLValue.getLValueBase(), Offset);
261}
262
263APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
264  if (E->getOpcode() == UnaryOperator::Extension) {
265    // FIXME: Deal with warnings?
266    return Visit(E->getSubExpr());
267  }
268
269  if (E->getOpcode() == UnaryOperator::AddrOf) {
270    APValue result;
271    if (EvaluateLValue(E->getSubExpr(), result, Info))
272      return result;
273  }
274
275  return APValue();
276}
277
278
279APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
280  const Expr* SubExpr = E->getSubExpr();
281
282   // Check for pointer->pointer cast
283  if (SubExpr->getType()->isPointerType()) {
284    APValue Result;
285    if (EvaluatePointer(SubExpr, Result, Info))
286      return Result;
287    return APValue();
288  }
289
290  if (SubExpr->getType()->isIntegralType()) {
291    llvm::APSInt Result(32);
292    if (EvaluateInteger(SubExpr, Result, Info)) {
293      Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
294      return APValue(0, Result.getZExtValue());
295    }
296  }
297
298  if (SubExpr->getType()->isFunctionType() ||
299      SubExpr->getType()->isArrayType()) {
300    APValue Result;
301    if (EvaluateLValue(SubExpr, Result, Info))
302      return Result;
303    return APValue();
304  }
305
306  //assert(0 && "Unhandled cast");
307  return APValue();
308}
309
310APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
311  if (E->isBuiltinCall() == Builtin::BI__builtin___CFStringMakeConstantString)
312    return APValue(E, 0);
313  return APValue();
314}
315
316APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
317  bool BoolResult;
318  if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
319    return APValue();
320
321  Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
322
323  APValue Result;
324  if (EvaluatePointer(EvalExpr, Result, Info))
325    return Result;
326  return APValue();
327}
328
329//===----------------------------------------------------------------------===//
330// Vector Evaluation
331//===----------------------------------------------------------------------===//
332
333namespace {
334  class VISIBILITY_HIDDEN VectorExprEvaluator
335  : public StmtVisitor<VectorExprEvaluator, APValue> {
336    EvalInfo &Info;
337  public:
338
339    VectorExprEvaluator(EvalInfo &info) : Info(info) {}
340
341    APValue VisitStmt(Stmt *S) {
342      return APValue();
343    }
344
345    APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
346    APValue VisitCastExpr(const CastExpr* E);
347    APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
348    APValue VisitInitListExpr(const InitListExpr *E);
349  };
350} // end anonymous namespace
351
352static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
353  if (!E->getType()->isVectorType())
354    return false;
355  Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
356  return !Result.isUninit();
357}
358
359APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
360  const Expr* SE = E->getSubExpr();
361
362  // Check for vector->vector bitcast.
363  if (SE->getType()->isVectorType())
364    return this->Visit(const_cast<Expr*>(SE));
365
366  return APValue();
367}
368
369APValue
370VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
371  return this->Visit(const_cast<Expr*>(E->getInitializer()));
372}
373
374APValue
375VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
376  const VectorType *VT = E->getType()->getAsVectorType();
377  unsigned NumInits = E->getNumInits();
378
379  if (!VT || VT->getNumElements() != NumInits)
380    return APValue();
381
382  QualType EltTy = VT->getElementType();
383  llvm::SmallVector<APValue, 4> Elements;
384
385  for (unsigned i = 0; i < NumInits; i++) {
386    if (EltTy->isIntegerType()) {
387      llvm::APSInt sInt(32);
388      if (!EvaluateInteger(E->getInit(i), sInt, Info))
389        return APValue();
390      Elements.push_back(APValue(sInt));
391    } else {
392      llvm::APFloat f(0.0);
393      if (!EvaluateFloat(E->getInit(i), f, Info))
394        return APValue();
395      Elements.push_back(APValue(f));
396    }
397  }
398  return APValue(&Elements[0], Elements.size());
399}
400
401//===----------------------------------------------------------------------===//
402// Integer Evaluation
403//===----------------------------------------------------------------------===//
404
405namespace {
406class VISIBILITY_HIDDEN IntExprEvaluator
407  : public StmtVisitor<IntExprEvaluator, bool> {
408  EvalInfo &Info;
409  APSInt &Result;
410public:
411  IntExprEvaluator(EvalInfo &info, APSInt &result)
412    : Info(info), Result(result) {}
413
414  unsigned getIntTypeSizeInBits(QualType T) const {
415    return (unsigned)Info.Ctx.getIntWidth(T);
416  }
417
418  bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
419    Info.EvalResult.DiagLoc = L;
420    Info.EvalResult.Diag = D;
421    Info.EvalResult.DiagExpr = E;
422    return true;  // still a constant.
423  }
424
425  bool Error(SourceLocation L, diag::kind D, const Expr *E) {
426    // If this is in an unevaluated portion of the subexpression, ignore the
427    // error.
428    if (Info.ShortCircuit) {
429      // If error is ignored because the value isn't evaluated, get the real
430      // type at least to prevent errors downstream.
431      Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
432      Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
433      return true;
434    }
435
436    // Take the first error.
437    if (Info.EvalResult.Diag == 0) {
438      Info.EvalResult.DiagLoc = L;
439      Info.EvalResult.Diag = D;
440      Info.EvalResult.DiagExpr = E;
441    }
442    return false;
443  }
444
445  //===--------------------------------------------------------------------===//
446  //                            Visitor Methods
447  //===--------------------------------------------------------------------===//
448
449  bool VisitStmt(Stmt *) {
450    assert(0 && "This should be called on integers, stmts are not integers");
451    return false;
452  }
453
454  bool VisitExpr(Expr *E) {
455    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
456  }
457
458  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
459
460  bool VisitIntegerLiteral(const IntegerLiteral *E) {
461    Result = E->getValue();
462    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
463    return true;
464  }
465  bool VisitCharacterLiteral(const CharacterLiteral *E) {
466    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
467    Result = E->getValue();
468    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
469    return true;
470  }
471  bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
472    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
473    // Per gcc docs "this built-in function ignores top level
474    // qualifiers".  We need to use the canonical version to properly
475    // be able to strip CRV qualifiers from the type.
476    QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
477    QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
478    Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
479                                         T1.getUnqualifiedType());
480    return true;
481  }
482  bool VisitDeclRefExpr(const DeclRefExpr *E);
483  bool VisitCallExpr(const CallExpr *E);
484  bool VisitBinaryOperator(const BinaryOperator *E);
485  bool VisitUnaryOperator(const UnaryOperator *E);
486  bool VisitConditionalOperator(const ConditionalOperator *E);
487
488  bool VisitCastExpr(CastExpr* E) {
489    return HandleCast(E);
490  }
491  bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
492
493  bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
494    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
495    Result = E->getValue();
496    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
497    return true;
498  }
499
500  bool VisitGNUNullExpr(const GNUNullExpr *E) {
501    Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
502    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
503    return true;
504  }
505
506  bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
507    Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
508    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
509    return true;
510  }
511
512  bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
513    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
514    Result = E->Evaluate();
515    return true;
516  }
517
518private:
519  bool HandleCast(CastExpr* E);
520  unsigned GetAlignOfExpr(const Expr *E);
521  unsigned GetAlignOfType(QualType T);
522};
523} // end anonymous namespace
524
525static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
526  return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
527}
528
529bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
530  // Enums are integer constant exprs.
531  if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
532    Result = D->getInitVal();
533    // FIXME: This is an ugly hack around the fact that enums don't set their
534    // signedness consistently; see PR3173
535    Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
536    return true;
537  }
538
539  // Otherwise, random variable references are not constants.
540  return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
541}
542
543/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
544/// as GCC.
545static int EvaluateBuiltinClassifyType(const CallExpr *E) {
546  // The following enum mimics the values returned by GCC.
547  enum gcc_type_class {
548    no_type_class = -1,
549    void_type_class, integer_type_class, char_type_class,
550    enumeral_type_class, boolean_type_class,
551    pointer_type_class, reference_type_class, offset_type_class,
552    real_type_class, complex_type_class,
553    function_type_class, method_type_class,
554    record_type_class, union_type_class,
555    array_type_class, string_type_class,
556    lang_type_class
557  };
558
559  // If no argument was supplied, default to "no_type_class". This isn't
560  // ideal, however it is what gcc does.
561  if (E->getNumArgs() == 0)
562    return no_type_class;
563
564  QualType ArgTy = E->getArg(0)->getType();
565  if (ArgTy->isVoidType())
566    return void_type_class;
567  else if (ArgTy->isEnumeralType())
568    return enumeral_type_class;
569  else if (ArgTy->isBooleanType())
570    return boolean_type_class;
571  else if (ArgTy->isCharType())
572    return string_type_class; // gcc doesn't appear to use char_type_class
573  else if (ArgTy->isIntegerType())
574    return integer_type_class;
575  else if (ArgTy->isPointerType())
576    return pointer_type_class;
577  else if (ArgTy->isReferenceType())
578    return reference_type_class;
579  else if (ArgTy->isRealType())
580    return real_type_class;
581  else if (ArgTy->isComplexType())
582    return complex_type_class;
583  else if (ArgTy->isFunctionType())
584    return function_type_class;
585  else if (ArgTy->isStructureType())
586    return record_type_class;
587  else if (ArgTy->isUnionType())
588    return union_type_class;
589  else if (ArgTy->isArrayType())
590    return array_type_class;
591  else if (ArgTy->isUnionType())
592    return union_type_class;
593  else  // FIXME: offset_type_class, method_type_class, & lang_type_class?
594    assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
595  return -1;
596}
597
598bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
599  Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
600
601  switch (E->isBuiltinCall()) {
602  default:
603    return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
604  case Builtin::BI__builtin_classify_type:
605    Result.setIsSigned(true);
606    Result = EvaluateBuiltinClassifyType(E);
607    return true;
608
609  case Builtin::BI__builtin_constant_p:
610    // __builtin_constant_p always has one operand: it returns true if that
611    // operand can be folded, false otherwise.
612    Result = E->getArg(0)->isEvaluatable(Info.Ctx);
613    return true;
614  }
615}
616
617bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
618  if (E->getOpcode() == BinaryOperator::Comma) {
619    if (!Visit(E->getRHS()))
620      return false;
621
622    if (!Info.ShortCircuit) {
623      // If we can't evaluate the LHS, it must be because it has
624      // side effects.
625      if (!E->getLHS()->isEvaluatable(Info.Ctx))
626        Info.EvalResult.HasSideEffects = true;
627
628      return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
629    }
630
631    return true;
632  }
633
634  if (E->isLogicalOp()) {
635    // These need to be handled specially because the operands aren't
636    // necessarily integral
637    bool lhsResult, rhsResult;
638
639    if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
640      // We were able to evaluate the LHS, see if we can get away with not
641      // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
642      if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
643          !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
644        Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
645        Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
646        Result = lhsResult;
647
648        Info.ShortCircuit++;
649        bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
650        Info.ShortCircuit--;
651
652        if (rhsEvaluated)
653          return true;
654
655        // FIXME: Return an extension warning saying that the RHS could not be
656        // evaluated.
657        return true;
658      }
659
660      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
661        Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
662        Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
663        if (E->getOpcode() == BinaryOperator::LOr)
664          Result = lhsResult || rhsResult;
665        else
666          Result = lhsResult && rhsResult;
667        return true;
668      }
669    } else {
670      if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
671        // We can't evaluate the LHS; however, sometimes the result
672        // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
673        if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
674            !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
675          Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
676          Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
677          Result = rhsResult;
678
679          // Since we werent able to evaluate the left hand side, it
680          // must have had side effects.
681          Info.EvalResult.HasSideEffects = true;
682
683          return true;
684        }
685      }
686    }
687
688    return false;
689  }
690
691  QualType LHSTy = E->getLHS()->getType();
692  QualType RHSTy = E->getRHS()->getType();
693
694  if (LHSTy->isRealFloatingType() &&
695      RHSTy->isRealFloatingType()) {
696    APFloat RHS(0.0), LHS(0.0);
697
698    if (!EvaluateFloat(E->getRHS(), RHS, Info))
699      return false;
700
701    if (!EvaluateFloat(E->getLHS(), LHS, Info))
702      return false;
703
704    APFloat::cmpResult CR = LHS.compare(RHS);
705
706    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
707
708    switch (E->getOpcode()) {
709    default:
710      assert(0 && "Invalid binary operator!");
711    case BinaryOperator::LT:
712      Result = CR == APFloat::cmpLessThan;
713      break;
714    case BinaryOperator::GT:
715      Result = CR == APFloat::cmpGreaterThan;
716      break;
717    case BinaryOperator::LE:
718      Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
719      break;
720    case BinaryOperator::GE:
721      Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
722      break;
723    case BinaryOperator::EQ:
724      Result = CR == APFloat::cmpEqual;
725      break;
726    case BinaryOperator::NE:
727      Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
728      break;
729    }
730
731    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
732    return true;
733  }
734
735  if (E->getOpcode() == BinaryOperator::Sub) {
736    if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
737      APValue LHSValue;
738      if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
739        return false;
740
741      APValue RHSValue;
742      if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
743        return false;
744
745      // FIXME: Is this correct? What if only one of the operands has a base?
746      if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
747        return false;
748
749      const QualType Type = E->getLHS()->getType();
750      const QualType ElementType = Type->getAsPointerType()->getPointeeType();
751
752      uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
753      D /= Info.Ctx.getTypeSize(ElementType) / 8;
754
755      Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
756      Result = D;
757      Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
758
759      return true;
760    }
761  }
762  if (!LHSTy->isIntegralType() ||
763      !RHSTy->isIntegralType()) {
764    // We can't continue from here for non-integral types, and they
765    // could potentially confuse the following operations.
766    // FIXME: Deal with EQ and friends.
767    return false;
768  }
769
770  // The LHS of a constant expr is always evaluated and needed.
771  llvm::APSInt RHS(32);
772  if (!Visit(E->getLHS())) {
773    return false; // error in subexpression.
774  }
775
776
777  // FIXME Maybe we want to succeed even where we can't evaluate the
778  // right side of LAnd/LOr?
779  // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
780  if (!EvaluateInteger(E->getRHS(), RHS, Info))
781    return false;
782
783  switch (E->getOpcode()) {
784  default:
785    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
786  case BinaryOperator::Mul: Result *= RHS; return true;
787  case BinaryOperator::Add: Result += RHS; return true;
788  case BinaryOperator::Sub: Result -= RHS; return true;
789  case BinaryOperator::And: Result &= RHS; return true;
790  case BinaryOperator::Xor: Result ^= RHS; return true;
791  case BinaryOperator::Or:  Result |= RHS; return true;
792  case BinaryOperator::Div:
793    if (RHS == 0)
794      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
795    Result /= RHS;
796    break;
797  case BinaryOperator::Rem:
798    if (RHS == 0)
799      return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
800    Result %= RHS;
801    break;
802  case BinaryOperator::Shl:
803    // FIXME: Warn about out of range shift amounts!
804    Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
805    break;
806  case BinaryOperator::Shr:
807    Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
808    break;
809
810  case BinaryOperator::LT:
811    Result = Result < RHS;
812    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
813    break;
814  case BinaryOperator::GT:
815    Result = Result > RHS;
816    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
817    break;
818  case BinaryOperator::LE:
819    Result = Result <= RHS;
820    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
821    break;
822  case BinaryOperator::GE:
823    Result = Result >= RHS;
824    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
825    break;
826  case BinaryOperator::EQ:
827    Result = Result == RHS;
828    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
829    break;
830  case BinaryOperator::NE:
831    Result = Result != RHS;
832    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
833    break;
834  case BinaryOperator::LAnd:
835    Result = Result != 0 && RHS != 0;
836    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
837    break;
838  case BinaryOperator::LOr:
839    Result = Result != 0 || RHS != 0;
840    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
841    break;
842  }
843
844  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
845  return true;
846}
847
848bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
849  bool Cond;
850  if (!HandleConversionToBool(E->getCond(), Cond, Info))
851    return false;
852
853  return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
854}
855
856unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
857  const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
858
859  // __alignof__(void) = 1 as a gcc extension.
860  if (Ty->isVoidType())
861    return 1;
862
863  // GCC extension: alignof(function) = 4.
864  // FIXME: AlignOf shouldn't be unconditionally 4!  It should listen to the
865  // attribute(align) directive.
866  if (Ty->isFunctionType())
867    return 4;
868
869  if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty))
870    return GetAlignOfType(QualType(ASQT->getBaseType(), 0));
871
872  // alignof VLA/incomplete array.
873  if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
874    return GetAlignOfType(VAT->getElementType());
875
876  // sizeof (objc class)?
877  if (isa<ObjCInterfaceType>(Ty))
878    return 1;  // FIXME: This probably isn't right.
879
880  // Get information about the alignment.
881  unsigned CharSize = Info.Ctx.Target.getCharWidth();
882  return Info.Ctx.getTypeAlign(Ty) / CharSize;
883}
884
885unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
886  E = E->IgnoreParens();
887
888  // alignof decl is always accepted, even if it doesn't make sense: we default
889  // to 1 in those cases.
890  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
891    return Info.Ctx.getDeclAlign(DRE->getDecl());
892
893  if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
894    return Info.Ctx.getDeclAlign(ME->getMemberDecl());
895
896  return GetAlignOfType(E->getType());
897}
898
899
900/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
901/// expression's type.
902bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
903  QualType DstTy = E->getType();
904  // Return the result in the right width.
905  Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
906  Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
907
908  // Handle alignof separately.
909  if (!E->isSizeOf()) {
910    if (E->isArgumentType())
911      Result = GetAlignOfType(E->getArgumentType());
912    else
913      Result = GetAlignOfExpr(E->getArgumentExpr());
914    return true;
915  }
916
917  QualType SrcTy = E->getTypeOfArgument();
918
919  // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
920  if (SrcTy->isVoidType()) {
921    Result = 1;
922    return true;
923  }
924
925  // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
926  if (!SrcTy->isConstantSizeType())
927    return false;
928
929  // GCC extension: sizeof(function) = 1.
930  if (SrcTy->isFunctionType()) {
931    Result = 1;
932    return true;
933  }
934
935  if (SrcTy->isObjCInterfaceType()) {
936    // Slightly unusual case: the size of an ObjC interface type is the
937    // size of the class.  This code intentionally falls through to the normal
938    // case.
939    ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
940    RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
941    SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
942  }
943
944  // Get information about the size.
945  unsigned CharSize = Info.Ctx.Target.getCharWidth();
946  Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
947  return true;
948}
949
950bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
951  // Special case unary operators that do not need their subexpression
952  // evaluated.  offsetof/sizeof/alignof are all special.
953  if (E->isOffsetOfOp()) {
954    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
955    Result = E->evaluateOffsetOf(Info.Ctx);
956    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
957    return true;
958  }
959
960  if (E->getOpcode() == UnaryOperator::LNot) {
961    // LNot's operand isn't necessarily an integer, so we handle it specially.
962    bool bres;
963    if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
964      return false;
965    Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
966    Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
967    Result = !bres;
968    return true;
969  }
970
971  // Get the operand value into 'Result'.
972  if (!Visit(E->getSubExpr()))
973    return false;
974
975  switch (E->getOpcode()) {
976  default:
977    // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
978    // See C99 6.6p3.
979    return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
980  case UnaryOperator::Extension:
981    // FIXME: Should extension allow i-c-e extension expressions in its scope?
982    // If so, we could clear the diagnostic ID.
983  case UnaryOperator::Plus:
984    // The result is always just the subexpr.
985    break;
986  case UnaryOperator::Minus:
987    Result = -Result;
988    break;
989  case UnaryOperator::Not:
990    Result = ~Result;
991    break;
992  }
993
994  Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
995  return true;
996}
997
998/// HandleCast - This is used to evaluate implicit or explicit casts where the
999/// result type is integer.
1000bool IntExprEvaluator::HandleCast(CastExpr *E) {
1001  Expr *SubExpr = E->getSubExpr();
1002  QualType DestType = E->getType();
1003
1004  unsigned DestWidth = getIntTypeSizeInBits(DestType);
1005
1006  if (DestType->isBooleanType()) {
1007    bool BoolResult;
1008    if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1009      return false;
1010    Result.zextOrTrunc(DestWidth);
1011    Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1012    Result = BoolResult;
1013    return true;
1014  }
1015
1016  // Handle simple integer->integer casts.
1017  if (SubExpr->getType()->isIntegralType()) {
1018    if (!Visit(SubExpr))
1019      return false;
1020
1021    // Figure out if this is a truncate, extend or noop cast.
1022    // If the input is signed, do a sign extend, noop, or truncate.
1023    Result.extOrTrunc(DestWidth);
1024    Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1025    return true;
1026  }
1027
1028  // FIXME: Clean this up!
1029  if (SubExpr->getType()->isPointerType()) {
1030    APValue LV;
1031    if (!EvaluatePointer(SubExpr, LV, Info))
1032      return false;
1033
1034    if (LV.getLValueBase())
1035      return false;
1036
1037    Result.extOrTrunc(DestWidth);
1038    Result = LV.getLValueOffset();
1039    Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1040    return true;
1041  }
1042
1043  if (!SubExpr->getType()->isRealFloatingType())
1044    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1045
1046  APFloat F(0.0);
1047  if (!EvaluateFloat(SubExpr, F, Info))
1048    return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1049
1050  // Determine whether we are converting to unsigned or signed.
1051  bool DestSigned = DestType->isSignedIntegerType();
1052
1053  // FIXME: Warning for overflow.
1054  uint64_t Space[4];
1055  bool ignored;
1056  (void)F.convertToInteger(Space, DestWidth, DestSigned,
1057                           llvm::APFloat::rmTowardZero, &ignored);
1058  Result = llvm::APInt(DestWidth, 4, Space);
1059  Result.setIsUnsigned(!DestSigned);
1060  return true;
1061}
1062
1063//===----------------------------------------------------------------------===//
1064// Float Evaluation
1065//===----------------------------------------------------------------------===//
1066
1067namespace {
1068class VISIBILITY_HIDDEN FloatExprEvaluator
1069  : public StmtVisitor<FloatExprEvaluator, bool> {
1070  EvalInfo &Info;
1071  APFloat &Result;
1072public:
1073  FloatExprEvaluator(EvalInfo &info, APFloat &result)
1074    : Info(info), Result(result) {}
1075
1076  bool VisitStmt(Stmt *S) {
1077    return false;
1078  }
1079
1080  bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1081  bool VisitCallExpr(const CallExpr *E);
1082
1083  bool VisitUnaryOperator(const UnaryOperator *E);
1084  bool VisitBinaryOperator(const BinaryOperator *E);
1085  bool VisitFloatingLiteral(const FloatingLiteral *E);
1086  bool VisitCastExpr(CastExpr *E);
1087  bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
1088};
1089} // end anonymous namespace
1090
1091static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1092  return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1093}
1094
1095bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
1096  switch (E->isBuiltinCall()) {
1097  default: return false;
1098  case Builtin::BI__builtin_huge_val:
1099  case Builtin::BI__builtin_huge_valf:
1100  case Builtin::BI__builtin_huge_vall:
1101  case Builtin::BI__builtin_inf:
1102  case Builtin::BI__builtin_inff:
1103  case Builtin::BI__builtin_infl: {
1104    const llvm::fltSemantics &Sem =
1105      Info.Ctx.getFloatTypeSemantics(E->getType());
1106    Result = llvm::APFloat::getInf(Sem);
1107    return true;
1108  }
1109
1110  case Builtin::BI__builtin_nan:
1111  case Builtin::BI__builtin_nanf:
1112  case Builtin::BI__builtin_nanl:
1113    // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1114    // can't constant fold it.
1115    if (const StringLiteral *S =
1116        dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1117      if (!S->isWide() && S->getByteLength() == 0) { // empty string.
1118        const llvm::fltSemantics &Sem =
1119          Info.Ctx.getFloatTypeSemantics(E->getType());
1120        Result = llvm::APFloat::getNaN(Sem);
1121        return true;
1122      }
1123    }
1124    return false;
1125
1126  case Builtin::BI__builtin_fabs:
1127  case Builtin::BI__builtin_fabsf:
1128  case Builtin::BI__builtin_fabsl:
1129    if (!EvaluateFloat(E->getArg(0), Result, Info))
1130      return false;
1131
1132    if (Result.isNegative())
1133      Result.changeSign();
1134    return true;
1135
1136  case Builtin::BI__builtin_copysign:
1137  case Builtin::BI__builtin_copysignf:
1138  case Builtin::BI__builtin_copysignl: {
1139    APFloat RHS(0.);
1140    if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1141        !EvaluateFloat(E->getArg(1), RHS, Info))
1142      return false;
1143    Result.copySign(RHS);
1144    return true;
1145  }
1146  }
1147}
1148
1149bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
1150  if (E->getOpcode() == UnaryOperator::Deref)
1151    return false;
1152
1153  if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1154    return false;
1155
1156  switch (E->getOpcode()) {
1157  default: return false;
1158  case UnaryOperator::Plus:
1159    return true;
1160  case UnaryOperator::Minus:
1161    Result.changeSign();
1162    return true;
1163  }
1164}
1165
1166bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1167  // FIXME: Diagnostics?  I really don't understand how the warnings
1168  // and errors are supposed to work.
1169  APFloat RHS(0.0);
1170  if (!EvaluateFloat(E->getLHS(), Result, Info))
1171    return false;
1172  if (!EvaluateFloat(E->getRHS(), RHS, Info))
1173    return false;
1174
1175  switch (E->getOpcode()) {
1176  default: return false;
1177  case BinaryOperator::Mul:
1178    Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1179    return true;
1180  case BinaryOperator::Add:
1181    Result.add(RHS, APFloat::rmNearestTiesToEven);
1182    return true;
1183  case BinaryOperator::Sub:
1184    Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1185    return true;
1186  case BinaryOperator::Div:
1187    Result.divide(RHS, APFloat::rmNearestTiesToEven);
1188    return true;
1189  case BinaryOperator::Rem:
1190    Result.mod(RHS, APFloat::rmNearestTiesToEven);
1191    return true;
1192  }
1193}
1194
1195bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1196  Result = E->getValue();
1197  return true;
1198}
1199
1200bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1201  Expr* SubExpr = E->getSubExpr();
1202
1203  const llvm::fltSemantics& destSemantics =
1204      Info.Ctx.getFloatTypeSemantics(E->getType());
1205  if (SubExpr->getType()->isIntegralType()) {
1206    APSInt IntResult;
1207    if (!EvaluateInteger(E, IntResult, Info))
1208      return false;
1209    Result = APFloat(destSemantics, 1);
1210    Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1211                            APFloat::rmNearestTiesToEven);
1212    return true;
1213  }
1214  if (SubExpr->getType()->isRealFloatingType()) {
1215    if (!Visit(SubExpr))
1216      return false;
1217    bool ignored;
1218    Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1219    return true;
1220  }
1221
1222  return false;
1223}
1224
1225bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1226  Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1227  return true;
1228}
1229
1230//===----------------------------------------------------------------------===//
1231// Complex Float Evaluation
1232//===----------------------------------------------------------------------===//
1233
1234namespace {
1235class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1236  : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1237  EvalInfo &Info;
1238
1239public:
1240  ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1241
1242  //===--------------------------------------------------------------------===//
1243  //                            Visitor Methods
1244  //===--------------------------------------------------------------------===//
1245
1246  APValue VisitStmt(Stmt *S) {
1247    return APValue();
1248  }
1249
1250  APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1251
1252  APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1253    APFloat Result(0.0);
1254    if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1255      return APValue();
1256
1257    return APValue(APFloat(Result.getSemantics(), APFloat::fcZero),
1258                   Result);
1259  }
1260
1261  APValue VisitCastExpr(CastExpr *E) {
1262    Expr* SubExpr = E->getSubExpr();
1263
1264    if (SubExpr->getType()->isRealFloatingType()) {
1265      APFloat Result(0.0);
1266
1267      if (!EvaluateFloat(SubExpr, Result, Info))
1268        return APValue();
1269
1270      return APValue(Result,
1271                     APFloat(Result.getSemantics(), APFloat::fcZero));
1272    }
1273
1274    // FIXME: Handle more casts.
1275    return APValue();
1276  }
1277
1278  APValue VisitBinaryOperator(const BinaryOperator *E);
1279
1280};
1281} // end anonymous namespace
1282
1283static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1284{
1285  Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1286  if (Result.isComplexFloat())
1287    assert(&Result.getComplexFloatReal().getSemantics() ==
1288           &Result.getComplexFloatImag().getSemantics() &&
1289           "Invalid complex evaluation.");
1290  return Result.isComplexFloat();
1291}
1292
1293APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1294{
1295  APValue Result, RHS;
1296
1297  if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1298    return APValue();
1299
1300  if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1301    return APValue();
1302
1303  switch (E->getOpcode()) {
1304  default: return APValue();
1305  case BinaryOperator::Add:
1306    Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1307                                     APFloat::rmNearestTiesToEven);
1308    Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1309                                     APFloat::rmNearestTiesToEven);
1310  case BinaryOperator::Sub:
1311    Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1312                                          APFloat::rmNearestTiesToEven);
1313    Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1314                                          APFloat::rmNearestTiesToEven);
1315  }
1316
1317  return Result;
1318}
1319
1320//===----------------------------------------------------------------------===//
1321// Top level Expr::Evaluate method.
1322//===----------------------------------------------------------------------===//
1323
1324/// Evaluate - Return true if this is a constant which we can fold using
1325/// any crazy technique (that has nothing to do with language standards) that
1326/// we want to.  If this function returns true, it returns the folded constant
1327/// in Result.
1328bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1329  EvalInfo Info(Ctx, Result);
1330
1331  if (getType()->isVectorType()) {
1332    if (!EvaluateVector(this, Result.Val, Info))
1333      return false;
1334  } else if (getType()->isIntegerType()) {
1335    llvm::APSInt sInt(32);
1336    if (!EvaluateInteger(this, sInt, Info))
1337      return false;
1338
1339    Result.Val = APValue(sInt);
1340  } else if (getType()->isPointerType()) {
1341    if (!EvaluatePointer(this, Result.Val, Info))
1342      return false;
1343  } else if (getType()->isRealFloatingType()) {
1344    llvm::APFloat f(0.0);
1345    if (!EvaluateFloat(this, f, Info))
1346      return false;
1347
1348    Result.Val = APValue(f);
1349  } else if (getType()->isComplexType()) {
1350    if (!EvaluateComplexFloat(this, Result.Val, Info))
1351      return false;
1352  }  else
1353    return false;
1354
1355  return true;
1356}
1357
1358/// isEvaluatable - Call Evaluate to see if this expression can be constant
1359/// folded, but discard the result.
1360bool Expr::isEvaluatable(ASTContext &Ctx) const {
1361  EvalResult Result;
1362  return Evaluate(Result, Ctx) && !Result.HasSideEffects;
1363}
1364
1365APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1366  EvalResult EvalResult;
1367  bool Result = Evaluate(EvalResult, Ctx);
1368  Result = Result;
1369  assert(Result && "Could not evaluate expression");
1370  assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
1371
1372  return EvalResult.Val.getInt();
1373}
1374