blob: 64d3fdd8a7303de32d15448967ab4c6d26b88940 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Friedman4efaa272008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner500d3292009-01-29 05:15:15 +000018#include "clang/AST/ASTDiagnostic.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonc754aa62008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000024
Chris Lattner87eae5e2008-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 Carlsson54da0492008-11-30 16:38:33 +000042 /// EvalResult - Contains information about the evaluation.
43 Expr::EvalResult &EvalResult;
Anders Carlssonf0c1e4b2008-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 Lattner87eae5e2008-07-11 22:52:41 +000048
Anders Carlsson54da0492008-11-30 16:38:33 +000049 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +000050 EvalResult(evalresult), ShortCircuit(0) {}
Chris Lattner87eae5e2008-07-11 22:52:41 +000051};
52
53
Eli Friedman4efaa272008-11-12 09:44:48 +000054static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-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 Dunbar69ab26a2009-02-20 18:22:23 +000057static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000058static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +000059static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000060
61//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-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 Dunbara2cfd342009-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 Friedman4efaa272008-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 Dunbar8a7b7c62008-11-12 21:52:46 +0000146#if 0
Eli Friedman4efaa272008-11-12 09:44:48 +0000147 // FIXME: Remove this when we support more expressions.
148 printf("Unhandled pointer statement\n");
149 S->dump();
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000150#endif
Eli Friedman4efaa272008-11-12 09:44:48 +0000151 return APValue();
152 }
153
154 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson35873c42008-11-24 04:41:22 +0000155 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman4efaa272008-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 Carlsson3068d112008-11-16 19:01:22 +0000160 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmane8761c82009-02-20 01:57:15 +0000161 APValue VisitUnaryDeref(UnaryOperator *E);
Eli Friedman4efaa272008-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 Carlsson35873c42008-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 Friedman4efaa272008-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 Gregor86f19402008-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 Friedman4efaa272008-11-12 09:44:48 +0000204
205 // FIXME: This is linear time.
Douglas Gregor44b43212008-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 Friedman4efaa272008-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 Carlsson3068d112008-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 Friedman4efaa272008-11-12 09:44:48 +0000238
Eli Friedmane8761c82009-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 Friedman4efaa272008-11-12 09:44:48 +0000247//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000248// Pointer Evaluation
249//===----------------------------------------------------------------------===//
250
Anders Carlssonc754aa62008-07-08 05:13:58 +0000251namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000252class VISIBILITY_HIDDEN PointerExprEvaluator
253 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000254 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000255public:
Anders Carlsson2bad1682008-07-08 14:30:00 +0000256
Chris Lattner87eae5e2008-07-11 22:52:41 +0000257 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000258
Anders Carlsson2bad1682008-07-08 14:30:00 +0000259 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000260 return APValue();
261 }
262
263 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
264
Anders Carlsson650c92f2008-07-08 15:34:11 +0000265 APValue VisitBinaryOperator(const BinaryOperator *E);
266 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000267 APValue VisitUnaryOperator(const UnaryOperator *E);
268 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
269 { return APValue(E, 0); }
Eli Friedmanf0115892009-01-25 01:21:06 +0000270 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
271 { return APValue(E, 0); }
Eli Friedman3941b182009-01-25 01:54:01 +0000272 APValue VisitCallExpr(CallExpr *E);
Mike Stumpb83d2872009-02-19 22:01:56 +0000273 APValue VisitBlockExpr(BlockExpr *E) {
274 if (!E->hasBlockDeclRefExprs())
275 return APValue(E, 0);
276 return APValue();
277 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000278 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlsson650c92f2008-07-08 15:34:11 +0000279};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000280} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000281
Chris Lattner87eae5e2008-07-11 22:52:41 +0000282static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Mike Stumpca2f3fd2009-02-18 21:44:49 +0000283 if (!E->getType()->isPointerType()
284 && !E->getType()->isBlockPointerType())
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000285 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000286 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000287 return Result.isLValue();
288}
289
290APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
291 if (E->getOpcode() != BinaryOperator::Add &&
292 E->getOpcode() != BinaryOperator::Sub)
293 return APValue();
294
295 const Expr *PExp = E->getLHS();
296 const Expr *IExp = E->getRHS();
297 if (IExp->getType()->isPointerType())
298 std::swap(PExp, IExp);
299
300 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000301 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000302 return APValue();
303
304 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000305 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000306 return APValue();
307
Eli Friedman4efaa272008-11-12 09:44:48 +0000308 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000309 uint64_t SizeOfPointee;
310
311 // Explicitly handle GNU void* and function pointer arithmetic extensions.
312 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
313 SizeOfPointee = 1;
314 else
315 SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
Eli Friedman4efaa272008-11-12 09:44:48 +0000316
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000317 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman4efaa272008-11-12 09:44:48 +0000318
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000319 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman4efaa272008-11-12 09:44:48 +0000320 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000321 else
Eli Friedman4efaa272008-11-12 09:44:48 +0000322 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
323
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000324 return APValue(ResultLValue.getLValueBase(), Offset);
325}
Eli Friedman4efaa272008-11-12 09:44:48 +0000326
327APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
328 if (E->getOpcode() == UnaryOperator::Extension) {
329 // FIXME: Deal with warnings?
330 return Visit(E->getSubExpr());
331 }
332
333 if (E->getOpcode() == UnaryOperator::AddrOf) {
334 APValue result;
335 if (EvaluateLValue(E->getSubExpr(), result, Info))
336 return result;
337 }
338
339 return APValue();
340}
Anders Carlssond407a762008-12-05 05:24:13 +0000341
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000342
Chris Lattnerb542afe2008-07-11 19:10:17 +0000343APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000344 const Expr* SubExpr = E->getSubExpr();
345
346 // Check for pointer->pointer cast
347 if (SubExpr->getType()->isPointerType()) {
348 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000349 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000350 return Result;
351 return APValue();
352 }
353
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000354 if (SubExpr->getType()->isIntegralType()) {
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000355 APValue Result;
356 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
357 return APValue();
358
359 if (Result.isInt()) {
360 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
361 return APValue(0, Result.getInt().getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000362 }
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000363
364 // Cast is of an lvalue, no need to change value.
365 return Result;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000366 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000367
368 if (SubExpr->getType()->isFunctionType() ||
369 SubExpr->getType()->isArrayType()) {
370 APValue Result;
371 if (EvaluateLValue(SubExpr, Result, Info))
372 return Result;
373 return APValue();
374 }
375
376 //assert(0 && "Unhandled cast");
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000377 return APValue();
378}
379
Eli Friedman3941b182009-01-25 01:54:01 +0000380APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000381 if (E->isBuiltinCall(Info.Ctx) ==
382 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman3941b182009-01-25 01:54:01 +0000383 return APValue(E, 0);
384 return APValue();
385}
386
Eli Friedman4efaa272008-11-12 09:44:48 +0000387APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
388 bool BoolResult;
389 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
390 return APValue();
391
392 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
393
394 APValue Result;
395 if (EvaluatePointer(EvalExpr, Result, Info))
396 return Result;
397 return APValue();
398}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000399
400//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000401// Vector Evaluation
402//===----------------------------------------------------------------------===//
403
404namespace {
405 class VISIBILITY_HIDDEN VectorExprEvaluator
406 : public StmtVisitor<VectorExprEvaluator, APValue> {
407 EvalInfo &Info;
408 public:
409
410 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
411
412 APValue VisitStmt(Stmt *S) {
413 return APValue();
414 }
415
416 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
417 APValue VisitCastExpr(const CastExpr* E);
418 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
419 APValue VisitInitListExpr(const InitListExpr *E);
420 };
421} // end anonymous namespace
422
423static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
424 if (!E->getType()->isVectorType())
425 return false;
426 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
427 return !Result.isUninit();
428}
429
430APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
431 const Expr* SE = E->getSubExpr();
432
433 // Check for vector->vector bitcast.
434 if (SE->getType()->isVectorType())
435 return this->Visit(const_cast<Expr*>(SE));
436
437 return APValue();
438}
439
440APValue
441VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
442 return this->Visit(const_cast<Expr*>(E->getInitializer()));
443}
444
445APValue
446VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
447 const VectorType *VT = E->getType()->getAsVectorType();
448 unsigned NumInits = E->getNumInits();
449
450 if (!VT || VT->getNumElements() != NumInits)
451 return APValue();
452
453 QualType EltTy = VT->getElementType();
454 llvm::SmallVector<APValue, 4> Elements;
455
456 for (unsigned i = 0; i < NumInits; i++) {
457 if (EltTy->isIntegerType()) {
458 llvm::APSInt sInt(32);
459 if (!EvaluateInteger(E->getInit(i), sInt, Info))
460 return APValue();
461 Elements.push_back(APValue(sInt));
462 } else {
463 llvm::APFloat f(0.0);
464 if (!EvaluateFloat(E->getInit(i), f, Info))
465 return APValue();
466 Elements.push_back(APValue(f));
467 }
468 }
469 return APValue(&Elements[0], Elements.size());
470}
471
472//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000473// Integer Evaluation
474//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000475
476namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000477class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000478 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000479 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000480 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000481public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000482 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000483 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000484
Anders Carlsson82206e22008-11-30 18:14:57 +0000485 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlsson54da0492008-11-30 16:38:33 +0000486 Info.EvalResult.DiagLoc = L;
487 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000488 Info.EvalResult.DiagExpr = E;
Chris Lattner54176fd2008-07-12 00:14:42 +0000489 return true; // still a constant.
490 }
Daniel Dunbar131eb432009-02-19 09:06:44 +0000491
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000492 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000493 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000494 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000495 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000496 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000497 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000498 return true;
499 }
500
Daniel Dunbar131eb432009-02-19 09:06:44 +0000501 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000502 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000503 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000504 Result = APValue(APSInt(I));
505 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000506 return true;
507 }
508
509 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000510 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000511 return true;
512 }
513
Anders Carlsson82206e22008-11-30 18:14:57 +0000514 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000515 // If this is in an unevaluated portion of the subexpression, ignore the
516 // error.
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000517 if (Info.ShortCircuit) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000518 // If error is ignored because the value isn't evaluated, get the real
519 // type at least to prevent errors downstream.
Daniel Dunbar131eb432009-02-19 09:06:44 +0000520 return Success(0, E);
Chris Lattner32fea9d2008-11-12 07:43:42 +0000521 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000522
Chris Lattner32fea9d2008-11-12 07:43:42 +0000523 // Take the first error.
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000524
525 // FIXME: This is wrong if we happen to have already emitted an
526 // extension diagnostic; in that case we should report this error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000527 if (Info.EvalResult.Diag == 0) {
528 Info.EvalResult.DiagLoc = L;
529 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000530 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000531 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000532 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000533 }
534
Anders Carlssonc754aa62008-07-08 05:13:58 +0000535 //===--------------------------------------------------------------------===//
536 // Visitor Methods
537 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000538
539 bool VisitStmt(Stmt *) {
540 assert(0 && "This should be called on integers, stmts are not integers");
541 return false;
542 }
Chris Lattner7a767782008-07-11 19:24:49 +0000543
Chris Lattner32fea9d2008-11-12 07:43:42 +0000544 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000545 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000546 }
547
Chris Lattnerb542afe2008-07-11 19:10:17 +0000548 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000549
Chris Lattner4c4867e2008-07-12 00:38:25 +0000550 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000551 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000552 }
553 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000554 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000555 }
556 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarac620de2008-10-24 08:07:57 +0000557 // Per gcc docs "this built-in function ignores top level
558 // qualifiers". We need to use the canonical version to properly
559 // be able to strip CRV qualifiers from the type.
560 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
561 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000562 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
563 T1.getUnqualifiedType()),
564 E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000565 }
566 bool VisitDeclRefExpr(const DeclRefExpr *E);
567 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000568 bool VisitBinaryOperator(const BinaryOperator *E);
569 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000570 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000571
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000572 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000573 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
574
Anders Carlsson3068d112008-11-16 19:01:22 +0000575 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000576 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000577 }
578
Anders Carlsson3f704562008-12-21 22:39:40 +0000579 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000580 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000581 }
582
Anders Carlsson3068d112008-11-16 19:01:22 +0000583 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000584 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000585 }
586
Sebastian Redl64b45f72009-01-05 20:52:13 +0000587 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000588 return Success(E->EvaluateTrait(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000589 }
590
Chris Lattnerfcee0012008-07-11 21:24:13 +0000591private:
Chris Lattneraf707ab2009-01-24 21:53:27 +0000592 unsigned GetAlignOfExpr(const Expr *E);
593 unsigned GetAlignOfType(QualType T);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000594};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000595} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000596
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000597static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000598 if (!E->getType()->isIntegralType())
599 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000600
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000601 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
602}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000603
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000604static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
605 APValue Val;
606 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
607 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000608 Result = Val.getInt();
609 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +0000610}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000611
Chris Lattner4c4867e2008-07-12 00:38:25 +0000612bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
613 // Enums are integer constant exprs.
614 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
Eli Friedmane9a0f432008-12-08 02:21:03 +0000615 // FIXME: This is an ugly hack around the fact that enums don't set their
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000616 // signedness consistently; see PR3173.
617 APSInt SI = D->getInitVal();
618 SI.setIsUnsigned(!E->getType()->isSignedIntegerType());
619 // FIXME: This is an ugly hack around the fact that enums don't
620 // set their width (!?!) consistently; see PR3173.
621 SI.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
622 return Success(SI, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000623 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000624
625 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
626 if (Info.Ctx.getLangOptions().CPlusPlus &&
627 E->getType().getCVRQualifiers() == QualType::Const) {
628 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
629 if (const Expr *Init = D->getInit())
630 return Visit(const_cast<Expr*>(Init));
631 }
632 }
633
Chris Lattner4c4867e2008-07-12 00:38:25 +0000634 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000635 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000636}
637
Chris Lattnera4d55d82008-10-06 06:40:35 +0000638/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
639/// as GCC.
640static int EvaluateBuiltinClassifyType(const CallExpr *E) {
641 // The following enum mimics the values returned by GCC.
642 enum gcc_type_class {
643 no_type_class = -1,
644 void_type_class, integer_type_class, char_type_class,
645 enumeral_type_class, boolean_type_class,
646 pointer_type_class, reference_type_class, offset_type_class,
647 real_type_class, complex_type_class,
648 function_type_class, method_type_class,
649 record_type_class, union_type_class,
650 array_type_class, string_type_class,
651 lang_type_class
652 };
653
654 // If no argument was supplied, default to "no_type_class". This isn't
655 // ideal, however it is what gcc does.
656 if (E->getNumArgs() == 0)
657 return no_type_class;
658
659 QualType ArgTy = E->getArg(0)->getType();
660 if (ArgTy->isVoidType())
661 return void_type_class;
662 else if (ArgTy->isEnumeralType())
663 return enumeral_type_class;
664 else if (ArgTy->isBooleanType())
665 return boolean_type_class;
666 else if (ArgTy->isCharType())
667 return string_type_class; // gcc doesn't appear to use char_type_class
668 else if (ArgTy->isIntegerType())
669 return integer_type_class;
670 else if (ArgTy->isPointerType())
671 return pointer_type_class;
672 else if (ArgTy->isReferenceType())
673 return reference_type_class;
674 else if (ArgTy->isRealType())
675 return real_type_class;
676 else if (ArgTy->isComplexType())
677 return complex_type_class;
678 else if (ArgTy->isFunctionType())
679 return function_type_class;
680 else if (ArgTy->isStructureType())
681 return record_type_class;
682 else if (ArgTy->isUnionType())
683 return union_type_class;
684 else if (ArgTy->isArrayType())
685 return array_type_class;
686 else if (ArgTy->isUnionType())
687 return union_type_class;
688 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
689 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
690 return -1;
691}
692
Chris Lattner4c4867e2008-07-12 00:38:25 +0000693bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000694 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000695 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000696 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000697 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +0000698 return Success(EvaluateBuiltinClassifyType(E), E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000699
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000700 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +0000701 // __builtin_constant_p always has one operand: it returns true if that
702 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +0000703 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000704 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000705}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000706
Chris Lattnerb542afe2008-07-11 19:10:17 +0000707bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000708 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +0000709 if (!Visit(E->getRHS()))
710 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000711
712 if (!Info.ShortCircuit) {
713 // If we can't evaluate the LHS, it must be because it has
714 // side effects.
715 if (!E->getLHS()->isEvaluatable(Info.Ctx))
716 Info.EvalResult.HasSideEffects = true;
717
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000718 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000719 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000720
Anders Carlsson027f62e2008-12-01 02:07:06 +0000721 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000722 }
723
724 if (E->isLogicalOp()) {
725 // These need to be handled specially because the operands aren't
726 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000727 bool lhsResult, rhsResult;
Anders Carlsson51fe9962008-11-22 21:04:56 +0000728
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000729 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +0000730 // We were able to evaluate the LHS, see if we can get away with not
731 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000732 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
733 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000734 Info.ShortCircuit++;
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000735 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000736 Info.ShortCircuit--;
737
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000738 // FIXME: Return an extension warning saying that the RHS could not be
739 // evaluated.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000740 // if (!rhsEvaluated) ...
741 (void) rhsEvaluated;
742
743 return Success(lhsResult, E);
Eli Friedmana6afa762008-11-13 06:09:17 +0000744 }
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000745
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000746 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000747 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +0000748 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000749 else
Daniel Dunbar131eb432009-02-19 09:06:44 +0000750 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000751 }
752 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000753 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000754 // We can't evaluate the LHS; however, sometimes the result
755 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000756 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
757 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000758 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000759 // must have had side effects.
760 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +0000761
762 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000763 }
764 }
Anders Carlsson51fe9962008-11-22 21:04:56 +0000765 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000766
Eli Friedmana6afa762008-11-13 06:09:17 +0000767 return false;
768 }
769
Anders Carlsson286f85e2008-11-16 07:17:21 +0000770 QualType LHSTy = E->getLHS()->getType();
771 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +0000772
773 if (LHSTy->isAnyComplexType()) {
774 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
775 APValue LHS, RHS;
776
777 if (!EvaluateComplex(E->getLHS(), LHS, Info))
778 return false;
779
780 if (!EvaluateComplex(E->getRHS(), RHS, Info))
781 return false;
782
783 if (LHS.isComplexFloat()) {
784 APFloat::cmpResult CR_r =
785 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
786 APFloat::cmpResult CR_i =
787 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
788
Daniel Dunbar4087e242009-01-29 06:43:41 +0000789 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +0000790 return Success((CR_r == APFloat::cmpEqual &&
791 CR_i == APFloat::cmpEqual), E);
792 else {
793 assert(E->getOpcode() == BinaryOperator::NE &&
794 "Invalid complex comparison.");
795 return Success(((CR_r == APFloat::cmpGreaterThan ||
796 CR_r == APFloat::cmpLessThan) &&
797 (CR_i == APFloat::cmpGreaterThan ||
798 CR_i == APFloat::cmpLessThan)), E);
799 }
Daniel Dunbar4087e242009-01-29 06:43:41 +0000800 } else {
Daniel Dunbar4087e242009-01-29 06:43:41 +0000801 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +0000802 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
803 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
804 else {
805 assert(E->getOpcode() == BinaryOperator::NE &&
806 "Invalid compex comparison.");
807 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
808 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
809 }
Daniel Dunbar4087e242009-01-29 06:43:41 +0000810 }
811 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000812
813 if (LHSTy->isRealFloatingType() &&
814 RHSTy->isRealFloatingType()) {
815 APFloat RHS(0.0), LHS(0.0);
816
817 if (!EvaluateFloat(E->getRHS(), RHS, Info))
818 return false;
819
820 if (!EvaluateFloat(E->getLHS(), LHS, Info))
821 return false;
822
823 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +0000824
Anders Carlsson286f85e2008-11-16 07:17:21 +0000825 switch (E->getOpcode()) {
826 default:
827 assert(0 && "Invalid binary operator!");
828 case BinaryOperator::LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +0000829 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +0000830 case BinaryOperator::GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +0000831 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +0000832 case BinaryOperator::LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +0000833 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +0000834 case BinaryOperator::GE:
Daniel Dunbar131eb432009-02-19 09:06:44 +0000835 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
836 E);
Anders Carlsson286f85e2008-11-16 07:17:21 +0000837 case BinaryOperator::EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +0000838 return Success(CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +0000839 case BinaryOperator::NE:
Daniel Dunbar131eb432009-02-19 09:06:44 +0000840 return Success(CR == APFloat::cmpGreaterThan
841 || CR == APFloat::cmpLessThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +0000842 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000843 }
844
Anders Carlsson3068d112008-11-16 19:01:22 +0000845 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000846 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000847 APValue LHSValue;
848 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
849 return false;
850
851 APValue RHSValue;
852 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
853 return false;
854
855 // FIXME: Is this correct? What if only one of the operands has a base?
856 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
857 return false;
858
859 const QualType Type = E->getLHS()->getType();
860 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
861
862 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
863 D /= Info.Ctx.getTypeSize(ElementType) / 8;
864
Daniel Dunbar131eb432009-02-19 09:06:44 +0000865 return Success(D, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000866 }
867 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000868 if (!LHSTy->isIntegralType() ||
869 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000870 // We can't continue from here for non-integral types, and they
871 // could potentially confuse the following operations.
872 // FIXME: Deal with EQ and friends.
873 return false;
874 }
875
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000876 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000877 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +0000878 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000879
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000880 // Only support arithmetic on integers for now.
881 if (!Result.isInt())
882 return false;
883
Daniel Dunbar131eb432009-02-19 09:06:44 +0000884 llvm::APSInt RHS;
Chris Lattner54176fd2008-07-12 00:14:42 +0000885 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000886 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000887
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000888 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000889 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000890 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000891 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
892 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
893 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
894 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
895 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
896 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000897 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000898 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000899 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000900 return Success(Result.getInt() / RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000901 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000902 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000903 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000904 return Success(Result.getInt() % RHS, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000905 case BinaryOperator::Shl: {
Chris Lattner54176fd2008-07-12 00:14:42 +0000906 // FIXME: Warn about out of range shift amounts!
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000907 unsigned SA =
908 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
909 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000910 }
911 case BinaryOperator::Shr: {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000912 unsigned SA =
913 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
914 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000915 }
Chris Lattnerb542afe2008-07-11 19:10:17 +0000916
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000917 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
918 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
919 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
920 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
921 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
922 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +0000923 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000924}
925
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000926bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +0000927 bool Cond;
928 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000929 return false;
930
Nuno Lopesa25bd552008-11-16 22:06:39 +0000931 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000932}
933
Chris Lattneraf707ab2009-01-24 21:53:27 +0000934unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere9feb472009-01-24 21:09:06 +0000935 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
936
937 // __alignof__(void) = 1 as a gcc extension.
938 if (Ty->isVoidType())
939 return 1;
940
941 // GCC extension: alignof(function) = 4.
942 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
943 // attribute(align) directive.
944 if (Ty->isFunctionType())
945 return 4;
946
Fariborz Jahanianf11284a2009-02-17 18:27:45 +0000947 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
948 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere9feb472009-01-24 21:09:06 +0000949
950 // alignof VLA/incomplete array.
951 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
952 return GetAlignOfType(VAT->getElementType());
953
954 // sizeof (objc class)?
955 if (isa<ObjCInterfaceType>(Ty))
956 return 1; // FIXME: This probably isn't right.
957
958 // Get information about the alignment.
959 unsigned CharSize = Info.Ctx.Target.getCharWidth();
960 return Info.Ctx.getTypeAlign(Ty) / CharSize;
961}
962
Chris Lattneraf707ab2009-01-24 21:53:27 +0000963unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
964 E = E->IgnoreParens();
965
966 // alignof decl is always accepted, even if it doesn't make sense: we default
967 // to 1 in those cases.
968 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000969 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000970
971 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbarb7d08442009-02-17 22:16:19 +0000972 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattneraf707ab2009-01-24 21:53:27 +0000973
Chris Lattnere9feb472009-01-24 21:09:06 +0000974 return GetAlignOfType(E->getType());
975}
976
977
Sebastian Redl05189992008-11-11 17:56:53 +0000978/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
979/// expression's type.
980bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
981 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000982
Chris Lattnere9feb472009-01-24 21:09:06 +0000983 // Handle alignof separately.
984 if (!E->isSizeOf()) {
985 if (E->isArgumentType())
Daniel Dunbar131eb432009-02-19 09:06:44 +0000986 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +0000987 else
Daniel Dunbar131eb432009-02-19 09:06:44 +0000988 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +0000989 }
990
Sebastian Redl05189992008-11-11 17:56:53 +0000991 QualType SrcTy = E->getTypeOfArgument();
992
Daniel Dunbar131eb432009-02-19 09:06:44 +0000993 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
994 // extension.
995 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
996 return Success(1, E);
Chris Lattnerfcee0012008-07-11 21:24:13 +0000997
998 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +0000999 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001000 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001001
1002 if (SrcTy->isObjCInterfaceType()) {
1003 // Slightly unusual case: the size of an ObjC interface type is the
1004 // size of the class. This code intentionally falls through to the normal
1005 // case.
1006 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
1007 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
1008 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
1009 }
1010
Chris Lattnere9feb472009-01-24 21:09:06 +00001011 // Get information about the size.
Chris Lattner87eae5e2008-07-11 22:52:41 +00001012 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Daniel Dunbar131eb432009-02-19 09:06:44 +00001013 return Success(Info.Ctx.getTypeSize(SrcTy) / CharSize, E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001014}
1015
Chris Lattnerb542afe2008-07-11 19:10:17 +00001016bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001017 // Special case unary operators that do not need their subexpression
1018 // evaluated. offsetof/sizeof/alignof are all special.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001019 if (E->isOffsetOfOp())
1020 return Success(E->evaluateOffsetOf(Info.Ctx), E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001021
1022 if (E->getOpcode() == UnaryOperator::LNot) {
1023 // LNot's operand isn't necessarily an integer, so we handle it specially.
1024 bool bres;
1025 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1026 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001027 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001028 }
1029
Chris Lattner87eae5e2008-07-11 22:52:41 +00001030 // Get the operand value into 'Result'.
1031 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001032 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001033
Chris Lattner75a48812008-07-11 22:15:16 +00001034 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001035 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001036 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1037 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001038 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001039 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001040 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1041 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001042 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001043 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001044 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001045 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001046 case UnaryOperator::Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001047 if (!Result.isInt()) return false;
1048 return Success(-Result.getInt(), E);
Chris Lattner75a48812008-07-11 22:15:16 +00001049 case UnaryOperator::Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001050 if (!Result.isInt()) return false;
1051 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001052 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001053}
1054
Chris Lattner732b2232008-07-12 01:15:53 +00001055/// HandleCast - This is used to evaluate implicit or explicit casts where the
1056/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001057bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001058 Expr *SubExpr = E->getSubExpr();
1059 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001060 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001061
Eli Friedman4efaa272008-11-12 09:44:48 +00001062 if (DestType->isBooleanType()) {
1063 bool BoolResult;
1064 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1065 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001066 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001067 }
1068
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001069 // Handle simple integer->integer casts.
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001070 if (SrcType->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001071 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001072 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001073
Eli Friedmanbe265702009-02-20 01:15:07 +00001074 if (!Result.isInt()) {
1075 // Only allow casts of lvalues if they are lossless.
1076 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1077 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001078
Daniel Dunbardd211642009-02-19 22:24:01 +00001079 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001080 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001081 }
1082
1083 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001084 if (SrcType->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001085 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001086 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001087 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001088
Daniel Dunbardd211642009-02-19 22:24:01 +00001089 if (LV.getLValueBase()) {
1090 // Only allow based lvalue casts if they are lossless.
1091 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1092 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001093
Daniel Dunbardd211642009-02-19 22:24:01 +00001094 Result = LV;
1095 return true;
1096 }
1097
1098 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset(), SrcType);
1099 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001100 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001101
Eli Friedmanbe265702009-02-20 01:15:07 +00001102 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1103 // This handles double-conversion cases, where there's both
1104 // an l-value promotion and an implicit conversion to int.
1105 APValue LV;
1106 if (!EvaluateLValue(SubExpr, LV, Info))
1107 return false;
1108
1109 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1110 return false;
1111
1112 Result = LV;
1113 return true;
1114 }
1115
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001116 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001117 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001118
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001119 APFloat F(0.0);
1120 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001121 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001122
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001123 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001124}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001125
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001126//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001127// Float Evaluation
1128//===----------------------------------------------------------------------===//
1129
1130namespace {
1131class VISIBILITY_HIDDEN FloatExprEvaluator
1132 : public StmtVisitor<FloatExprEvaluator, bool> {
1133 EvalInfo &Info;
1134 APFloat &Result;
1135public:
1136 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1137 : Info(info), Result(result) {}
1138
1139 bool VisitStmt(Stmt *S) {
1140 return false;
1141 }
1142
1143 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001144 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001145
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001146 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001147 bool VisitBinaryOperator(const BinaryOperator *E);
1148 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001149 bool VisitCastExpr(CastExpr *E);
1150 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001151};
1152} // end anonymous namespace
1153
1154static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1155 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1156}
1157
Chris Lattner019f4e82008-10-06 05:28:25 +00001158bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001159 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001160 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001161 case Builtin::BI__builtin_huge_val:
1162 case Builtin::BI__builtin_huge_valf:
1163 case Builtin::BI__builtin_huge_vall:
1164 case Builtin::BI__builtin_inf:
1165 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001166 case Builtin::BI__builtin_infl: {
1167 const llvm::fltSemantics &Sem =
1168 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001169 Result = llvm::APFloat::getInf(Sem);
1170 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001171 }
Chris Lattner9e621712008-10-06 06:31:58 +00001172
1173 case Builtin::BI__builtin_nan:
1174 case Builtin::BI__builtin_nanf:
1175 case Builtin::BI__builtin_nanl:
1176 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1177 // can't constant fold it.
1178 if (const StringLiteral *S =
1179 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1180 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001181 const llvm::fltSemantics &Sem =
1182 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +00001183 Result = llvm::APFloat::getNaN(Sem);
1184 return true;
1185 }
1186 }
1187 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001188
1189 case Builtin::BI__builtin_fabs:
1190 case Builtin::BI__builtin_fabsf:
1191 case Builtin::BI__builtin_fabsl:
1192 if (!EvaluateFloat(E->getArg(0), Result, Info))
1193 return false;
1194
1195 if (Result.isNegative())
1196 Result.changeSign();
1197 return true;
1198
1199 case Builtin::BI__builtin_copysign:
1200 case Builtin::BI__builtin_copysignf:
1201 case Builtin::BI__builtin_copysignl: {
1202 APFloat RHS(0.);
1203 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1204 !EvaluateFloat(E->getArg(1), RHS, Info))
1205 return false;
1206 Result.copySign(RHS);
1207 return true;
1208 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001209 }
1210}
1211
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001212bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001213 if (E->getOpcode() == UnaryOperator::Deref)
1214 return false;
1215
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001216 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1217 return false;
1218
1219 switch (E->getOpcode()) {
1220 default: return false;
1221 case UnaryOperator::Plus:
1222 return true;
1223 case UnaryOperator::Minus:
1224 Result.changeSign();
1225 return true;
1226 }
1227}
Chris Lattner019f4e82008-10-06 05:28:25 +00001228
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001229bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1230 // FIXME: Diagnostics? I really don't understand how the warnings
1231 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001232 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001233 if (!EvaluateFloat(E->getLHS(), Result, Info))
1234 return false;
1235 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1236 return false;
1237
1238 switch (E->getOpcode()) {
1239 default: return false;
1240 case BinaryOperator::Mul:
1241 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1242 return true;
1243 case BinaryOperator::Add:
1244 Result.add(RHS, APFloat::rmNearestTiesToEven);
1245 return true;
1246 case BinaryOperator::Sub:
1247 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1248 return true;
1249 case BinaryOperator::Div:
1250 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1251 return true;
1252 case BinaryOperator::Rem:
1253 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1254 return true;
1255 }
1256}
1257
1258bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1259 Result = E->getValue();
1260 return true;
1261}
1262
Eli Friedman4efaa272008-11-12 09:44:48 +00001263bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1264 Expr* SubExpr = E->getSubExpr();
Nate Begeman59b5da62009-01-18 03:20:47 +00001265
Eli Friedman4efaa272008-11-12 09:44:48 +00001266 if (SubExpr->getType()->isIntegralType()) {
1267 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001268 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00001269 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001270 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1271 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001272 return true;
1273 }
1274 if (SubExpr->getType()->isRealFloatingType()) {
1275 if (!Visit(SubExpr))
1276 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001277 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1278 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001279 return true;
1280 }
1281
1282 return false;
1283}
1284
1285bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1286 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1287 return true;
1288}
1289
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001290//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001291// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001292//===----------------------------------------------------------------------===//
1293
1294namespace {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001295class VISIBILITY_HIDDEN ComplexExprEvaluator
1296 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001297 EvalInfo &Info;
1298
1299public:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001300 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001301
1302 //===--------------------------------------------------------------------===//
1303 // Visitor Methods
1304 //===--------------------------------------------------------------------===//
1305
1306 APValue VisitStmt(Stmt *S) {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001307 return APValue();
1308 }
1309
1310 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1311
1312 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001313 Expr* SubExpr = E->getSubExpr();
1314
1315 if (SubExpr->getType()->isRealFloatingType()) {
1316 APFloat Result(0.0);
1317
1318 if (!EvaluateFloat(SubExpr, Result, Info))
1319 return APValue();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001320
Daniel Dunbar3f279872009-01-29 01:32:56 +00001321 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001322 Result);
1323 } else {
1324 assert(SubExpr->getType()->isIntegerType() &&
1325 "Unexpected imaginary literal.");
1326
1327 llvm::APSInt Result;
1328 if (!EvaluateInteger(SubExpr, Result, Info))
1329 return APValue();
1330
1331 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1332 Zero = 0;
1333 return APValue(Zero, Result);
1334 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001335 }
1336
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001337 APValue VisitCastExpr(CastExpr *E) {
1338 Expr* SubExpr = E->getSubExpr();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001339 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1340 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001341
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001342 if (SubType->isRealFloatingType()) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001343 APFloat Result(0.0);
1344
1345 if (!EvaluateFloat(SubExpr, Result, Info))
1346 return APValue();
1347
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001348 // Apply float conversion if necessary.
1349 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbar8f826f02009-01-24 19:08:01 +00001350 return APValue(Result,
Daniel Dunbar3f279872009-01-29 01:32:56 +00001351 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001352 } else if (SubType->isIntegerType()) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001353 APSInt Result;
1354
1355 if (!EvaluateInteger(SubExpr, Result, Info))
1356 return APValue();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001357
1358 // Apply integer conversion if necessary.
1359 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001360 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1361 Zero = 0;
1362 return APValue(Result, Zero);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001363 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1364 APValue Src;
1365
1366 if (!EvaluateComplex(SubExpr, Src, Info))
1367 return APValue();
1368
1369 QualType SrcType = CT->getElementType();
1370
1371 if (Src.isComplexFloat()) {
1372 if (EltType->isRealFloatingType()) {
1373 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1374 Src.getComplexFloatReal(),
1375 Info.Ctx),
1376 HandleFloatToFloatCast(EltType, SrcType,
1377 Src.getComplexFloatImag(),
1378 Info.Ctx));
1379 } else {
1380 return APValue(HandleFloatToIntCast(EltType, SrcType,
1381 Src.getComplexFloatReal(),
1382 Info.Ctx),
1383 HandleFloatToIntCast(EltType, SrcType,
1384 Src.getComplexFloatImag(),
1385 Info.Ctx));
1386 }
1387 } else {
1388 assert(Src.isComplexInt() && "Invalid evaluate result.");
1389 if (EltType->isRealFloatingType()) {
1390 return APValue(HandleIntToFloatCast(EltType, SrcType,
1391 Src.getComplexIntReal(),
1392 Info.Ctx),
1393 HandleIntToFloatCast(EltType, SrcType,
1394 Src.getComplexIntImag(),
1395 Info.Ctx));
1396 } else {
1397 return APValue(HandleIntToIntCast(EltType, SrcType,
1398 Src.getComplexIntReal(),
1399 Info.Ctx),
1400 HandleIntToIntCast(EltType, SrcType,
1401 Src.getComplexIntImag(),
1402 Info.Ctx));
1403 }
1404 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001405 }
1406
1407 // FIXME: Handle more casts.
1408 return APValue();
1409 }
1410
1411 APValue VisitBinaryOperator(const BinaryOperator *E);
1412
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001413};
1414} // end anonymous namespace
1415
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001416static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001417{
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001418 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1419 assert((!Result.isComplexFloat() ||
1420 (&Result.getComplexFloatReal().getSemantics() ==
1421 &Result.getComplexFloatImag().getSemantics())) &&
1422 "Invalid complex evaluation.");
1423 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001424}
1425
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001426APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001427{
1428 APValue Result, RHS;
1429
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001430 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001431 return APValue();
1432
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001433 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001434 return APValue();
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001435
Daniel Dunbar3f279872009-01-29 01:32:56 +00001436 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1437 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001438 switch (E->getOpcode()) {
1439 default: return APValue();
1440 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001441 if (Result.isComplexFloat()) {
1442 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1443 APFloat::rmNearestTiesToEven);
1444 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1445 APFloat::rmNearestTiesToEven);
1446 } else {
1447 Result.getComplexIntReal() += RHS.getComplexIntReal();
1448 Result.getComplexIntImag() += RHS.getComplexIntImag();
1449 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001450 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001451 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001452 if (Result.isComplexFloat()) {
1453 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1454 APFloat::rmNearestTiesToEven);
1455 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1456 APFloat::rmNearestTiesToEven);
1457 } else {
1458 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1459 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1460 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001461 break;
1462 case BinaryOperator::Mul:
1463 if (Result.isComplexFloat()) {
1464 APValue LHS = Result;
1465 APFloat &LHS_r = LHS.getComplexFloatReal();
1466 APFloat &LHS_i = LHS.getComplexFloatImag();
1467 APFloat &RHS_r = RHS.getComplexFloatReal();
1468 APFloat &RHS_i = RHS.getComplexFloatImag();
1469
1470 APFloat Tmp = LHS_r;
1471 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1472 Result.getComplexFloatReal() = Tmp;
1473 Tmp = LHS_i;
1474 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1475 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1476
1477 Tmp = LHS_r;
1478 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1479 Result.getComplexFloatImag() = Tmp;
1480 Tmp = LHS_i;
1481 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1482 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1483 } else {
1484 APValue LHS = Result;
1485 Result.getComplexIntReal() =
1486 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1487 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1488 Result.getComplexIntImag() =
1489 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1490 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1491 }
1492 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001493 }
1494
1495 return Result;
1496}
1497
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001498//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001499// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001500//===----------------------------------------------------------------------===//
1501
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001502/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner019f4e82008-10-06 05:28:25 +00001503/// any crazy technique (that has nothing to do with language standards) that
1504/// we want to. If this function returns true, it returns the folded constant
1505/// in Result.
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001506bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1507 EvalInfo Info(Ctx, Result);
Anders Carlsson54da0492008-11-30 16:38:33 +00001508
Nate Begeman59b5da62009-01-18 03:20:47 +00001509 if (getType()->isVectorType()) {
1510 if (!EvaluateVector(this, Result.Val, Info))
1511 return false;
1512 } else if (getType()->isIntegerType()) {
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001513 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001514 return false;
Mike Stumpca2f3fd2009-02-18 21:44:49 +00001515 } else if (getType()->isPointerType()
1516 || getType()->isBlockPointerType()) {
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001517 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001518 return false;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001519 } else if (getType()->isRealFloatingType()) {
1520 llvm::APFloat f(0.0);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001521 if (!EvaluateFloat(this, f, Info))
1522 return false;
1523
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001524 Result.Val = APValue(f);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001525 } else if (getType()->isAnyComplexType()) {
1526 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001527 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001528 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00001529 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001530
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001531 return true;
1532}
1533
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001534/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001535/// folded, but discard the result.
1536bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001537 EvalResult Result;
1538 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001539}
Anders Carlsson51fe9962008-11-22 21:04:56 +00001540
1541APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001542 EvalResult EvalResult;
1543 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00001544 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00001545 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001546 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00001547
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001548 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00001549}