blob: 3a3b1527fa44b0efd39e1904344ad584b6967c7a [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);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000057static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +000058static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000059
60//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +000061// Misc utilities
62//===----------------------------------------------------------------------===//
63
64static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
65 if (E->getType()->isIntegralType()) {
66 APSInt IntResult;
67 if (!EvaluateInteger(E, IntResult, Info))
68 return false;
69 Result = IntResult != 0;
70 return true;
71 } else if (E->getType()->isRealFloatingType()) {
72 APFloat FloatResult(0.0);
73 if (!EvaluateFloat(E, FloatResult, Info))
74 return false;
75 Result = !FloatResult.isZero();
76 return true;
77 } else if (E->getType()->isPointerType()) {
78 APValue PointerResult;
79 if (!EvaluatePointer(E, PointerResult, Info))
80 return false;
81 // FIXME: Is this accurate for all kinds of bases? If not, what would
82 // the check look like?
83 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
84 return true;
85 }
86
87 return false;
88}
89
Daniel Dunbara2cfd342009-01-29 06:16:07 +000090static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
91 APFloat &Value, ASTContext &Ctx) {
92 unsigned DestWidth = Ctx.getIntWidth(DestType);
93 // Determine whether we are converting to unsigned or signed.
94 bool DestSigned = DestType->isSignedIntegerType();
95
96 // FIXME: Warning for overflow.
97 uint64_t Space[4];
98 bool ignored;
99 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
100 llvm::APFloat::rmTowardZero, &ignored);
101 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
102}
103
104static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
105 APFloat &Value, ASTContext &Ctx) {
106 bool ignored;
107 APFloat Result = Value;
108 Result.convert(Ctx.getFloatTypeSemantics(DestType),
109 APFloat::rmNearestTiesToEven, &ignored);
110 return Result;
111}
112
113static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
114 APSInt &Value, ASTContext &Ctx) {
115 unsigned DestWidth = Ctx.getIntWidth(DestType);
116 APSInt Result = Value;
117 // Figure out if this is a truncate, extend or noop cast.
118 // If the input is signed, do a sign extend, noop, or truncate.
119 Result.extOrTrunc(DestWidth);
120 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
121 return Result;
122}
123
124static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
125 APSInt &Value, ASTContext &Ctx) {
126
127 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
128 Result.convertFromAPInt(Value, Value.isSigned(),
129 APFloat::rmNearestTiesToEven);
130 return Result;
131}
132
Eli Friedman4efaa272008-11-12 09:44:48 +0000133//===----------------------------------------------------------------------===//
134// LValue Evaluation
135//===----------------------------------------------------------------------===//
136namespace {
137class VISIBILITY_HIDDEN LValueExprEvaluator
138 : public StmtVisitor<LValueExprEvaluator, APValue> {
139 EvalInfo &Info;
140public:
141
142 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
143
144 APValue VisitStmt(Stmt *S) {
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000145#if 0
Eli Friedman4efaa272008-11-12 09:44:48 +0000146 // FIXME: Remove this when we support more expressions.
147 printf("Unhandled pointer statement\n");
148 S->dump();
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000149#endif
Eli Friedman4efaa272008-11-12 09:44:48 +0000150 return APValue();
151 }
152
153 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson35873c42008-11-24 04:41:22 +0000154 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000155 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
156 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
157 APValue VisitMemberExpr(MemberExpr *E);
158 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson3068d112008-11-16 19:01:22 +0000159 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000160};
161} // end anonymous namespace
162
163static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
164 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
165 return Result.isLValue();
166}
167
Anders Carlsson35873c42008-11-24 04:41:22 +0000168APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E)
169{
170 if (!E->hasGlobalStorage())
171 return APValue();
172
173 return APValue(E, 0);
174}
175
Eli Friedman4efaa272008-11-12 09:44:48 +0000176APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
177 if (E->isFileScope())
178 return APValue(E, 0);
179 return APValue();
180}
181
182APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
183 APValue result;
184 QualType Ty;
185 if (E->isArrow()) {
186 if (!EvaluatePointer(E->getBase(), result, Info))
187 return APValue();
188 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
189 } else {
190 result = Visit(E->getBase());
191 if (result.isUninit())
192 return APValue();
193 Ty = E->getBase()->getType();
194 }
195
196 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
197 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000198
199 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
200 if (!FD) // FIXME: deal with other kinds of member expressions
201 return APValue();
Eli Friedman4efaa272008-11-12 09:44:48 +0000202
203 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000204 unsigned i = 0;
205 for (RecordDecl::field_iterator Field = RD->field_begin(),
206 FieldEnd = RD->field_end();
207 Field != FieldEnd; (void)++Field, ++i) {
208 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000209 break;
210 }
211
212 result.setLValue(result.getLValueBase(),
213 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
214
215 return result;
216}
217
Anders Carlsson3068d112008-11-16 19:01:22 +0000218APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
219{
220 APValue Result;
221
222 if (!EvaluatePointer(E->getBase(), Result, Info))
223 return APValue();
224
225 APSInt Index;
226 if (!EvaluateInteger(E->getIdx(), Index, Info))
227 return APValue();
228
229 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
230
231 uint64_t Offset = Index.getSExtValue() * ElementSize;
232 Result.setLValue(Result.getLValueBase(),
233 Result.getLValueOffset() + Offset);
234 return Result;
235}
Eli Friedman4efaa272008-11-12 09:44:48 +0000236
237//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000238// Pointer Evaluation
239//===----------------------------------------------------------------------===//
240
Anders Carlssonc754aa62008-07-08 05:13:58 +0000241namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000242class VISIBILITY_HIDDEN PointerExprEvaluator
243 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000244 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000245public:
Anders Carlsson2bad1682008-07-08 14:30:00 +0000246
Chris Lattner87eae5e2008-07-11 22:52:41 +0000247 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000248
Anders Carlsson2bad1682008-07-08 14:30:00 +0000249 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000250 return APValue();
251 }
252
253 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
254
Anders Carlsson650c92f2008-07-08 15:34:11 +0000255 APValue VisitBinaryOperator(const BinaryOperator *E);
256 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000257 APValue VisitUnaryOperator(const UnaryOperator *E);
258 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
259 { return APValue(E, 0); }
Eli Friedmanf0115892009-01-25 01:21:06 +0000260 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
261 { return APValue(E, 0); }
Eli Friedman3941b182009-01-25 01:54:01 +0000262 APValue VisitCallExpr(CallExpr *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000263 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlsson650c92f2008-07-08 15:34:11 +0000264};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000265} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000266
Chris Lattner87eae5e2008-07-11 22:52:41 +0000267static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000268 if (!E->getType()->isPointerType())
269 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000270 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000271 return Result.isLValue();
272}
273
274APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
275 if (E->getOpcode() != BinaryOperator::Add &&
276 E->getOpcode() != BinaryOperator::Sub)
277 return APValue();
278
279 const Expr *PExp = E->getLHS();
280 const Expr *IExp = E->getRHS();
281 if (IExp->getType()->isPointerType())
282 std::swap(PExp, IExp);
283
284 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000285 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000286 return APValue();
287
288 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000289 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000290 return APValue();
291
Eli Friedman4efaa272008-11-12 09:44:48 +0000292 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
293 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
294
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000295 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman4efaa272008-11-12 09:44:48 +0000296
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000297 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman4efaa272008-11-12 09:44:48 +0000298 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000299 else
Eli Friedman4efaa272008-11-12 09:44:48 +0000300 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
301
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000302 return APValue(ResultLValue.getLValueBase(), Offset);
303}
Eli Friedman4efaa272008-11-12 09:44:48 +0000304
305APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
306 if (E->getOpcode() == UnaryOperator::Extension) {
307 // FIXME: Deal with warnings?
308 return Visit(E->getSubExpr());
309 }
310
311 if (E->getOpcode() == UnaryOperator::AddrOf) {
312 APValue result;
313 if (EvaluateLValue(E->getSubExpr(), result, Info))
314 return result;
315 }
316
317 return APValue();
318}
Anders Carlssond407a762008-12-05 05:24:13 +0000319
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000320
Chris Lattnerb542afe2008-07-11 19:10:17 +0000321APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000322 const Expr* SubExpr = E->getSubExpr();
323
324 // Check for pointer->pointer cast
325 if (SubExpr->getType()->isPointerType()) {
326 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000327 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000328 return Result;
329 return APValue();
330 }
331
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000332 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000333 llvm::APSInt Result(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000334 if (EvaluateInteger(SubExpr, Result, Info)) {
335 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000336 return APValue(0, Result.getZExtValue());
337 }
338 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000339
340 if (SubExpr->getType()->isFunctionType() ||
341 SubExpr->getType()->isArrayType()) {
342 APValue Result;
343 if (EvaluateLValue(SubExpr, Result, Info))
344 return Result;
345 return APValue();
346 }
347
348 //assert(0 && "Unhandled cast");
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000349 return APValue();
350}
351
Eli Friedman3941b182009-01-25 01:54:01 +0000352APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +0000353 if (E->isBuiltinCall(Info.Ctx) ==
354 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman3941b182009-01-25 01:54:01 +0000355 return APValue(E, 0);
356 return APValue();
357}
358
Eli Friedman4efaa272008-11-12 09:44:48 +0000359APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
360 bool BoolResult;
361 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
362 return APValue();
363
364 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
365
366 APValue Result;
367 if (EvaluatePointer(EvalExpr, Result, Info))
368 return Result;
369 return APValue();
370}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000371
372//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000373// Vector Evaluation
374//===----------------------------------------------------------------------===//
375
376namespace {
377 class VISIBILITY_HIDDEN VectorExprEvaluator
378 : public StmtVisitor<VectorExprEvaluator, APValue> {
379 EvalInfo &Info;
380 public:
381
382 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
383
384 APValue VisitStmt(Stmt *S) {
385 return APValue();
386 }
387
388 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
389 APValue VisitCastExpr(const CastExpr* E);
390 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
391 APValue VisitInitListExpr(const InitListExpr *E);
392 };
393} // end anonymous namespace
394
395static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
396 if (!E->getType()->isVectorType())
397 return false;
398 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
399 return !Result.isUninit();
400}
401
402APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
403 const Expr* SE = E->getSubExpr();
404
405 // Check for vector->vector bitcast.
406 if (SE->getType()->isVectorType())
407 return this->Visit(const_cast<Expr*>(SE));
408
409 return APValue();
410}
411
412APValue
413VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
414 return this->Visit(const_cast<Expr*>(E->getInitializer()));
415}
416
417APValue
418VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
419 const VectorType *VT = E->getType()->getAsVectorType();
420 unsigned NumInits = E->getNumInits();
421
422 if (!VT || VT->getNumElements() != NumInits)
423 return APValue();
424
425 QualType EltTy = VT->getElementType();
426 llvm::SmallVector<APValue, 4> Elements;
427
428 for (unsigned i = 0; i < NumInits; i++) {
429 if (EltTy->isIntegerType()) {
430 llvm::APSInt sInt(32);
431 if (!EvaluateInteger(E->getInit(i), sInt, Info))
432 return APValue();
433 Elements.push_back(APValue(sInt));
434 } else {
435 llvm::APFloat f(0.0);
436 if (!EvaluateFloat(E->getInit(i), f, Info))
437 return APValue();
438 Elements.push_back(APValue(f));
439 }
440 }
441 return APValue(&Elements[0], Elements.size());
442}
443
444//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000445// Integer Evaluation
446//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000447
448namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000449class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000450 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000451 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000452 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000453public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000454 IntExprEvaluator(EvalInfo &info, APSInt &result)
455 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000456
Chris Lattner7a767782008-07-11 19:24:49 +0000457 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000458 return (unsigned)Info.Ctx.getIntWidth(T);
459 }
460
Anders Carlsson82206e22008-11-30 18:14:57 +0000461 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlsson54da0492008-11-30 16:38:33 +0000462 Info.EvalResult.DiagLoc = L;
463 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000464 Info.EvalResult.DiagExpr = E;
Chris Lattner54176fd2008-07-12 00:14:42 +0000465 return true; // still a constant.
466 }
467
Anders Carlsson82206e22008-11-30 18:14:57 +0000468 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000469 // If this is in an unevaluated portion of the subexpression, ignore the
470 // error.
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000471 if (Info.ShortCircuit) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000472 // If error is ignored because the value isn't evaluated, get the real
473 // type at least to prevent errors downstream.
Anders Carlsson82206e22008-11-30 18:14:57 +0000474 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
475 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000476 return true;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000477 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000478
Chris Lattner32fea9d2008-11-12 07:43:42 +0000479 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000480 if (Info.EvalResult.Diag == 0) {
481 Info.EvalResult.DiagLoc = L;
482 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000483 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000484 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000485 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000486 }
487
Anders Carlssonc754aa62008-07-08 05:13:58 +0000488 //===--------------------------------------------------------------------===//
489 // Visitor Methods
490 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000491
492 bool VisitStmt(Stmt *) {
493 assert(0 && "This should be called on integers, stmts are not integers");
494 return false;
495 }
Chris Lattner7a767782008-07-11 19:24:49 +0000496
Chris Lattner32fea9d2008-11-12 07:43:42 +0000497 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000498 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000499 }
500
Chris Lattnerb542afe2008-07-11 19:10:17 +0000501 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000502
Chris Lattner4c4867e2008-07-12 00:38:25 +0000503 bool VisitIntegerLiteral(const IntegerLiteral *E) {
504 Result = E->getValue();
505 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
506 return true;
507 }
508 bool VisitCharacterLiteral(const CharacterLiteral *E) {
509 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
510 Result = E->getValue();
511 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
512 return true;
513 }
514 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
515 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarac620de2008-10-24 08:07:57 +0000516 // Per gcc docs "this built-in function ignores top level
517 // qualifiers". We need to use the canonical version to properly
518 // be able to strip CRV qualifiers from the type.
519 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
520 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
521 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
522 T1.getUnqualifiedType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000523 return true;
524 }
525 bool VisitDeclRefExpr(const DeclRefExpr *E);
526 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000527 bool VisitBinaryOperator(const BinaryOperator *E);
528 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000529 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000530
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000531 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000532 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
533
Anders Carlsson3068d112008-11-16 19:01:22 +0000534 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000535 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson3068d112008-11-16 19:01:22 +0000536 Result = E->getValue();
537 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
538 return true;
539 }
540
Anders Carlsson3f704562008-12-21 22:39:40 +0000541 bool VisitGNUNullExpr(const GNUNullExpr *E) {
542 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
543 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
544 return true;
545 }
546
Anders Carlsson3068d112008-11-16 19:01:22 +0000547 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
548 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
549 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
550 return true;
551 }
552
Sebastian Redl64b45f72009-01-05 20:52:13 +0000553 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
554 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
555 Result = E->Evaluate();
556 return true;
557 }
558
Chris Lattnerfcee0012008-07-11 21:24:13 +0000559private:
Chris Lattneraf707ab2009-01-24 21:53:27 +0000560 unsigned GetAlignOfExpr(const Expr *E);
561 unsigned GetAlignOfType(QualType T);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000562};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000563} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000564
Chris Lattner87eae5e2008-07-11 22:52:41 +0000565static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
566 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000567}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000568
Chris Lattner4c4867e2008-07-12 00:38:25 +0000569bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
570 // Enums are integer constant exprs.
571 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
572 Result = D->getInitVal();
Eli Friedmane9a0f432008-12-08 02:21:03 +0000573 // FIXME: This is an ugly hack around the fact that enums don't set their
574 // signedness consistently; see PR3173
575 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000576 return true;
577 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000578
579 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
580 if (Info.Ctx.getLangOptions().CPlusPlus &&
581 E->getType().getCVRQualifiers() == QualType::Const) {
582 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
583 if (const Expr *Init = D->getInit())
584 return Visit(const_cast<Expr*>(Init));
585 }
586 }
587
Chris Lattner4c4867e2008-07-12 00:38:25 +0000588 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000589 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000590}
591
Chris Lattnera4d55d82008-10-06 06:40:35 +0000592/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
593/// as GCC.
594static int EvaluateBuiltinClassifyType(const CallExpr *E) {
595 // The following enum mimics the values returned by GCC.
596 enum gcc_type_class {
597 no_type_class = -1,
598 void_type_class, integer_type_class, char_type_class,
599 enumeral_type_class, boolean_type_class,
600 pointer_type_class, reference_type_class, offset_type_class,
601 real_type_class, complex_type_class,
602 function_type_class, method_type_class,
603 record_type_class, union_type_class,
604 array_type_class, string_type_class,
605 lang_type_class
606 };
607
608 // If no argument was supplied, default to "no_type_class". This isn't
609 // ideal, however it is what gcc does.
610 if (E->getNumArgs() == 0)
611 return no_type_class;
612
613 QualType ArgTy = E->getArg(0)->getType();
614 if (ArgTy->isVoidType())
615 return void_type_class;
616 else if (ArgTy->isEnumeralType())
617 return enumeral_type_class;
618 else if (ArgTy->isBooleanType())
619 return boolean_type_class;
620 else if (ArgTy->isCharType())
621 return string_type_class; // gcc doesn't appear to use char_type_class
622 else if (ArgTy->isIntegerType())
623 return integer_type_class;
624 else if (ArgTy->isPointerType())
625 return pointer_type_class;
626 else if (ArgTy->isReferenceType())
627 return reference_type_class;
628 else if (ArgTy->isRealType())
629 return real_type_class;
630 else if (ArgTy->isComplexType())
631 return complex_type_class;
632 else if (ArgTy->isFunctionType())
633 return function_type_class;
634 else if (ArgTy->isStructureType())
635 return record_type_class;
636 else if (ArgTy->isUnionType())
637 return union_type_class;
638 else if (ArgTy->isArrayType())
639 return array_type_class;
640 else if (ArgTy->isUnionType())
641 return union_type_class;
642 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
643 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
644 return -1;
645}
646
Chris Lattner4c4867e2008-07-12 00:38:25 +0000647bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
648 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000649
Douglas Gregor3c385e52009-02-14 18:57:46 +0000650 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000651 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000652 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000653 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000654 Result.setIsSigned(true);
655 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000656 return true;
657
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000658 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +0000659 // __builtin_constant_p always has one operand: it returns true if that
660 // operand can be folded, false otherwise.
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000661 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner019f4e82008-10-06 05:28:25 +0000662 return true;
663 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000664}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000665
Chris Lattnerb542afe2008-07-11 19:10:17 +0000666bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000667 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +0000668 if (!Visit(E->getRHS()))
669 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000670
671 if (!Info.ShortCircuit) {
672 // If we can't evaluate the LHS, it must be because it has
673 // side effects.
674 if (!E->getLHS()->isEvaluatable(Info.Ctx))
675 Info.EvalResult.HasSideEffects = true;
676
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000677 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000678 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000679
Anders Carlsson027f62e2008-12-01 02:07:06 +0000680 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000681 }
682
683 if (E->isLogicalOp()) {
684 // These need to be handled specially because the operands aren't
685 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000686 bool lhsResult, rhsResult;
Anders Carlsson51fe9962008-11-22 21:04:56 +0000687
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000688 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +0000689 // We were able to evaluate the LHS, see if we can get away with not
690 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000691 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
692 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000693 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
694 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000695 Result = lhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000696
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000697 Info.ShortCircuit++;
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000698 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000699 Info.ShortCircuit--;
700
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000701 if (rhsEvaluated)
702 return true;
703
704 // FIXME: Return an extension warning saying that the RHS could not be
705 // evaluated.
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000706 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000707 }
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000708
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000709 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000710 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
711 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
712 if (E->getOpcode() == BinaryOperator::LOr)
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000713 Result = lhsResult || rhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000714 else
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000715 Result = lhsResult && rhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000716 return true;
717 }
718 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000719 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000720 // We can't evaluate the LHS; however, sometimes the result
721 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000722 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
723 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000724 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
725 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000726 Result = rhsResult;
727
728 // Since we werent able to evaluate the left hand side, it
729 // must have had side effects.
730 Info.EvalResult.HasSideEffects = true;
731
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000732 return true;
733 }
734 }
Anders Carlsson51fe9962008-11-22 21:04:56 +0000735 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000736
Eli Friedmana6afa762008-11-13 06:09:17 +0000737 return false;
738 }
739
Anders Carlsson286f85e2008-11-16 07:17:21 +0000740 QualType LHSTy = E->getLHS()->getType();
741 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +0000742
743 if (LHSTy->isAnyComplexType()) {
744 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
745 APValue LHS, RHS;
746
747 if (!EvaluateComplex(E->getLHS(), LHS, Info))
748 return false;
749
750 if (!EvaluateComplex(E->getRHS(), RHS, Info))
751 return false;
752
753 if (LHS.isComplexFloat()) {
754 APFloat::cmpResult CR_r =
755 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
756 APFloat::cmpResult CR_i =
757 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
758
759 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
760 if (E->getOpcode() == BinaryOperator::EQ)
761 Result = (CR_r == APFloat::cmpEqual &&
762 CR_i == APFloat::cmpEqual);
763 else if (E->getOpcode() == BinaryOperator::NE)
764 Result = ((CR_r == APFloat::cmpGreaterThan ||
765 CR_r == APFloat::cmpLessThan) &&
766 (CR_i == APFloat::cmpGreaterThan ||
767 CR_i == APFloat::cmpLessThan));
768 else
769 assert(0 && "Invalid complex compartison.");
770 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
771 return true;
772 } else {
773 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
774 if (E->getOpcode() == BinaryOperator::EQ)
775 Result = (LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
776 LHS.getComplexIntImag() == RHS.getComplexIntImag());
777 else if (E->getOpcode() == BinaryOperator::NE)
778 Result = (LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
779 LHS.getComplexIntImag() != RHS.getComplexIntImag());
780 else
781 assert(0 && "Invalid complex compartison.");
782 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
783 return true;
784 }
785 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000786
787 if (LHSTy->isRealFloatingType() &&
788 RHSTy->isRealFloatingType()) {
789 APFloat RHS(0.0), LHS(0.0);
790
791 if (!EvaluateFloat(E->getRHS(), RHS, Info))
792 return false;
793
794 if (!EvaluateFloat(E->getLHS(), LHS, Info))
795 return false;
796
797 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +0000798
799 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
800
Anders Carlsson286f85e2008-11-16 07:17:21 +0000801 switch (E->getOpcode()) {
802 default:
803 assert(0 && "Invalid binary operator!");
804 case BinaryOperator::LT:
805 Result = CR == APFloat::cmpLessThan;
806 break;
807 case BinaryOperator::GT:
808 Result = CR == APFloat::cmpGreaterThan;
809 break;
810 case BinaryOperator::LE:
811 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
812 break;
813 case BinaryOperator::GE:
814 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
815 break;
816 case BinaryOperator::EQ:
817 Result = CR == APFloat::cmpEqual;
818 break;
819 case BinaryOperator::NE:
820 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
821 break;
822 }
823
Anders Carlsson286f85e2008-11-16 07:17:21 +0000824 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
825 return true;
826 }
827
Anders Carlsson3068d112008-11-16 19:01:22 +0000828 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000829 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000830 APValue LHSValue;
831 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
832 return false;
833
834 APValue RHSValue;
835 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
836 return false;
837
838 // FIXME: Is this correct? What if only one of the operands has a base?
839 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
840 return false;
841
842 const QualType Type = E->getLHS()->getType();
843 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
844
845 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
846 D /= Info.Ctx.getTypeSize(ElementType) / 8;
847
Anders Carlsson3068d112008-11-16 19:01:22 +0000848 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson529569e2008-11-16 22:46:56 +0000849 Result = D;
Anders Carlsson3068d112008-11-16 19:01:22 +0000850 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
851
852 return true;
853 }
854 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000855 if (!LHSTy->isIntegralType() ||
856 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000857 // We can't continue from here for non-integral types, and they
858 // could potentially confuse the following operations.
859 // FIXME: Deal with EQ and friends.
860 return false;
861 }
862
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000863 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000864 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000865 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000866 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000867 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000868
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000869
870 // FIXME Maybe we want to succeed even where we can't evaluate the
871 // right side of LAnd/LOr?
872 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000873 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000874 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000875
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000876 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000877 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000878 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner54176fd2008-07-12 00:14:42 +0000879 case BinaryOperator::Mul: Result *= RHS; return true;
880 case BinaryOperator::Add: Result += RHS; return true;
881 case BinaryOperator::Sub: Result -= RHS; return true;
882 case BinaryOperator::And: Result &= RHS; return true;
883 case BinaryOperator::Xor: Result ^= RHS; return true;
884 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000885 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000886 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000887 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000888 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000889 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000890 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000891 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000892 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000893 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000894 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000895 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000896 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000897 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000898 break;
899 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000900 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000901 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000902
Chris Lattnerac7cb602008-07-11 19:29:32 +0000903 case BinaryOperator::LT:
904 Result = Result < RHS;
905 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
906 break;
907 case BinaryOperator::GT:
908 Result = Result > RHS;
909 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
910 break;
911 case BinaryOperator::LE:
912 Result = Result <= RHS;
913 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
914 break;
915 case BinaryOperator::GE:
916 Result = Result >= RHS;
917 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
918 break;
919 case BinaryOperator::EQ:
920 Result = Result == RHS;
921 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
922 break;
923 case BinaryOperator::NE:
924 Result = Result != RHS;
925 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
926 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000927 case BinaryOperator::LAnd:
928 Result = Result != 0 && RHS != 0;
929 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
930 break;
931 case BinaryOperator::LOr:
932 Result = Result != 0 || RHS != 0;
933 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
934 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000935 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000936
937 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000938 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000939}
940
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000941bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +0000942 bool Cond;
943 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000944 return false;
945
Nuno Lopesa25bd552008-11-16 22:06:39 +0000946 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000947}
948
Chris Lattneraf707ab2009-01-24 21:53:27 +0000949unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere9feb472009-01-24 21:09:06 +0000950 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
951
952 // __alignof__(void) = 1 as a gcc extension.
953 if (Ty->isVoidType())
954 return 1;
955
956 // GCC extension: alignof(function) = 4.
957 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
958 // attribute(align) directive.
959 if (Ty->isFunctionType())
960 return 4;
961
962 if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty))
963 return GetAlignOfType(QualType(ASQT->getBaseType(), 0));
964
965 // alignof VLA/incomplete array.
966 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
967 return GetAlignOfType(VAT->getElementType());
968
969 // sizeof (objc class)?
970 if (isa<ObjCInterfaceType>(Ty))
971 return 1; // FIXME: This probably isn't right.
972
973 // Get information about the alignment.
974 unsigned CharSize = Info.Ctx.Target.getCharWidth();
975 return Info.Ctx.getTypeAlign(Ty) / CharSize;
976}
977
Chris Lattneraf707ab2009-01-24 21:53:27 +0000978unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
979 E = E->IgnoreParens();
980
981 // alignof decl is always accepted, even if it doesn't make sense: we default
982 // to 1 in those cases.
983 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
984 return Info.Ctx.getDeclAlign(DRE->getDecl());
985
986 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
987 return Info.Ctx.getDeclAlign(ME->getMemberDecl());
988
Chris Lattnere9feb472009-01-24 21:09:06 +0000989 return GetAlignOfType(E->getType());
990}
991
992
Sebastian Redl05189992008-11-11 17:56:53 +0000993/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
994/// expression's type.
995bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
996 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000997 // Return the result in the right width.
998 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
999 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
1000
Chris Lattnere9feb472009-01-24 21:09:06 +00001001 // Handle alignof separately.
1002 if (!E->isSizeOf()) {
1003 if (E->isArgumentType())
1004 Result = GetAlignOfType(E->getArgumentType());
1005 else
1006 Result = GetAlignOfExpr(E->getArgumentExpr());
1007 return true;
1008 }
1009
Sebastian Redl05189992008-11-11 17:56:53 +00001010 QualType SrcTy = E->getTypeOfArgument();
1011
Chris Lattnerfcee0012008-07-11 21:24:13 +00001012 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +00001013 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +00001014 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +00001015 return true;
1016 }
Chris Lattnerfcee0012008-07-11 21:24:13 +00001017
1018 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001019 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001020 return false;
Fariborz Jahanian67303c12009-01-16 01:42:12 +00001021
Chris Lattnerfcee0012008-07-11 21:24:13 +00001022 // GCC extension: sizeof(function) = 1.
1023 if (SrcTy->isFunctionType()) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001024 Result = 1;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001025 return true;
1026 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001027
1028 if (SrcTy->isObjCInterfaceType()) {
1029 // Slightly unusual case: the size of an ObjC interface type is the
1030 // size of the class. This code intentionally falls through to the normal
1031 // case.
1032 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
1033 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
1034 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
1035 }
1036
Chris Lattnere9feb472009-01-24 21:09:06 +00001037 // Get information about the size.
Chris Lattner87eae5e2008-07-11 22:52:41 +00001038 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnere9feb472009-01-24 21:09:06 +00001039 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001040 return true;
1041}
1042
Chris Lattnerb542afe2008-07-11 19:10:17 +00001043bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001044 // Special case unary operators that do not need their subexpression
1045 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +00001046 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001047 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +00001048 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +00001049 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1050 return true;
1051 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001052
1053 if (E->getOpcode() == UnaryOperator::LNot) {
1054 // LNot's operand isn't necessarily an integer, so we handle it specially.
1055 bool bres;
1056 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1057 return false;
1058 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
1059 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1060 Result = !bres;
1061 return true;
1062 }
1063
Chris Lattner87eae5e2008-07-11 22:52:41 +00001064 // Get the operand value into 'Result'.
1065 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001066 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001067
Chris Lattner75a48812008-07-11 22:15:16 +00001068 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001069 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001070 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1071 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001072 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001073 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001074 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1075 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +00001076 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001077 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +00001078 break;
1079 case UnaryOperator::Minus:
1080 Result = -Result;
1081 break;
1082 case UnaryOperator::Not:
1083 Result = ~Result;
1084 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001085 }
1086
1087 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +00001088 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001089}
1090
Chris Lattner732b2232008-07-12 01:15:53 +00001091/// HandleCast - This is used to evaluate implicit or explicit casts where the
1092/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001093bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001094 Expr *SubExpr = E->getSubExpr();
1095 QualType DestType = E->getType();
1096
Chris Lattner7a767782008-07-11 19:24:49 +00001097 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001098
Eli Friedman4efaa272008-11-12 09:44:48 +00001099 if (DestType->isBooleanType()) {
1100 bool BoolResult;
1101 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1102 return false;
1103 Result.zextOrTrunc(DestWidth);
1104 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1105 Result = BoolResult;
1106 return true;
1107 }
1108
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001109 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +00001110 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001111 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001112 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001113
1114 Result = HandleIntToIntCast(DestType, SubExpr->getType(), Result, Info.Ctx);
Chris Lattner732b2232008-07-12 01:15:53 +00001115 return true;
1116 }
1117
1118 // FIXME: Clean this up!
1119 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001120 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001121 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001122 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001123
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001124 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001125 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001126
Anders Carlsson559e56b2008-07-08 16:49:00 +00001127 Result.extOrTrunc(DestWidth);
1128 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +00001129 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1130 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +00001131 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001132
Chris Lattner732b2232008-07-12 01:15:53 +00001133 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001134 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001135
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001136 APFloat F(0.0);
1137 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001138 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001139
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001140 Result = HandleFloatToIntCast(DestType, SubExpr->getType(), F, Info.Ctx);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001141 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001142}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001143
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001144//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001145// Float Evaluation
1146//===----------------------------------------------------------------------===//
1147
1148namespace {
1149class VISIBILITY_HIDDEN FloatExprEvaluator
1150 : public StmtVisitor<FloatExprEvaluator, bool> {
1151 EvalInfo &Info;
1152 APFloat &Result;
1153public:
1154 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1155 : Info(info), Result(result) {}
1156
1157 bool VisitStmt(Stmt *S) {
1158 return false;
1159 }
1160
1161 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001162 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001163
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001164 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001165 bool VisitBinaryOperator(const BinaryOperator *E);
1166 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001167 bool VisitCastExpr(CastExpr *E);
1168 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001169};
1170} // end anonymous namespace
1171
1172static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1173 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1174}
1175
Chris Lattner019f4e82008-10-06 05:28:25 +00001176bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001177 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001178 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001179 case Builtin::BI__builtin_huge_val:
1180 case Builtin::BI__builtin_huge_valf:
1181 case Builtin::BI__builtin_huge_vall:
1182 case Builtin::BI__builtin_inf:
1183 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001184 case Builtin::BI__builtin_infl: {
1185 const llvm::fltSemantics &Sem =
1186 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001187 Result = llvm::APFloat::getInf(Sem);
1188 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001189 }
Chris Lattner9e621712008-10-06 06:31:58 +00001190
1191 case Builtin::BI__builtin_nan:
1192 case Builtin::BI__builtin_nanf:
1193 case Builtin::BI__builtin_nanl:
1194 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1195 // can't constant fold it.
1196 if (const StringLiteral *S =
1197 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1198 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001199 const llvm::fltSemantics &Sem =
1200 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +00001201 Result = llvm::APFloat::getNaN(Sem);
1202 return true;
1203 }
1204 }
1205 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001206
1207 case Builtin::BI__builtin_fabs:
1208 case Builtin::BI__builtin_fabsf:
1209 case Builtin::BI__builtin_fabsl:
1210 if (!EvaluateFloat(E->getArg(0), Result, Info))
1211 return false;
1212
1213 if (Result.isNegative())
1214 Result.changeSign();
1215 return true;
1216
1217 case Builtin::BI__builtin_copysign:
1218 case Builtin::BI__builtin_copysignf:
1219 case Builtin::BI__builtin_copysignl: {
1220 APFloat RHS(0.);
1221 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1222 !EvaluateFloat(E->getArg(1), RHS, Info))
1223 return false;
1224 Result.copySign(RHS);
1225 return true;
1226 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001227 }
1228}
1229
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001230bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001231 if (E->getOpcode() == UnaryOperator::Deref)
1232 return false;
1233
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001234 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1235 return false;
1236
1237 switch (E->getOpcode()) {
1238 default: return false;
1239 case UnaryOperator::Plus:
1240 return true;
1241 case UnaryOperator::Minus:
1242 Result.changeSign();
1243 return true;
1244 }
1245}
Chris Lattner019f4e82008-10-06 05:28:25 +00001246
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001247bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1248 // FIXME: Diagnostics? I really don't understand how the warnings
1249 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001250 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001251 if (!EvaluateFloat(E->getLHS(), Result, Info))
1252 return false;
1253 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1254 return false;
1255
1256 switch (E->getOpcode()) {
1257 default: return false;
1258 case BinaryOperator::Mul:
1259 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1260 return true;
1261 case BinaryOperator::Add:
1262 Result.add(RHS, APFloat::rmNearestTiesToEven);
1263 return true;
1264 case BinaryOperator::Sub:
1265 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1266 return true;
1267 case BinaryOperator::Div:
1268 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1269 return true;
1270 case BinaryOperator::Rem:
1271 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1272 return true;
1273 }
1274}
1275
1276bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1277 Result = E->getValue();
1278 return true;
1279}
1280
Eli Friedman4efaa272008-11-12 09:44:48 +00001281bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1282 Expr* SubExpr = E->getSubExpr();
Nate Begeman59b5da62009-01-18 03:20:47 +00001283
Eli Friedman4efaa272008-11-12 09:44:48 +00001284 if (SubExpr->getType()->isIntegralType()) {
1285 APSInt IntResult;
1286 if (!EvaluateInteger(E, IntResult, Info))
1287 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001288 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1289 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001290 return true;
1291 }
1292 if (SubExpr->getType()->isRealFloatingType()) {
1293 if (!Visit(SubExpr))
1294 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001295 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1296 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001297 return true;
1298 }
1299
1300 return false;
1301}
1302
1303bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1304 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1305 return true;
1306}
1307
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001308//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001309// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001310//===----------------------------------------------------------------------===//
1311
1312namespace {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001313class VISIBILITY_HIDDEN ComplexExprEvaluator
1314 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001315 EvalInfo &Info;
1316
1317public:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001318 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001319
1320 //===--------------------------------------------------------------------===//
1321 // Visitor Methods
1322 //===--------------------------------------------------------------------===//
1323
1324 APValue VisitStmt(Stmt *S) {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001325 return APValue();
1326 }
1327
1328 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1329
1330 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001331 Expr* SubExpr = E->getSubExpr();
1332
1333 if (SubExpr->getType()->isRealFloatingType()) {
1334 APFloat Result(0.0);
1335
1336 if (!EvaluateFloat(SubExpr, Result, Info))
1337 return APValue();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001338
Daniel Dunbar3f279872009-01-29 01:32:56 +00001339 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001340 Result);
1341 } else {
1342 assert(SubExpr->getType()->isIntegerType() &&
1343 "Unexpected imaginary literal.");
1344
1345 llvm::APSInt Result;
1346 if (!EvaluateInteger(SubExpr, Result, Info))
1347 return APValue();
1348
1349 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1350 Zero = 0;
1351 return APValue(Zero, Result);
1352 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001353 }
1354
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001355 APValue VisitCastExpr(CastExpr *E) {
1356 Expr* SubExpr = E->getSubExpr();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001357 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1358 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001359
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001360 if (SubType->isRealFloatingType()) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001361 APFloat Result(0.0);
1362
1363 if (!EvaluateFloat(SubExpr, Result, Info))
1364 return APValue();
1365
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001366 // Apply float conversion if necessary.
1367 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbar8f826f02009-01-24 19:08:01 +00001368 return APValue(Result,
Daniel Dunbar3f279872009-01-29 01:32:56 +00001369 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001370 } else if (SubType->isIntegerType()) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001371 APSInt Result;
1372
1373 if (!EvaluateInteger(SubExpr, Result, Info))
1374 return APValue();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001375
1376 // Apply integer conversion if necessary.
1377 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001378 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1379 Zero = 0;
1380 return APValue(Result, Zero);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001381 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1382 APValue Src;
1383
1384 if (!EvaluateComplex(SubExpr, Src, Info))
1385 return APValue();
1386
1387 QualType SrcType = CT->getElementType();
1388
1389 if (Src.isComplexFloat()) {
1390 if (EltType->isRealFloatingType()) {
1391 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1392 Src.getComplexFloatReal(),
1393 Info.Ctx),
1394 HandleFloatToFloatCast(EltType, SrcType,
1395 Src.getComplexFloatImag(),
1396 Info.Ctx));
1397 } else {
1398 return APValue(HandleFloatToIntCast(EltType, SrcType,
1399 Src.getComplexFloatReal(),
1400 Info.Ctx),
1401 HandleFloatToIntCast(EltType, SrcType,
1402 Src.getComplexFloatImag(),
1403 Info.Ctx));
1404 }
1405 } else {
1406 assert(Src.isComplexInt() && "Invalid evaluate result.");
1407 if (EltType->isRealFloatingType()) {
1408 return APValue(HandleIntToFloatCast(EltType, SrcType,
1409 Src.getComplexIntReal(),
1410 Info.Ctx),
1411 HandleIntToFloatCast(EltType, SrcType,
1412 Src.getComplexIntImag(),
1413 Info.Ctx));
1414 } else {
1415 return APValue(HandleIntToIntCast(EltType, SrcType,
1416 Src.getComplexIntReal(),
1417 Info.Ctx),
1418 HandleIntToIntCast(EltType, SrcType,
1419 Src.getComplexIntImag(),
1420 Info.Ctx));
1421 }
1422 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001423 }
1424
1425 // FIXME: Handle more casts.
1426 return APValue();
1427 }
1428
1429 APValue VisitBinaryOperator(const BinaryOperator *E);
1430
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001431};
1432} // end anonymous namespace
1433
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001434static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001435{
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001436 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1437 assert((!Result.isComplexFloat() ||
1438 (&Result.getComplexFloatReal().getSemantics() ==
1439 &Result.getComplexFloatImag().getSemantics())) &&
1440 "Invalid complex evaluation.");
1441 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001442}
1443
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001444APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001445{
1446 APValue Result, RHS;
1447
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001448 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001449 return APValue();
1450
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001451 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001452 return APValue();
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001453
Daniel Dunbar3f279872009-01-29 01:32:56 +00001454 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1455 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001456 switch (E->getOpcode()) {
1457 default: return APValue();
1458 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001459 if (Result.isComplexFloat()) {
1460 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1461 APFloat::rmNearestTiesToEven);
1462 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1463 APFloat::rmNearestTiesToEven);
1464 } else {
1465 Result.getComplexIntReal() += RHS.getComplexIntReal();
1466 Result.getComplexIntImag() += RHS.getComplexIntImag();
1467 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001468 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001469 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001470 if (Result.isComplexFloat()) {
1471 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1472 APFloat::rmNearestTiesToEven);
1473 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1474 APFloat::rmNearestTiesToEven);
1475 } else {
1476 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1477 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1478 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001479 break;
1480 case BinaryOperator::Mul:
1481 if (Result.isComplexFloat()) {
1482 APValue LHS = Result;
1483 APFloat &LHS_r = LHS.getComplexFloatReal();
1484 APFloat &LHS_i = LHS.getComplexFloatImag();
1485 APFloat &RHS_r = RHS.getComplexFloatReal();
1486 APFloat &RHS_i = RHS.getComplexFloatImag();
1487
1488 APFloat Tmp = LHS_r;
1489 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1490 Result.getComplexFloatReal() = Tmp;
1491 Tmp = LHS_i;
1492 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1493 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1494
1495 Tmp = LHS_r;
1496 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1497 Result.getComplexFloatImag() = Tmp;
1498 Tmp = LHS_i;
1499 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1500 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1501 } else {
1502 APValue LHS = Result;
1503 Result.getComplexIntReal() =
1504 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1505 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1506 Result.getComplexIntImag() =
1507 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1508 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1509 }
1510 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001511 }
1512
1513 return Result;
1514}
1515
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001516//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001517// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001518//===----------------------------------------------------------------------===//
1519
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001520/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner019f4e82008-10-06 05:28:25 +00001521/// any crazy technique (that has nothing to do with language standards) that
1522/// we want to. If this function returns true, it returns the folded constant
1523/// in Result.
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001524bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1525 EvalInfo Info(Ctx, Result);
Anders Carlsson54da0492008-11-30 16:38:33 +00001526
Nate Begeman59b5da62009-01-18 03:20:47 +00001527 if (getType()->isVectorType()) {
1528 if (!EvaluateVector(this, Result.Val, Info))
1529 return false;
1530 } else if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001531 llvm::APSInt sInt(32);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001532 if (!EvaluateInteger(this, sInt, Info))
1533 return false;
1534
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001535 Result.Val = APValue(sInt);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001536 } else if (getType()->isPointerType()) {
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001537 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001538 return false;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001539 } else if (getType()->isRealFloatingType()) {
1540 llvm::APFloat f(0.0);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001541 if (!EvaluateFloat(this, f, Info))
1542 return false;
1543
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001544 Result.Val = APValue(f);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001545 } else if (getType()->isAnyComplexType()) {
1546 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001547 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001548 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00001549 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001550
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001551 return true;
1552}
1553
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001554/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001555/// folded, but discard the result.
1556bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001557 EvalResult Result;
1558 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001559}
Anders Carlsson51fe9962008-11-22 21:04:56 +00001560
1561APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001562 EvalResult EvalResult;
1563 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00001564 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00001565 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001566 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00001567
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001568 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00001569}