blob: 8f43700e46d1df896ac239dd5b50de0392e4ce24 [file] [log] [blame]
Chris Lattnera42f09a2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc7436af2008-07-03 04:20:39 +00002//
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"
Eli Friedman7888b932008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeonefddb9c2008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner545f39e2009-01-29 05:15:15 +000018#include "clang/AST/ASTDiagnostic.h"
Anders Carlssonc0328012008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssoncad17b52008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnera823ccf2008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedman2f445492008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc7436af2008-07-03 04:20:39 +000024
Chris Lattner422373c2008-07-11 22:52:41 +000025/// 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
Anders Carlssondd8d41f2008-11-30 16:38:33 +000042 /// EvalResult - Contains information about the evaluation.
43 Expr::EvalResult &EvalResult;
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000044
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;
Chris Lattner422373c2008-07-11 22:52:41 +000048
Anders Carlssondd8d41f2008-11-30 16:38:33 +000049 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000050 EvalResult(evalresult), ShortCircuit(0) {}
Chris Lattner422373c2008-07-11 22:52:41 +000051};
52
53
Eli Friedman7888b932008-11-12 09:44:48 +000054static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner422373c2008-07-11 22:52:41 +000055static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
56static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Daniel Dunbar56611002009-02-20 18:22:23 +000057static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Eli Friedman2f445492008-08-22 00:06:13 +000058static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +000059static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000060
61//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000062// 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
Daniel Dunbaraffa0e32009-01-29 06:16:07 +000091static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
92 APFloat &Value, ASTContext &Ctx) {
93 unsigned DestWidth = Ctx.getIntWidth(DestType);
94 // Determine whether we are converting to unsigned or signed.
95 bool DestSigned = DestType->isSignedIntegerType();
96
97 // FIXME: Warning for overflow.
98 uint64_t Space[4];
99 bool ignored;
100 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
101 llvm::APFloat::rmTowardZero, &ignored);
102 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
103}
104
105static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
106 APFloat &Value, ASTContext &Ctx) {
107 bool ignored;
108 APFloat Result = Value;
109 Result.convert(Ctx.getFloatTypeSemantics(DestType),
110 APFloat::rmNearestTiesToEven, &ignored);
111 return Result;
112}
113
114static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
115 APSInt &Value, ASTContext &Ctx) {
116 unsigned DestWidth = Ctx.getIntWidth(DestType);
117 APSInt Result = Value;
118 // Figure out if this is a truncate, extend or noop cast.
119 // If the input is signed, do a sign extend, noop, or truncate.
120 Result.extOrTrunc(DestWidth);
121 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
122 return Result;
123}
124
125static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
126 APSInt &Value, ASTContext &Ctx) {
127
128 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
129 Result.convertFromAPInt(Value, Value.isSigned(),
130 APFloat::rmNearestTiesToEven);
131 return Result;
132}
133
Eli Friedman7888b932008-11-12 09:44:48 +0000134//===----------------------------------------------------------------------===//
135// LValue Evaluation
136//===----------------------------------------------------------------------===//
137namespace {
138class VISIBILITY_HIDDEN LValueExprEvaluator
139 : public StmtVisitor<LValueExprEvaluator, APValue> {
140 EvalInfo &Info;
141public:
142
143 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
144
145 APValue VisitStmt(Stmt *S) {
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000146#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000147 // FIXME: Remove this when we support more expressions.
148 printf("Unhandled pointer statement\n");
149 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000150#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000151 return APValue();
152 }
153
154 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssone284ebe2008-11-24 04:41:22 +0000155 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000156 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
157 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
158 APValue VisitMemberExpr(MemberExpr *E);
159 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson027f2882008-11-16 19:01:22 +0000160 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmandbd0a9b2009-02-20 01:57:15 +0000161 APValue VisitUnaryDeref(UnaryOperator *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000162};
163} // end anonymous namespace
164
165static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
166 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
167 return Result.isLValue();
168}
169
Anders Carlssone284ebe2008-11-24 04:41:22 +0000170APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
171{
172 if (!E->hasGlobalStorage())
173 return APValue();
174
175 return APValue(E, 0);
176}
177
Eli Friedman7888b932008-11-12 09:44:48 +0000178APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
179 if (E->isFileScope())
180 return APValue(E, 0);
181 return APValue();
182}
183
184APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
185 APValue result;
186 QualType Ty;
187 if (E->isArrow()) {
188 if (!EvaluatePointer(E->getBase(), result, Info))
189 return APValue();
190 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
191 } else {
192 result = Visit(E->getBase());
193 if (result.isUninit())
194 return APValue();
195 Ty = E->getBase()->getType();
196 }
197
198 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
199 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor82d44772008-12-20 23:49:58 +0000200
201 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
202 if (!FD) // FIXME: deal with other kinds of member expressions
203 return APValue();
Eli Friedman7888b932008-11-12 09:44:48 +0000204
205 // FIXME: This is linear time.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000206 unsigned i = 0;
207 for (RecordDecl::field_iterator Field = RD->field_begin(),
208 FieldEnd = RD->field_end();
209 Field != FieldEnd; (void)++Field, ++i) {
210 if (*Field == FD)
Eli Friedman7888b932008-11-12 09:44:48 +0000211 break;
212 }
213
214 result.setLValue(result.getLValueBase(),
215 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
216
217 return result;
218}
219
Anders Carlsson027f2882008-11-16 19:01:22 +0000220APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
221{
222 APValue Result;
223
224 if (!EvaluatePointer(E->getBase(), Result, Info))
225 return APValue();
226
227 APSInt Index;
228 if (!EvaluateInteger(E->getIdx(), Index, Info))
229 return APValue();
230
231 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
232
233 uint64_t Offset = Index.getSExtValue() * ElementSize;
234 Result.setLValue(Result.getLValueBase(),
235 Result.getLValueOffset() + Offset);
236 return Result;
237}
Eli Friedman7888b932008-11-12 09:44:48 +0000238
Eli Friedmandbd0a9b2009-02-20 01:57:15 +0000239APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E)
240{
241 APValue Result;
242 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
243 return APValue();
244 return Result;
245}
246
Eli Friedman7888b932008-11-12 09:44:48 +0000247//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000248// Pointer Evaluation
249//===----------------------------------------------------------------------===//
250
Anders Carlssoncad17b52008-07-08 05:13:58 +0000251namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000252class VISIBILITY_HIDDEN PointerExprEvaluator
253 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000254 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000255public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000256
Chris Lattner422373c2008-07-11 22:52:41 +0000257 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000258
Anders Carlsson02a34c32008-07-08 14:30:00 +0000259 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000260 return APValue();
261 }
262
263 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
264
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000265 APValue VisitBinaryOperator(const BinaryOperator *E);
266 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000267 APValue VisitUnaryOperator(const UnaryOperator *E);
268 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
269 { return APValue(E, 0); }
Eli Friedmanf1941132009-01-25 01:21:06 +0000270 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
271 { return APValue(E, 0); }
Eli Friedman67f4ac52009-01-25 01:54:01 +0000272 APValue VisitCallExpr(CallExpr *E);
Mike Stumpae93d652009-02-19 22:01:56 +0000273 APValue VisitBlockExpr(BlockExpr *E) {
274 if (!E->hasBlockDeclRefExprs())
275 return APValue(E, 0);
276 return APValue();
277 }
Eli Friedman7888b932008-11-12 09:44:48 +0000278 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000279};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000280} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000281
Eli Friedman2f6d70d2009-02-22 04:02:33 +0000282static bool HasPointerEvalType(const Expr* E) {
283 return E->getType()->isPointerType()
284 || E->getType()->isBlockPointerType()
285 || E->getType()->isObjCQualifiedIdType()
286 || E->getType()->isObjCQualifiedClassType();
287}
288
Chris Lattner422373c2008-07-11 22:52:41 +0000289static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Eli Friedman2f6d70d2009-02-22 04:02:33 +0000290 if (!HasPointerEvalType(E))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000291 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000292 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000293 return Result.isLValue();
294}
295
296APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
297 if (E->getOpcode() != BinaryOperator::Add &&
298 E->getOpcode() != BinaryOperator::Sub)
299 return APValue();
300
301 const Expr *PExp = E->getLHS();
302 const Expr *IExp = E->getRHS();
303 if (IExp->getType()->isPointerType())
304 std::swap(PExp, IExp);
305
306 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000307 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000308 return APValue();
309
310 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000311 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000312 return APValue();
313
Eli Friedman7888b932008-11-12 09:44:48 +0000314 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
Anders Carlsson4fbb52c2009-02-19 04:55:58 +0000315 uint64_t SizeOfPointee;
316
317 // Explicitly handle GNU void* and function pointer arithmetic extensions.
318 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
319 SizeOfPointee = 1;
320 else
321 SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
Eli Friedman7888b932008-11-12 09:44:48 +0000322
Chris Lattnera823ccf2008-07-11 18:11:29 +0000323 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000324
Chris Lattnera823ccf2008-07-11 18:11:29 +0000325 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000326 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000327 else
Eli Friedman7888b932008-11-12 09:44:48 +0000328 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
329
Chris Lattnera823ccf2008-07-11 18:11:29 +0000330 return APValue(ResultLValue.getLValueBase(), Offset);
331}
Eli Friedman7888b932008-11-12 09:44:48 +0000332
333APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
334 if (E->getOpcode() == UnaryOperator::Extension) {
335 // FIXME: Deal with warnings?
336 return Visit(E->getSubExpr());
337 }
338
339 if (E->getOpcode() == UnaryOperator::AddrOf) {
340 APValue result;
341 if (EvaluateLValue(E->getSubExpr(), result, Info))
342 return result;
343 }
344
345 return APValue();
346}
Anders Carlsson4ab88da2008-12-05 05:24:13 +0000347
Chris Lattnera823ccf2008-07-11 18:11:29 +0000348
Chris Lattnera42f09a2008-07-11 19:10:17 +0000349APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000350 const Expr* SubExpr = E->getSubExpr();
351
352 // Check for pointer->pointer cast
353 if (SubExpr->getType()->isPointerType()) {
354 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000355 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000356 return Result;
357 return APValue();
358 }
359
Eli Friedman3e64dd72008-07-27 05:46:18 +0000360 if (SubExpr->getType()->isIntegralType()) {
Daniel Dunbar56611002009-02-20 18:22:23 +0000361 APValue Result;
362 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
363 return APValue();
364
365 if (Result.isInt()) {
366 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
367 return APValue(0, Result.getInt().getZExtValue());
Chris Lattnera823ccf2008-07-11 18:11:29 +0000368 }
Daniel Dunbar56611002009-02-20 18:22:23 +0000369
370 // Cast is of an lvalue, no need to change value.
371 return Result;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000372 }
Eli Friedman7888b932008-11-12 09:44:48 +0000373
374 if (SubExpr->getType()->isFunctionType() ||
375 SubExpr->getType()->isArrayType()) {
376 APValue Result;
377 if (EvaluateLValue(SubExpr, Result, Info))
378 return Result;
379 return APValue();
380 }
381
382 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000383 return APValue();
384}
385
Eli Friedman67f4ac52009-01-25 01:54:01 +0000386APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000387 if (E->isBuiltinCall(Info.Ctx) ==
388 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman67f4ac52009-01-25 01:54:01 +0000389 return APValue(E, 0);
390 return APValue();
391}
392
Eli Friedman7888b932008-11-12 09:44:48 +0000393APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
394 bool BoolResult;
395 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
396 return APValue();
397
398 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
399
400 APValue Result;
401 if (EvaluatePointer(EvalExpr, Result, Info))
402 return Result;
403 return APValue();
404}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000405
406//===----------------------------------------------------------------------===//
Nate Begemand6d2f772009-01-18 03:20:47 +0000407// Vector Evaluation
408//===----------------------------------------------------------------------===//
409
410namespace {
411 class VISIBILITY_HIDDEN VectorExprEvaluator
412 : public StmtVisitor<VectorExprEvaluator, APValue> {
413 EvalInfo &Info;
414 public:
415
416 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
417
418 APValue VisitStmt(Stmt *S) {
419 return APValue();
420 }
421
422 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
423 APValue VisitCastExpr(const CastExpr* E);
424 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
425 APValue VisitInitListExpr(const InitListExpr *E);
426 };
427} // end anonymous namespace
428
429static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
430 if (!E->getType()->isVectorType())
431 return false;
432 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
433 return !Result.isUninit();
434}
435
436APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
437 const Expr* SE = E->getSubExpr();
438
439 // Check for vector->vector bitcast.
440 if (SE->getType()->isVectorType())
441 return this->Visit(const_cast<Expr*>(SE));
442
443 return APValue();
444}
445
446APValue
447VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
448 return this->Visit(const_cast<Expr*>(E->getInitializer()));
449}
450
451APValue
452VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
453 const VectorType *VT = E->getType()->getAsVectorType();
454 unsigned NumInits = E->getNumInits();
455
456 if (!VT || VT->getNumElements() != NumInits)
457 return APValue();
458
459 QualType EltTy = VT->getElementType();
460 llvm::SmallVector<APValue, 4> Elements;
461
462 for (unsigned i = 0; i < NumInits; i++) {
463 if (EltTy->isIntegerType()) {
464 llvm::APSInt sInt(32);
465 if (!EvaluateInteger(E->getInit(i), sInt, Info))
466 return APValue();
467 Elements.push_back(APValue(sInt));
468 } else {
469 llvm::APFloat f(0.0);
470 if (!EvaluateFloat(E->getInit(i), f, Info))
471 return APValue();
472 Elements.push_back(APValue(f));
473 }
474 }
475 return APValue(&Elements[0], Elements.size());
476}
477
478//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000479// Integer Evaluation
480//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000481
482namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000483class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000484 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000485 EvalInfo &Info;
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000486 APValue &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000487public:
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000488 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner422373c2008-07-11 22:52:41 +0000489 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000490
Anders Carlssonfa76d822008-11-30 18:14:57 +0000491 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000492 Info.EvalResult.DiagLoc = L;
493 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000494 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000495 return true; // still a constant.
496 }
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000497
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000498 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbarb5c66db2009-02-21 18:14:20 +0000499 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000500 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000501 "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000502 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000503 "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000504 Result = APValue(SI);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000505 return true;
506 }
507
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000508 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbarb5c66db2009-02-21 18:14:20 +0000509 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000510 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000511 "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000512 Result = APValue(APSInt(I));
513 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000514 return true;
515 }
516
517 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbarb5c66db2009-02-21 18:14:20 +0000518 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000519 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000520 return true;
521 }
522
Anders Carlssonfa76d822008-11-30 18:14:57 +0000523 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000524 // If this is in an unevaluated portion of the subexpression, ignore the
525 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000526 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000527 // If error is ignored because the value isn't evaluated, get the real
528 // type at least to prevent errors downstream.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000529 return Success(0, E);
Chris Lattner438f3b12008-11-12 07:43:42 +0000530 }
Chris Lattner82437da2008-07-12 00:14:42 +0000531
Chris Lattner438f3b12008-11-12 07:43:42 +0000532 // Take the first error.
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000533
534 // FIXME: This is wrong if we happen to have already emitted an
535 // extension diagnostic; in that case we should report this error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000536 if (Info.EvalResult.Diag == 0) {
537 Info.EvalResult.DiagLoc = L;
538 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000539 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000540 }
Chris Lattner82437da2008-07-12 00:14:42 +0000541 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000542 }
543
Anders Carlssoncad17b52008-07-08 05:13:58 +0000544 //===--------------------------------------------------------------------===//
545 // Visitor Methods
546 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000547
548 bool VisitStmt(Stmt *) {
549 assert(0 && "This should be called on integers, stmts are not integers");
550 return false;
551 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000552
Chris Lattner438f3b12008-11-12 07:43:42 +0000553 bool VisitExpr(Expr *E) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000554 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssoncad17b52008-07-08 05:13:58 +0000555 }
556
Chris Lattnera42f09a2008-07-11 19:10:17 +0000557 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000558
Chris Lattner15e59112008-07-12 00:38:25 +0000559 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000560 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000561 }
562 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000563 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000564 }
565 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000566 // Per gcc docs "this built-in function ignores top level
567 // qualifiers". We need to use the canonical version to properly
568 // be able to strip CRV qualifiers from the type.
569 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
570 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000571 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
572 T1.getUnqualifiedType()),
573 E);
Chris Lattner15e59112008-07-12 00:38:25 +0000574 }
575 bool VisitDeclRefExpr(const DeclRefExpr *E);
576 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000577 bool VisitBinaryOperator(const BinaryOperator *E);
578 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000579 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000580
Daniel Dunbaraffa0e32009-01-29 06:16:07 +0000581 bool VisitCastExpr(CastExpr* E);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000582 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
583
Anders Carlsson027f2882008-11-16 19:01:22 +0000584 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000585 return Success(E->getValue(), E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000586 }
587
Anders Carlsson774f9c72008-12-21 22:39:40 +0000588 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000589 return Success(0, E);
Anders Carlsson774f9c72008-12-21 22:39:40 +0000590 }
591
Anders Carlsson027f2882008-11-16 19:01:22 +0000592 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000593 return Success(0, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000594 }
595
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000596 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000597 return Success(E->EvaluateTrait(), E);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000598 }
599
Chris Lattner265a0892008-07-11 21:24:13 +0000600private:
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000601 unsigned GetAlignOfExpr(const Expr *E);
602 unsigned GetAlignOfType(QualType T);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000603};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000604} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000605
Daniel Dunbar56611002009-02-20 18:22:23 +0000606static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000607 if (!E->getType()->isIntegralType())
608 return false;
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000609
Daniel Dunbar56611002009-02-20 18:22:23 +0000610 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
611}
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000612
Daniel Dunbar56611002009-02-20 18:22:23 +0000613static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
614 APValue Val;
615 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
616 return false;
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000617 Result = Val.getInt();
618 return true;
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000619}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000620
Chris Lattner15e59112008-07-12 00:38:25 +0000621bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
622 // Enums are integer constant exprs.
623 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
Eli Friedman8b10a232008-12-08 02:21:03 +0000624 // FIXME: This is an ugly hack around the fact that enums don't set their
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000625 // signedness consistently; see PR3173.
626 APSInt SI = D->getInitVal();
627 SI.setIsUnsigned(!E->getType()->isSignedIntegerType());
628 // FIXME: This is an ugly hack around the fact that enums don't
629 // set their width (!?!) consistently; see PR3173.
630 SI.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
631 return Success(SI, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000632 }
Sebastian Redl410dd872009-02-08 15:51:17 +0000633
634 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
635 if (Info.Ctx.getLangOptions().CPlusPlus &&
636 E->getType().getCVRQualifiers() == QualType::Const) {
637 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
638 if (const Expr *Init = D->getInit())
639 return Visit(const_cast<Expr*>(Init));
640 }
641 }
642
Chris Lattner15e59112008-07-12 00:38:25 +0000643 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000644 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000645}
646
Chris Lattner1eee9402008-10-06 06:40:35 +0000647/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
648/// as GCC.
649static int EvaluateBuiltinClassifyType(const CallExpr *E) {
650 // The following enum mimics the values returned by GCC.
651 enum gcc_type_class {
652 no_type_class = -1,
653 void_type_class, integer_type_class, char_type_class,
654 enumeral_type_class, boolean_type_class,
655 pointer_type_class, reference_type_class, offset_type_class,
656 real_type_class, complex_type_class,
657 function_type_class, method_type_class,
658 record_type_class, union_type_class,
659 array_type_class, string_type_class,
660 lang_type_class
661 };
662
663 // If no argument was supplied, default to "no_type_class". This isn't
664 // ideal, however it is what gcc does.
665 if (E->getNumArgs() == 0)
666 return no_type_class;
667
668 QualType ArgTy = E->getArg(0)->getType();
669 if (ArgTy->isVoidType())
670 return void_type_class;
671 else if (ArgTy->isEnumeralType())
672 return enumeral_type_class;
673 else if (ArgTy->isBooleanType())
674 return boolean_type_class;
675 else if (ArgTy->isCharType())
676 return string_type_class; // gcc doesn't appear to use char_type_class
677 else if (ArgTy->isIntegerType())
678 return integer_type_class;
679 else if (ArgTy->isPointerType())
680 return pointer_type_class;
681 else if (ArgTy->isReferenceType())
682 return reference_type_class;
683 else if (ArgTy->isRealType())
684 return real_type_class;
685 else if (ArgTy->isComplexType())
686 return complex_type_class;
687 else if (ArgTy->isFunctionType())
688 return function_type_class;
689 else if (ArgTy->isStructureType())
690 return record_type_class;
691 else if (ArgTy->isUnionType())
692 return union_type_class;
693 else if (ArgTy->isArrayType())
694 return array_type_class;
695 else if (ArgTy->isUnionType())
696 return union_type_class;
697 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
698 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
699 return -1;
700}
701
Chris Lattner15e59112008-07-12 00:38:25 +0000702bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000703 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner87293782008-10-06 05:28:25 +0000704 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000705 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000706 case Builtin::BI__builtin_classify_type:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000707 return Success(EvaluateBuiltinClassifyType(E), E);
Chris Lattner87293782008-10-06 05:28:25 +0000708
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000709 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000710 // __builtin_constant_p always has one operand: it returns true if that
711 // operand can be folded, false otherwise.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000712 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner87293782008-10-06 05:28:25 +0000713 }
Chris Lattner15e59112008-07-12 00:38:25 +0000714}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000715
Chris Lattnera42f09a2008-07-11 19:10:17 +0000716bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000717 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000718 if (!Visit(E->getRHS()))
719 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000720
721 if (!Info.ShortCircuit) {
722 // If we can't evaluate the LHS, it must be because it has
723 // side effects.
724 if (!E->getLHS()->isEvaluatable(Info.Ctx))
725 Info.EvalResult.HasSideEffects = true;
726
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000727 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000728 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000729
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000730 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000731 }
732
733 if (E->isLogicalOp()) {
734 // These need to be handled specially because the operands aren't
735 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000736 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000737
Anders Carlsson501da1f2008-11-30 16:51:17 +0000738 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000739 // We were able to evaluate the LHS, see if we can get away with not
740 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000741 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
742 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000743 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000744 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000745 Info.ShortCircuit--;
746
Anders Carlsson501da1f2008-11-30 16:51:17 +0000747 // FIXME: Return an extension warning saying that the RHS could not be
748 // evaluated.
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000749 // if (!rhsEvaluated) ...
750 (void) rhsEvaluated;
751
752 return Success(lhsResult, E);
Eli Friedman14cc7542008-11-13 06:09:17 +0000753 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000754
Anders Carlsson501da1f2008-11-30 16:51:17 +0000755 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000756 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000757 return Success(lhsResult || rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000758 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000759 return Success(lhsResult && rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000760 }
761 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000762 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000763 // We can't evaluate the LHS; however, sometimes the result
764 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000765 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
766 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000767 // Since we weren't able to evaluate the left hand side, it
Anders Carlsson501da1f2008-11-30 16:51:17 +0000768 // must have had side effects.
769 Info.EvalResult.HasSideEffects = true;
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000770
771 return Success(rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000772 }
773 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000774 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000775
Eli Friedman14cc7542008-11-13 06:09:17 +0000776 return false;
777 }
778
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000779 QualType LHSTy = E->getLHS()->getType();
780 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000781
782 if (LHSTy->isAnyComplexType()) {
783 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
784 APValue LHS, RHS;
785
786 if (!EvaluateComplex(E->getLHS(), LHS, Info))
787 return false;
788
789 if (!EvaluateComplex(E->getRHS(), RHS, Info))
790 return false;
791
792 if (LHS.isComplexFloat()) {
793 APFloat::cmpResult CR_r =
794 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
795 APFloat::cmpResult CR_i =
796 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
797
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000798 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000799 return Success((CR_r == APFloat::cmpEqual &&
800 CR_i == APFloat::cmpEqual), E);
801 else {
802 assert(E->getOpcode() == BinaryOperator::NE &&
803 "Invalid complex comparison.");
804 return Success(((CR_r == APFloat::cmpGreaterThan ||
805 CR_r == APFloat::cmpLessThan) &&
806 (CR_i == APFloat::cmpGreaterThan ||
807 CR_i == APFloat::cmpLessThan)), E);
808 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000809 } else {
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000810 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000811 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
812 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
813 else {
814 assert(E->getOpcode() == BinaryOperator::NE &&
815 "Invalid compex comparison.");
816 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
817 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
818 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000819 }
820 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000821
822 if (LHSTy->isRealFloatingType() &&
823 RHSTy->isRealFloatingType()) {
824 APFloat RHS(0.0), LHS(0.0);
825
826 if (!EvaluateFloat(E->getRHS(), RHS, Info))
827 return false;
828
829 if (!EvaluateFloat(E->getLHS(), LHS, Info))
830 return false;
831
832 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000833
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000834 switch (E->getOpcode()) {
835 default:
836 assert(0 && "Invalid binary operator!");
837 case BinaryOperator::LT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000838 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000839 case BinaryOperator::GT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000840 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000841 case BinaryOperator::LE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000842 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000843 case BinaryOperator::GE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000844 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
845 E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000846 case BinaryOperator::EQ:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000847 return Success(CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000848 case BinaryOperator::NE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000849 return Success(CR == APFloat::cmpGreaterThan
850 || CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000851 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000852 }
853
Anders Carlsson027f2882008-11-16 19:01:22 +0000854 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000855 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000856 APValue LHSValue;
857 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
858 return false;
859
860 APValue RHSValue;
861 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
862 return false;
863
864 // FIXME: Is this correct? What if only one of the operands has a base?
865 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
866 return false;
867
868 const QualType Type = E->getLHS()->getType();
869 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
870
871 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
872 D /= Info.Ctx.getTypeSize(ElementType) / 8;
873
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000874 return Success(D, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000875 }
876 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000877 if (!LHSTy->isIntegralType() ||
878 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000879 // We can't continue from here for non-integral types, and they
880 // could potentially confuse the following operations.
881 // FIXME: Deal with EQ and friends.
882 return false;
883 }
884
Anders Carlssond1aa5812008-07-08 14:35:21 +0000885 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000886 if (!Visit(E->getLHS()))
Chris Lattner82437da2008-07-12 00:14:42 +0000887 return false; // error in subexpression.
Eli Friedman3e64dd72008-07-27 05:46:18 +0000888
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000889 // Only support arithmetic on integers for now.
890 if (!Result.isInt())
891 return false;
892
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000893 llvm::APSInt RHS;
Chris Lattner82437da2008-07-12 00:14:42 +0000894 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000895 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000896
Anders Carlssond1aa5812008-07-08 14:35:21 +0000897 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000898 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000899 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000900 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
901 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
902 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
903 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
904 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
905 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000906 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000907 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000908 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000909 return Success(Result.getInt() / RHS, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000910 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000911 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000912 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000913 return Success(Result.getInt() % RHS, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000914 case BinaryOperator::Shl: {
Chris Lattner82437da2008-07-12 00:14:42 +0000915 // FIXME: Warn about out of range shift amounts!
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000916 unsigned SA =
917 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
918 return Success(Result.getInt() << SA, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000919 }
920 case BinaryOperator::Shr: {
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000921 unsigned SA =
922 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
923 return Success(Result.getInt() >> SA, E);
Daniel Dunbar470c0b22009-02-19 18:37:50 +0000924 }
Chris Lattnera42f09a2008-07-11 19:10:17 +0000925
Daniel Dunbarf2dc6752009-02-19 20:17:33 +0000926 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
927 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
928 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
929 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
930 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
931 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000932 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000933}
934
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000935bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000936 bool Cond;
937 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000938 return false;
939
Nuno Lopes308de752008-11-16 22:06:39 +0000940 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000941}
942
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000943unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere3f61e12009-01-24 21:09:06 +0000944 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
945
946 // __alignof__(void) = 1 as a gcc extension.
947 if (Ty->isVoidType())
948 return 1;
949
950 // GCC extension: alignof(function) = 4.
951 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
952 // attribute(align) directive.
953 if (Ty->isFunctionType())
954 return 4;
955
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000956 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
957 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere3f61e12009-01-24 21:09:06 +0000958
959 // alignof VLA/incomplete array.
960 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
961 return GetAlignOfType(VAT->getElementType());
962
963 // sizeof (objc class)?
964 if (isa<ObjCInterfaceType>(Ty))
965 return 1; // FIXME: This probably isn't right.
966
967 // Get information about the alignment.
968 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Eli Friedmanb1c0b542009-02-22 03:31:23 +0000969 return Info.Ctx.getPreferredTypeAlign(Ty) / CharSize;
Chris Lattnere3f61e12009-01-24 21:09:06 +0000970}
971
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000972unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
973 E = E->IgnoreParens();
974
975 // alignof decl is always accepted, even if it doesn't make sense: we default
976 // to 1 in those cases.
977 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000978 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000979
980 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000981 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000982
Chris Lattnere3f61e12009-01-24 21:09:06 +0000983 return GetAlignOfType(E->getType());
984}
985
986
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000987/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
988/// expression's type.
989bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
990 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000991
Chris Lattnere3f61e12009-01-24 21:09:06 +0000992 // Handle alignof separately.
993 if (!E->isSizeOf()) {
994 if (E->isArgumentType())
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000995 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000996 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000997 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000998 }
999
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001000 QualType SrcTy = E->getTypeOfArgument();
1001
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001002 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1003 // extension.
1004 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1005 return Success(1, E);
Chris Lattner265a0892008-07-11 21:24:13 +00001006
1007 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere3f61e12009-01-24 21:09:06 +00001008 if (!SrcTy->isConstantSizeType())
Chris Lattner265a0892008-07-11 21:24:13 +00001009 return false;
Eli Friedman5a2c38f2009-01-24 22:19:05 +00001010
1011 if (SrcTy->isObjCInterfaceType()) {
1012 // Slightly unusual case: the size of an ObjC interface type is the
1013 // size of the class. This code intentionally falls through to the normal
1014 // case.
1015 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
1016 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
1017 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
1018 }
1019
Chris Lattnere3f61e12009-01-24 21:09:06 +00001020 // Get information about the size.
Chris Lattner422373c2008-07-11 22:52:41 +00001021 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001022 return Success(Info.Ctx.getTypeSize(SrcTy) / CharSize, E);
Chris Lattner265a0892008-07-11 21:24:13 +00001023}
1024
Chris Lattnera42f09a2008-07-11 19:10:17 +00001025bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +00001026 // Special case unary operators that do not need their subexpression
1027 // evaluated. offsetof/sizeof/alignof are all special.
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001028 if (E->isOffsetOfOp())
1029 return Success(E->evaluateOffsetOf(Info.Ctx), E);
Eli Friedman14cc7542008-11-13 06:09:17 +00001030
1031 if (E->getOpcode() == UnaryOperator::LNot) {
1032 // LNot's operand isn't necessarily an integer, so we handle it specially.
1033 bool bres;
1034 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1035 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001036 return Success(!bres, E);
Eli Friedman14cc7542008-11-13 06:09:17 +00001037 }
1038
Daniel Dunbarb5c66db2009-02-21 18:14:20 +00001039 // Only handle integral operations...
1040 if (!E->getSubExpr()->getType()->isIntegralType())
1041 return false;
1042
Chris Lattner422373c2008-07-11 22:52:41 +00001043 // Get the operand value into 'Result'.
1044 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +00001045 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001046
Chris Lattner400d7402008-07-11 22:15:16 +00001047 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +00001048 default:
Chris Lattner400d7402008-07-11 22:15:16 +00001049 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1050 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001051 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +00001052 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +00001053 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1054 // If so, we could clear the diagnostic ID.
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001055 return true;
Chris Lattner400d7402008-07-11 22:15:16 +00001056 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +00001057 // The result is always just the subexpr.
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001058 return true;
Chris Lattner400d7402008-07-11 22:15:16 +00001059 case UnaryOperator::Minus:
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001060 if (!Result.isInt()) return false;
1061 return Success(-Result.getInt(), E);
Chris Lattner400d7402008-07-11 22:15:16 +00001062 case UnaryOperator::Not:
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001063 if (!Result.isInt()) return false;
1064 return Success(~Result.getInt(), E);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001065 }
Anders Carlssond1aa5812008-07-08 14:35:21 +00001066}
1067
Chris Lattnerff579ff2008-07-12 01:15:53 +00001068/// HandleCast - This is used to evaluate implicit or explicit casts where the
1069/// result type is integer.
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001070bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlssonfa76d822008-11-30 18:14:57 +00001071 Expr *SubExpr = E->getSubExpr();
1072 QualType DestType = E->getType();
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001073 QualType SrcType = SubExpr->getType();
Anders Carlssonfa76d822008-11-30 18:14:57 +00001074
Eli Friedman7888b932008-11-12 09:44:48 +00001075 if (DestType->isBooleanType()) {
1076 bool BoolResult;
1077 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1078 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001079 return Success(BoolResult, E);
Eli Friedman7888b932008-11-12 09:44:48 +00001080 }
1081
Anders Carlssond1aa5812008-07-08 14:35:21 +00001082 // Handle simple integer->integer casts.
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001083 if (SrcType->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +00001084 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001085 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001086
Eli Friedman0366a812009-02-20 01:15:07 +00001087 if (!Result.isInt()) {
1088 // Only allow casts of lvalues if they are lossless.
1089 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1090 }
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001091
Daniel Dunbarc9967f92009-02-19 22:24:01 +00001092 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001093 Result.getInt(), Info.Ctx), E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001094 }
1095
1096 // FIXME: Clean this up!
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001097 if (SrcType->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +00001098 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +00001099 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001100 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001101
Daniel Dunbarc9967f92009-02-19 22:24:01 +00001102 if (LV.getLValueBase()) {
1103 // Only allow based lvalue casts if they are lossless.
1104 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1105 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001106
Daniel Dunbarc9967f92009-02-19 22:24:01 +00001107 Result = LV;
1108 return true;
1109 }
1110
1111 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset(), SrcType);
1112 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson02a34c32008-07-08 14:30:00 +00001113 }
Eli Friedman7888b932008-11-12 09:44:48 +00001114
Eli Friedman0366a812009-02-20 01:15:07 +00001115 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1116 // This handles double-conversion cases, where there's both
1117 // an l-value promotion and an implicit conversion to int.
1118 APValue LV;
1119 if (!EvaluateLValue(SubExpr, LV, Info))
1120 return false;
1121
1122 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1123 return false;
1124
1125 Result = LV;
1126 return true;
1127 }
1128
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001129 if (!SrcType->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001130 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001131
Eli Friedman2f445492008-08-22 00:06:13 +00001132 APFloat F(0.0);
1133 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001134 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001135
Daniel Dunbar6dda4ba2009-02-19 22:16:29 +00001136 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssond1aa5812008-07-08 14:35:21 +00001137}
Anders Carlsson02a34c32008-07-08 14:30:00 +00001138
Chris Lattnera823ccf2008-07-11 18:11:29 +00001139//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +00001140// Float Evaluation
1141//===----------------------------------------------------------------------===//
1142
1143namespace {
1144class VISIBILITY_HIDDEN FloatExprEvaluator
1145 : public StmtVisitor<FloatExprEvaluator, bool> {
1146 EvalInfo &Info;
1147 APFloat &Result;
1148public:
1149 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1150 : Info(info), Result(result) {}
1151
1152 bool VisitStmt(Stmt *S) {
1153 return false;
1154 }
1155
1156 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +00001157 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001158
Daniel Dunbar804ead02008-10-16 03:51:50 +00001159 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001160 bool VisitBinaryOperator(const BinaryOperator *E);
1161 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +00001162 bool VisitCastExpr(CastExpr *E);
1163 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001164};
1165} // end anonymous namespace
1166
1167static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1168 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1169}
1170
Chris Lattner87293782008-10-06 05:28:25 +00001171bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +00001172 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner27cde262008-10-06 05:53:16 +00001173 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +00001174 case Builtin::BI__builtin_huge_val:
1175 case Builtin::BI__builtin_huge_valf:
1176 case Builtin::BI__builtin_huge_vall:
1177 case Builtin::BI__builtin_inf:
1178 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001179 case Builtin::BI__builtin_infl: {
1180 const llvm::fltSemantics &Sem =
1181 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +00001182 Result = llvm::APFloat::getInf(Sem);
1183 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001184 }
Chris Lattner667e1ee2008-10-06 06:31:58 +00001185
1186 case Builtin::BI__builtin_nan:
1187 case Builtin::BI__builtin_nanf:
1188 case Builtin::BI__builtin_nanl:
1189 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1190 // can't constant fold it.
1191 if (const StringLiteral *S =
1192 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1193 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001194 const llvm::fltSemantics &Sem =
1195 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +00001196 Result = llvm::APFloat::getNaN(Sem);
1197 return true;
1198 }
1199 }
1200 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +00001201
1202 case Builtin::BI__builtin_fabs:
1203 case Builtin::BI__builtin_fabsf:
1204 case Builtin::BI__builtin_fabsl:
1205 if (!EvaluateFloat(E->getArg(0), Result, Info))
1206 return false;
1207
1208 if (Result.isNegative())
1209 Result.changeSign();
1210 return true;
1211
1212 case Builtin::BI__builtin_copysign:
1213 case Builtin::BI__builtin_copysignf:
1214 case Builtin::BI__builtin_copysignl: {
1215 APFloat RHS(0.);
1216 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1217 !EvaluateFloat(E->getArg(1), RHS, Info))
1218 return false;
1219 Result.copySign(RHS);
1220 return true;
1221 }
Chris Lattner87293782008-10-06 05:28:25 +00001222 }
1223}
1224
Daniel Dunbar804ead02008-10-16 03:51:50 +00001225bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +00001226 if (E->getOpcode() == UnaryOperator::Deref)
1227 return false;
1228
Daniel Dunbar804ead02008-10-16 03:51:50 +00001229 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1230 return false;
1231
1232 switch (E->getOpcode()) {
1233 default: return false;
1234 case UnaryOperator::Plus:
1235 return true;
1236 case UnaryOperator::Minus:
1237 Result.changeSign();
1238 return true;
1239 }
1240}
Chris Lattner87293782008-10-06 05:28:25 +00001241
Eli Friedman2f445492008-08-22 00:06:13 +00001242bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1243 // FIXME: Diagnostics? I really don't understand how the warnings
1244 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001245 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001246 if (!EvaluateFloat(E->getLHS(), Result, Info))
1247 return false;
1248 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1249 return false;
1250
1251 switch (E->getOpcode()) {
1252 default: return false;
1253 case BinaryOperator::Mul:
1254 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1255 return true;
1256 case BinaryOperator::Add:
1257 Result.add(RHS, APFloat::rmNearestTiesToEven);
1258 return true;
1259 case BinaryOperator::Sub:
1260 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1261 return true;
1262 case BinaryOperator::Div:
1263 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1264 return true;
1265 case BinaryOperator::Rem:
1266 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1267 return true;
1268 }
1269}
1270
1271bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1272 Result = E->getValue();
1273 return true;
1274}
1275
Eli Friedman7888b932008-11-12 09:44:48 +00001276bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1277 Expr* SubExpr = E->getSubExpr();
Nate Begemand6d2f772009-01-18 03:20:47 +00001278
Eli Friedman7888b932008-11-12 09:44:48 +00001279 if (SubExpr->getType()->isIntegralType()) {
1280 APSInt IntResult;
Daniel Dunbar470c0b22009-02-19 18:37:50 +00001281 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman7888b932008-11-12 09:44:48 +00001282 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001283 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1284 IntResult, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001285 return true;
1286 }
1287 if (SubExpr->getType()->isRealFloatingType()) {
1288 if (!Visit(SubExpr))
1289 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001290 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1291 Result, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001292 return true;
1293 }
1294
1295 return false;
1296}
1297
1298bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1299 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1300 return true;
1301}
1302
Eli Friedman2f445492008-08-22 00:06:13 +00001303//===----------------------------------------------------------------------===//
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001304// Complex Evaluation (for float and integer)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001305//===----------------------------------------------------------------------===//
1306
1307namespace {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001308class VISIBILITY_HIDDEN ComplexExprEvaluator
1309 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001310 EvalInfo &Info;
1311
1312public:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001313 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001314
1315 //===--------------------------------------------------------------------===//
1316 // Visitor Methods
1317 //===--------------------------------------------------------------------===//
1318
1319 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001320 return APValue();
1321 }
1322
1323 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1324
1325 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001326 Expr* SubExpr = E->getSubExpr();
1327
1328 if (SubExpr->getType()->isRealFloatingType()) {
1329 APFloat Result(0.0);
1330
1331 if (!EvaluateFloat(SubExpr, Result, Info))
1332 return APValue();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001333
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001334 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001335 Result);
1336 } else {
1337 assert(SubExpr->getType()->isIntegerType() &&
1338 "Unexpected imaginary literal.");
1339
1340 llvm::APSInt Result;
1341 if (!EvaluateInteger(SubExpr, Result, Info))
1342 return APValue();
1343
1344 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1345 Zero = 0;
1346 return APValue(Zero, Result);
1347 }
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001348 }
1349
Anders Carlssonad2794c2008-11-16 21:51:21 +00001350 APValue VisitCastExpr(CastExpr *E) {
1351 Expr* SubExpr = E->getSubExpr();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001352 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1353 QualType SubType = SubExpr->getType();
Anders Carlssonad2794c2008-11-16 21:51:21 +00001354
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001355 if (SubType->isRealFloatingType()) {
Anders Carlssonad2794c2008-11-16 21:51:21 +00001356 APFloat Result(0.0);
1357
1358 if (!EvaluateFloat(SubExpr, Result, Info))
1359 return APValue();
1360
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001361 // Apply float conversion if necessary.
1362 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbarf8abb942009-01-24 19:08:01 +00001363 return APValue(Result,
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001364 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001365 } else if (SubType->isIntegerType()) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001366 APSInt Result;
1367
1368 if (!EvaluateInteger(SubExpr, Result, Info))
1369 return APValue();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001370
1371 // Apply integer conversion if necessary.
1372 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001373 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1374 Zero = 0;
1375 return APValue(Result, Zero);
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001376 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1377 APValue Src;
1378
1379 if (!EvaluateComplex(SubExpr, Src, Info))
1380 return APValue();
1381
1382 QualType SrcType = CT->getElementType();
1383
1384 if (Src.isComplexFloat()) {
1385 if (EltType->isRealFloatingType()) {
1386 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1387 Src.getComplexFloatReal(),
1388 Info.Ctx),
1389 HandleFloatToFloatCast(EltType, SrcType,
1390 Src.getComplexFloatImag(),
1391 Info.Ctx));
1392 } else {
1393 return APValue(HandleFloatToIntCast(EltType, SrcType,
1394 Src.getComplexFloatReal(),
1395 Info.Ctx),
1396 HandleFloatToIntCast(EltType, SrcType,
1397 Src.getComplexFloatImag(),
1398 Info.Ctx));
1399 }
1400 } else {
1401 assert(Src.isComplexInt() && "Invalid evaluate result.");
1402 if (EltType->isRealFloatingType()) {
1403 return APValue(HandleIntToFloatCast(EltType, SrcType,
1404 Src.getComplexIntReal(),
1405 Info.Ctx),
1406 HandleIntToFloatCast(EltType, SrcType,
1407 Src.getComplexIntImag(),
1408 Info.Ctx));
1409 } else {
1410 return APValue(HandleIntToIntCast(EltType, SrcType,
1411 Src.getComplexIntReal(),
1412 Info.Ctx),
1413 HandleIntToIntCast(EltType, SrcType,
1414 Src.getComplexIntImag(),
1415 Info.Ctx));
1416 }
1417 }
Anders Carlssonad2794c2008-11-16 21:51:21 +00001418 }
1419
1420 // FIXME: Handle more casts.
1421 return APValue();
1422 }
1423
1424 APValue VisitBinaryOperator(const BinaryOperator *E);
1425
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001426};
1427} // end anonymous namespace
1428
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001429static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001430{
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001431 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1432 assert((!Result.isComplexFloat() ||
1433 (&Result.getComplexFloatReal().getSemantics() ==
1434 &Result.getComplexFloatImag().getSemantics())) &&
1435 "Invalid complex evaluation.");
1436 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001437}
1438
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001439APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonad2794c2008-11-16 21:51:21 +00001440{
1441 APValue Result, RHS;
1442
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001443 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001444 return APValue();
1445
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001446 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001447 return APValue();
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001448
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001449 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1450 "Invalid operands to binary operator.");
Anders Carlssonad2794c2008-11-16 21:51:21 +00001451 switch (E->getOpcode()) {
1452 default: return APValue();
1453 case BinaryOperator::Add:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001454 if (Result.isComplexFloat()) {
1455 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1456 APFloat::rmNearestTiesToEven);
1457 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1458 APFloat::rmNearestTiesToEven);
1459 } else {
1460 Result.getComplexIntReal() += RHS.getComplexIntReal();
1461 Result.getComplexIntImag() += RHS.getComplexIntImag();
1462 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001463 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001464 case BinaryOperator::Sub:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001465 if (Result.isComplexFloat()) {
1466 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1467 APFloat::rmNearestTiesToEven);
1468 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1469 APFloat::rmNearestTiesToEven);
1470 } else {
1471 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1472 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1473 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001474 break;
1475 case BinaryOperator::Mul:
1476 if (Result.isComplexFloat()) {
1477 APValue LHS = Result;
1478 APFloat &LHS_r = LHS.getComplexFloatReal();
1479 APFloat &LHS_i = LHS.getComplexFloatImag();
1480 APFloat &RHS_r = RHS.getComplexFloatReal();
1481 APFloat &RHS_i = RHS.getComplexFloatImag();
1482
1483 APFloat Tmp = LHS_r;
1484 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1485 Result.getComplexFloatReal() = Tmp;
1486 Tmp = LHS_i;
1487 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1488 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1489
1490 Tmp = LHS_r;
1491 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1492 Result.getComplexFloatImag() = Tmp;
1493 Tmp = LHS_i;
1494 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1495 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1496 } else {
1497 APValue LHS = Result;
1498 Result.getComplexIntReal() =
1499 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1500 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1501 Result.getComplexIntImag() =
1502 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1503 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1504 }
1505 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001506 }
1507
1508 return Result;
1509}
1510
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001511//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001512// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001513//===----------------------------------------------------------------------===//
1514
Chris Lattneref069662008-11-16 21:24:15 +00001515/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001516/// any crazy technique (that has nothing to do with language standards) that
1517/// we want to. If this function returns true, it returns the folded constant
1518/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001519bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1520 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001521
Nate Begemand6d2f772009-01-18 03:20:47 +00001522 if (getType()->isVectorType()) {
1523 if (!EvaluateVector(this, Result.Val, Info))
1524 return false;
1525 } else if (getType()->isIntegerType()) {
Daniel Dunbarf2dc6752009-02-19 20:17:33 +00001526 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001527 return false;
Eli Friedman2f6d70d2009-02-22 04:02:33 +00001528 } else if (HasPointerEvalType(this)) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001529 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001530 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001531 } else if (getType()->isRealFloatingType()) {
1532 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001533 if (!EvaluateFloat(this, f, Info))
1534 return false;
1535
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001536 Result.Val = APValue(f);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001537 } else if (getType()->isAnyComplexType()) {
1538 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001539 return false;
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001540 } else
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001541 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001542
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001543 return true;
1544}
1545
Chris Lattneref069662008-11-16 21:24:15 +00001546/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001547/// folded, but discard the result.
1548bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001549 EvalResult Result;
1550 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001551}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001552
1553APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson8c3de802008-12-19 20:58:05 +00001554 EvalResult EvalResult;
1555 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001556 Result = Result;
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001557 assert(Result && "Could not evaluate expression");
Anders Carlsson8c3de802008-12-19 20:58:05 +00001558 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001559
Anders Carlsson8c3de802008-12-19 20:58:05 +00001560 return EvalResult.Val.getInt();
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001561}