blob: eae3f64ac96352a1862e7d27d4fedf1b022cca02 [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) {
353 if (E->isBuiltinCall() == Builtin::BI__builtin___CFStringMakeConstantString)
354 return APValue(E, 0);
355 return APValue();
356}
357
Eli Friedman4efaa272008-11-12 09:44:48 +0000358APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
359 bool BoolResult;
360 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
361 return APValue();
362
363 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
364
365 APValue Result;
366 if (EvaluatePointer(EvalExpr, Result, Info))
367 return Result;
368 return APValue();
369}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000370
371//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000372// Vector Evaluation
373//===----------------------------------------------------------------------===//
374
375namespace {
376 class VISIBILITY_HIDDEN VectorExprEvaluator
377 : public StmtVisitor<VectorExprEvaluator, APValue> {
378 EvalInfo &Info;
379 public:
380
381 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
382
383 APValue VisitStmt(Stmt *S) {
384 return APValue();
385 }
386
387 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
388 APValue VisitCastExpr(const CastExpr* E);
389 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
390 APValue VisitInitListExpr(const InitListExpr *E);
391 };
392} // end anonymous namespace
393
394static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
395 if (!E->getType()->isVectorType())
396 return false;
397 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
398 return !Result.isUninit();
399}
400
401APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
402 const Expr* SE = E->getSubExpr();
403
404 // Check for vector->vector bitcast.
405 if (SE->getType()->isVectorType())
406 return this->Visit(const_cast<Expr*>(SE));
407
408 return APValue();
409}
410
411APValue
412VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
413 return this->Visit(const_cast<Expr*>(E->getInitializer()));
414}
415
416APValue
417VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
418 const VectorType *VT = E->getType()->getAsVectorType();
419 unsigned NumInits = E->getNumInits();
420
421 if (!VT || VT->getNumElements() != NumInits)
422 return APValue();
423
424 QualType EltTy = VT->getElementType();
425 llvm::SmallVector<APValue, 4> Elements;
426
427 for (unsigned i = 0; i < NumInits; i++) {
428 if (EltTy->isIntegerType()) {
429 llvm::APSInt sInt(32);
430 if (!EvaluateInteger(E->getInit(i), sInt, Info))
431 return APValue();
432 Elements.push_back(APValue(sInt));
433 } else {
434 llvm::APFloat f(0.0);
435 if (!EvaluateFloat(E->getInit(i), f, Info))
436 return APValue();
437 Elements.push_back(APValue(f));
438 }
439 }
440 return APValue(&Elements[0], Elements.size());
441}
442
443//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000444// Integer Evaluation
445//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000446
447namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000448class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000449 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000450 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000451 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000452public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000453 IntExprEvaluator(EvalInfo &info, APSInt &result)
454 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000455
Chris Lattner7a767782008-07-11 19:24:49 +0000456 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000457 return (unsigned)Info.Ctx.getIntWidth(T);
458 }
459
Anders Carlsson82206e22008-11-30 18:14:57 +0000460 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlsson54da0492008-11-30 16:38:33 +0000461 Info.EvalResult.DiagLoc = L;
462 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000463 Info.EvalResult.DiagExpr = E;
Chris Lattner54176fd2008-07-12 00:14:42 +0000464 return true; // still a constant.
465 }
466
Anders Carlsson82206e22008-11-30 18:14:57 +0000467 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000468 // If this is in an unevaluated portion of the subexpression, ignore the
469 // error.
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000470 if (Info.ShortCircuit) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000471 // If error is ignored because the value isn't evaluated, get the real
472 // type at least to prevent errors downstream.
Anders Carlsson82206e22008-11-30 18:14:57 +0000473 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
474 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000475 return true;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000476 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000477
Chris Lattner32fea9d2008-11-12 07:43:42 +0000478 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000479 if (Info.EvalResult.Diag == 0) {
480 Info.EvalResult.DiagLoc = L;
481 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000482 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000483 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000484 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000485 }
486
Anders Carlssonc754aa62008-07-08 05:13:58 +0000487 //===--------------------------------------------------------------------===//
488 // Visitor Methods
489 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000490
491 bool VisitStmt(Stmt *) {
492 assert(0 && "This should be called on integers, stmts are not integers");
493 return false;
494 }
Chris Lattner7a767782008-07-11 19:24:49 +0000495
Chris Lattner32fea9d2008-11-12 07:43:42 +0000496 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000497 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000498 }
499
Chris Lattnerb542afe2008-07-11 19:10:17 +0000500 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000501
Chris Lattner4c4867e2008-07-12 00:38:25 +0000502 bool VisitIntegerLiteral(const IntegerLiteral *E) {
503 Result = E->getValue();
504 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
505 return true;
506 }
507 bool VisitCharacterLiteral(const CharacterLiteral *E) {
508 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
509 Result = E->getValue();
510 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
511 return true;
512 }
513 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
514 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarac620de2008-10-24 08:07:57 +0000515 // Per gcc docs "this built-in function ignores top level
516 // qualifiers". We need to use the canonical version to properly
517 // be able to strip CRV qualifiers from the type.
518 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
519 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
520 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
521 T1.getUnqualifiedType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000522 return true;
523 }
524 bool VisitDeclRefExpr(const DeclRefExpr *E);
525 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000526 bool VisitBinaryOperator(const BinaryOperator *E);
527 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000528 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000529
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000530 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000531 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
532
Anders Carlsson3068d112008-11-16 19:01:22 +0000533 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000534 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson3068d112008-11-16 19:01:22 +0000535 Result = E->getValue();
536 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
537 return true;
538 }
539
Anders Carlsson3f704562008-12-21 22:39:40 +0000540 bool VisitGNUNullExpr(const GNUNullExpr *E) {
541 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
542 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
543 return true;
544 }
545
Anders Carlsson3068d112008-11-16 19:01:22 +0000546 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
547 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
548 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
549 return true;
550 }
551
Sebastian Redl64b45f72009-01-05 20:52:13 +0000552 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
553 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
554 Result = E->Evaluate();
555 return true;
556 }
557
Chris Lattnerfcee0012008-07-11 21:24:13 +0000558private:
Chris Lattneraf707ab2009-01-24 21:53:27 +0000559 unsigned GetAlignOfExpr(const Expr *E);
560 unsigned GetAlignOfType(QualType T);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000561};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000562} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000563
Chris Lattner87eae5e2008-07-11 22:52:41 +0000564static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
565 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000566}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000567
Chris Lattner4c4867e2008-07-12 00:38:25 +0000568bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
569 // Enums are integer constant exprs.
570 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
571 Result = D->getInitVal();
Eli Friedmane9a0f432008-12-08 02:21:03 +0000572 // FIXME: This is an ugly hack around the fact that enums don't set their
573 // signedness consistently; see PR3173
574 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000575 return true;
576 }
577
578 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000579 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000580}
581
Chris Lattnera4d55d82008-10-06 06:40:35 +0000582/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
583/// as GCC.
584static int EvaluateBuiltinClassifyType(const CallExpr *E) {
585 // The following enum mimics the values returned by GCC.
586 enum gcc_type_class {
587 no_type_class = -1,
588 void_type_class, integer_type_class, char_type_class,
589 enumeral_type_class, boolean_type_class,
590 pointer_type_class, reference_type_class, offset_type_class,
591 real_type_class, complex_type_class,
592 function_type_class, method_type_class,
593 record_type_class, union_type_class,
594 array_type_class, string_type_class,
595 lang_type_class
596 };
597
598 // If no argument was supplied, default to "no_type_class". This isn't
599 // ideal, however it is what gcc does.
600 if (E->getNumArgs() == 0)
601 return no_type_class;
602
603 QualType ArgTy = E->getArg(0)->getType();
604 if (ArgTy->isVoidType())
605 return void_type_class;
606 else if (ArgTy->isEnumeralType())
607 return enumeral_type_class;
608 else if (ArgTy->isBooleanType())
609 return boolean_type_class;
610 else if (ArgTy->isCharType())
611 return string_type_class; // gcc doesn't appear to use char_type_class
612 else if (ArgTy->isIntegerType())
613 return integer_type_class;
614 else if (ArgTy->isPointerType())
615 return pointer_type_class;
616 else if (ArgTy->isReferenceType())
617 return reference_type_class;
618 else if (ArgTy->isRealType())
619 return real_type_class;
620 else if (ArgTy->isComplexType())
621 return complex_type_class;
622 else if (ArgTy->isFunctionType())
623 return function_type_class;
624 else if (ArgTy->isStructureType())
625 return record_type_class;
626 else if (ArgTy->isUnionType())
627 return union_type_class;
628 else if (ArgTy->isArrayType())
629 return array_type_class;
630 else if (ArgTy->isUnionType())
631 return union_type_class;
632 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
633 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
634 return -1;
635}
636
Chris Lattner4c4867e2008-07-12 00:38:25 +0000637bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
638 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000639
Chris Lattner019f4e82008-10-06 05:28:25 +0000640 switch (E->isBuiltinCall()) {
641 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000642 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000643 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000644 Result.setIsSigned(true);
645 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000646 return true;
647
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000648 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +0000649 // __builtin_constant_p always has one operand: it returns true if that
650 // operand can be folded, false otherwise.
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000651 Result = E->getArg(0)->isEvaluatable(Info.Ctx);
Chris Lattner019f4e82008-10-06 05:28:25 +0000652 return true;
653 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000654}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000655
Chris Lattnerb542afe2008-07-11 19:10:17 +0000656bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000657 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +0000658 if (!Visit(E->getRHS()))
659 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000660
661 if (!Info.ShortCircuit) {
662 // If we can't evaluate the LHS, it must be because it has
663 // side effects.
664 if (!E->getLHS()->isEvaluatable(Info.Ctx))
665 Info.EvalResult.HasSideEffects = true;
666
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000667 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson4fdfb092008-12-01 06:44:05 +0000668 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000669
Anders Carlsson027f62e2008-12-01 02:07:06 +0000670 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000671 }
672
673 if (E->isLogicalOp()) {
674 // These need to be handled specially because the operands aren't
675 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000676 bool lhsResult, rhsResult;
Anders Carlsson51fe9962008-11-22 21:04:56 +0000677
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000678 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +0000679 // We were able to evaluate the LHS, see if we can get away with not
680 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000681 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
682 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000683 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
684 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000685 Result = lhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000686
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000687 Info.ShortCircuit++;
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000688 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +0000689 Info.ShortCircuit--;
690
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000691 if (rhsEvaluated)
692 return true;
693
694 // FIXME: Return an extension warning saying that the RHS could not be
695 // evaluated.
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000696 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +0000697 }
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000698
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000699 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000700 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
701 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
702 if (E->getOpcode() == BinaryOperator::LOr)
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000703 Result = lhsResult || rhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000704 else
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000705 Result = lhsResult && rhsResult;
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000706 return true;
707 }
708 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000709 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000710 // We can't evaluate the LHS; however, sometimes the result
711 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000712 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
713 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000714 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
715 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Anders Carlssonfcb4d092008-11-30 16:51:17 +0000716 Result = rhsResult;
717
718 // Since we werent able to evaluate the left hand side, it
719 // must have had side effects.
720 Info.EvalResult.HasSideEffects = true;
721
Anders Carlsson4bbc0e02008-11-24 04:21:33 +0000722 return true;
723 }
724 }
Anders Carlsson51fe9962008-11-22 21:04:56 +0000725 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000726
Eli Friedmana6afa762008-11-13 06:09:17 +0000727 return false;
728 }
729
Anders Carlsson286f85e2008-11-16 07:17:21 +0000730 QualType LHSTy = E->getLHS()->getType();
731 QualType RHSTy = E->getRHS()->getType();
732
733 if (LHSTy->isRealFloatingType() &&
734 RHSTy->isRealFloatingType()) {
735 APFloat RHS(0.0), LHS(0.0);
736
737 if (!EvaluateFloat(E->getRHS(), RHS, Info))
738 return false;
739
740 if (!EvaluateFloat(E->getLHS(), LHS, Info))
741 return false;
742
743 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +0000744
745 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
746
Anders Carlsson286f85e2008-11-16 07:17:21 +0000747 switch (E->getOpcode()) {
748 default:
749 assert(0 && "Invalid binary operator!");
750 case BinaryOperator::LT:
751 Result = CR == APFloat::cmpLessThan;
752 break;
753 case BinaryOperator::GT:
754 Result = CR == APFloat::cmpGreaterThan;
755 break;
756 case BinaryOperator::LE:
757 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
758 break;
759 case BinaryOperator::GE:
760 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
761 break;
762 case BinaryOperator::EQ:
763 Result = CR == APFloat::cmpEqual;
764 break;
765 case BinaryOperator::NE:
766 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
767 break;
768 }
769
Anders Carlsson286f85e2008-11-16 07:17:21 +0000770 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
771 return true;
772 }
773
Anders Carlsson3068d112008-11-16 19:01:22 +0000774 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson529569e2008-11-16 22:46:56 +0000775 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000776 APValue LHSValue;
777 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
778 return false;
779
780 APValue RHSValue;
781 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
782 return false;
783
784 // FIXME: Is this correct? What if only one of the operands has a base?
785 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
786 return false;
787
788 const QualType Type = E->getLHS()->getType();
789 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
790
791 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
792 D /= Info.Ctx.getTypeSize(ElementType) / 8;
793
Anders Carlsson3068d112008-11-16 19:01:22 +0000794 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson529569e2008-11-16 22:46:56 +0000795 Result = D;
Anders Carlsson3068d112008-11-16 19:01:22 +0000796 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
797
798 return true;
799 }
800 }
Anders Carlsson286f85e2008-11-16 07:17:21 +0000801 if (!LHSTy->isIntegralType() ||
802 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000803 // We can't continue from here for non-integral types, and they
804 // could potentially confuse the following operations.
805 // FIXME: Deal with EQ and friends.
806 return false;
807 }
808
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000809 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000810 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000811 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000812 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000813 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000814
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000815
816 // FIXME Maybe we want to succeed even where we can't evaluate the
817 // right side of LAnd/LOr?
818 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000819 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000820 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000821
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000822 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000823 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000824 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner54176fd2008-07-12 00:14:42 +0000825 case BinaryOperator::Mul: Result *= RHS; return true;
826 case BinaryOperator::Add: Result += RHS; return true;
827 case BinaryOperator::Sub: Result -= RHS; return true;
828 case BinaryOperator::And: Result &= RHS; return true;
829 case BinaryOperator::Xor: Result ^= RHS; return true;
830 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000831 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000832 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000833 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000834 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000835 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000836 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000837 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000838 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner75a48812008-07-11 22:15:16 +0000839 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000840 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000841 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000842 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000843 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000844 break;
845 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000846 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000847 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000848
Chris Lattnerac7cb602008-07-11 19:29:32 +0000849 case BinaryOperator::LT:
850 Result = Result < RHS;
851 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
852 break;
853 case BinaryOperator::GT:
854 Result = Result > RHS;
855 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
856 break;
857 case BinaryOperator::LE:
858 Result = Result <= RHS;
859 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
860 break;
861 case BinaryOperator::GE:
862 Result = Result >= RHS;
863 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
864 break;
865 case BinaryOperator::EQ:
866 Result = Result == RHS;
867 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
868 break;
869 case BinaryOperator::NE:
870 Result = Result != RHS;
871 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
872 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000873 case BinaryOperator::LAnd:
874 Result = Result != 0 && RHS != 0;
875 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
876 break;
877 case BinaryOperator::LOr:
878 Result = Result != 0 || RHS != 0;
879 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
880 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000881 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000882
883 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000884 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000885}
886
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000887bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +0000888 bool Cond;
889 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000890 return false;
891
Nuno Lopesa25bd552008-11-16 22:06:39 +0000892 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000893}
894
Chris Lattneraf707ab2009-01-24 21:53:27 +0000895unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere9feb472009-01-24 21:09:06 +0000896 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
897
898 // __alignof__(void) = 1 as a gcc extension.
899 if (Ty->isVoidType())
900 return 1;
901
902 // GCC extension: alignof(function) = 4.
903 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
904 // attribute(align) directive.
905 if (Ty->isFunctionType())
906 return 4;
907
908 if (const ASQualType *ASQT = dyn_cast<ASQualType>(Ty))
909 return GetAlignOfType(QualType(ASQT->getBaseType(), 0));
910
911 // alignof VLA/incomplete array.
912 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
913 return GetAlignOfType(VAT->getElementType());
914
915 // sizeof (objc class)?
916 if (isa<ObjCInterfaceType>(Ty))
917 return 1; // FIXME: This probably isn't right.
918
919 // Get information about the alignment.
920 unsigned CharSize = Info.Ctx.Target.getCharWidth();
921 return Info.Ctx.getTypeAlign(Ty) / CharSize;
922}
923
Chris Lattneraf707ab2009-01-24 21:53:27 +0000924unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
925 E = E->IgnoreParens();
926
927 // alignof decl is always accepted, even if it doesn't make sense: we default
928 // to 1 in those cases.
929 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
930 return Info.Ctx.getDeclAlign(DRE->getDecl());
931
932 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
933 return Info.Ctx.getDeclAlign(ME->getMemberDecl());
934
Chris Lattnere9feb472009-01-24 21:09:06 +0000935 return GetAlignOfType(E->getType());
936}
937
938
Sebastian Redl05189992008-11-11 17:56:53 +0000939/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
940/// expression's type.
941bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
942 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000943 // Return the result in the right width.
944 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
945 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
946
Chris Lattnere9feb472009-01-24 21:09:06 +0000947 // Handle alignof separately.
948 if (!E->isSizeOf()) {
949 if (E->isArgumentType())
950 Result = GetAlignOfType(E->getArgumentType());
951 else
952 Result = GetAlignOfExpr(E->getArgumentExpr());
953 return true;
954 }
955
Sebastian Redl05189992008-11-11 17:56:53 +0000956 QualType SrcTy = E->getTypeOfArgument();
957
Chris Lattnerfcee0012008-07-11 21:24:13 +0000958 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +0000959 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +0000960 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +0000961 return true;
962 }
Chris Lattnerfcee0012008-07-11 21:24:13 +0000963
964 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +0000965 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +0000966 return false;
Fariborz Jahanian67303c12009-01-16 01:42:12 +0000967
Chris Lattnerfcee0012008-07-11 21:24:13 +0000968 // GCC extension: sizeof(function) = 1.
969 if (SrcTy->isFunctionType()) {
Chris Lattnere9feb472009-01-24 21:09:06 +0000970 Result = 1;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000971 return true;
972 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000973
974 if (SrcTy->isObjCInterfaceType()) {
975 // Slightly unusual case: the size of an ObjC interface type is the
976 // size of the class. This code intentionally falls through to the normal
977 // case.
978 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
979 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
980 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
981 }
982
Chris Lattnere9feb472009-01-24 21:09:06 +0000983 // Get information about the size.
Chris Lattner87eae5e2008-07-11 22:52:41 +0000984 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnere9feb472009-01-24 21:09:06 +0000985 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000986 return true;
987}
988
Chris Lattnerb542afe2008-07-11 19:10:17 +0000989bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000990 // Special case unary operators that do not need their subexpression
991 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +0000992 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000993 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +0000994 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +0000995 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
996 return true;
997 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000998
999 if (E->getOpcode() == UnaryOperator::LNot) {
1000 // LNot's operand isn't necessarily an integer, so we handle it specially.
1001 bool bres;
1002 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1003 return false;
1004 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
1005 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
1006 Result = !bres;
1007 return true;
1008 }
1009
Chris Lattner87eae5e2008-07-11 22:52:41 +00001010 // Get the operand value into 'Result'.
1011 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001012 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001013
Chris Lattner75a48812008-07-11 22:15:16 +00001014 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001015 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001016 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1017 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001018 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001019 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001020 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1021 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +00001022 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001023 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +00001024 break;
1025 case UnaryOperator::Minus:
1026 Result = -Result;
1027 break;
1028 case UnaryOperator::Not:
1029 Result = ~Result;
1030 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001031 }
1032
1033 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +00001034 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001035}
1036
Chris Lattner732b2232008-07-12 01:15:53 +00001037/// HandleCast - This is used to evaluate implicit or explicit casts where the
1038/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001039bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001040 Expr *SubExpr = E->getSubExpr();
1041 QualType DestType = E->getType();
1042
Chris Lattner7a767782008-07-11 19:24:49 +00001043 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001044
Eli Friedman4efaa272008-11-12 09:44:48 +00001045 if (DestType->isBooleanType()) {
1046 bool BoolResult;
1047 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1048 return false;
1049 Result.zextOrTrunc(DestWidth);
1050 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1051 Result = BoolResult;
1052 return true;
1053 }
1054
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001055 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +00001056 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001057 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001058 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001059
1060 Result = HandleIntToIntCast(DestType, SubExpr->getType(), Result, Info.Ctx);
Chris Lattner732b2232008-07-12 01:15:53 +00001061 return true;
1062 }
1063
1064 // FIXME: Clean this up!
1065 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001066 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001067 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001068 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001069
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001070 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001071 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001072
Anders Carlsson559e56b2008-07-08 16:49:00 +00001073 Result.extOrTrunc(DestWidth);
1074 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +00001075 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
1076 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +00001077 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001078
Chris Lattner732b2232008-07-12 01:15:53 +00001079 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001080 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001081
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001082 APFloat F(0.0);
1083 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001084 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001085
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001086 Result = HandleFloatToIntCast(DestType, SubExpr->getType(), F, Info.Ctx);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001087 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001088}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001089
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001090//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001091// Float Evaluation
1092//===----------------------------------------------------------------------===//
1093
1094namespace {
1095class VISIBILITY_HIDDEN FloatExprEvaluator
1096 : public StmtVisitor<FloatExprEvaluator, bool> {
1097 EvalInfo &Info;
1098 APFloat &Result;
1099public:
1100 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1101 : Info(info), Result(result) {}
1102
1103 bool VisitStmt(Stmt *S) {
1104 return false;
1105 }
1106
1107 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001108 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001109
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001110 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001111 bool VisitBinaryOperator(const BinaryOperator *E);
1112 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001113 bool VisitCastExpr(CastExpr *E);
1114 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001115};
1116} // end anonymous namespace
1117
1118static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1119 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1120}
1121
Chris Lattner019f4e82008-10-06 05:28:25 +00001122bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001123 switch (E->isBuiltinCall()) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001124 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001125 case Builtin::BI__builtin_huge_val:
1126 case Builtin::BI__builtin_huge_valf:
1127 case Builtin::BI__builtin_huge_vall:
1128 case Builtin::BI__builtin_inf:
1129 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001130 case Builtin::BI__builtin_infl: {
1131 const llvm::fltSemantics &Sem =
1132 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001133 Result = llvm::APFloat::getInf(Sem);
1134 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001135 }
Chris Lattner9e621712008-10-06 06:31:58 +00001136
1137 case Builtin::BI__builtin_nan:
1138 case Builtin::BI__builtin_nanf:
1139 case Builtin::BI__builtin_nanl:
1140 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1141 // can't constant fold it.
1142 if (const StringLiteral *S =
1143 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1144 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001145 const llvm::fltSemantics &Sem =
1146 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +00001147 Result = llvm::APFloat::getNaN(Sem);
1148 return true;
1149 }
1150 }
1151 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001152
1153 case Builtin::BI__builtin_fabs:
1154 case Builtin::BI__builtin_fabsf:
1155 case Builtin::BI__builtin_fabsl:
1156 if (!EvaluateFloat(E->getArg(0), Result, Info))
1157 return false;
1158
1159 if (Result.isNegative())
1160 Result.changeSign();
1161 return true;
1162
1163 case Builtin::BI__builtin_copysign:
1164 case Builtin::BI__builtin_copysignf:
1165 case Builtin::BI__builtin_copysignl: {
1166 APFloat RHS(0.);
1167 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1168 !EvaluateFloat(E->getArg(1), RHS, Info))
1169 return false;
1170 Result.copySign(RHS);
1171 return true;
1172 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001173 }
1174}
1175
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001176bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001177 if (E->getOpcode() == UnaryOperator::Deref)
1178 return false;
1179
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001180 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1181 return false;
1182
1183 switch (E->getOpcode()) {
1184 default: return false;
1185 case UnaryOperator::Plus:
1186 return true;
1187 case UnaryOperator::Minus:
1188 Result.changeSign();
1189 return true;
1190 }
1191}
Chris Lattner019f4e82008-10-06 05:28:25 +00001192
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001193bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1194 // FIXME: Diagnostics? I really don't understand how the warnings
1195 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001196 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001197 if (!EvaluateFloat(E->getLHS(), Result, Info))
1198 return false;
1199 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1200 return false;
1201
1202 switch (E->getOpcode()) {
1203 default: return false;
1204 case BinaryOperator::Mul:
1205 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1206 return true;
1207 case BinaryOperator::Add:
1208 Result.add(RHS, APFloat::rmNearestTiesToEven);
1209 return true;
1210 case BinaryOperator::Sub:
1211 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1212 return true;
1213 case BinaryOperator::Div:
1214 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1215 return true;
1216 case BinaryOperator::Rem:
1217 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1218 return true;
1219 }
1220}
1221
1222bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1223 Result = E->getValue();
1224 return true;
1225}
1226
Eli Friedman4efaa272008-11-12 09:44:48 +00001227bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1228 Expr* SubExpr = E->getSubExpr();
Nate Begeman59b5da62009-01-18 03:20:47 +00001229
Eli Friedman4efaa272008-11-12 09:44:48 +00001230 if (SubExpr->getType()->isIntegralType()) {
1231 APSInt IntResult;
1232 if (!EvaluateInteger(E, IntResult, Info))
1233 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001234 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1235 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001236 return true;
1237 }
1238 if (SubExpr->getType()->isRealFloatingType()) {
1239 if (!Visit(SubExpr))
1240 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001241 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1242 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001243 return true;
1244 }
1245
1246 return false;
1247}
1248
1249bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1250 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1251 return true;
1252}
1253
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001254//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001255// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001256//===----------------------------------------------------------------------===//
1257
1258namespace {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001259class VISIBILITY_HIDDEN ComplexExprEvaluator
1260 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001261 EvalInfo &Info;
1262
1263public:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001264 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001265
1266 //===--------------------------------------------------------------------===//
1267 // Visitor Methods
1268 //===--------------------------------------------------------------------===//
1269
1270 APValue VisitStmt(Stmt *S) {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001271 return APValue();
1272 }
1273
1274 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1275
1276 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001277 Expr* SubExpr = E->getSubExpr();
1278
1279 if (SubExpr->getType()->isRealFloatingType()) {
1280 APFloat Result(0.0);
1281
1282 if (!EvaluateFloat(SubExpr, Result, Info))
1283 return APValue();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001284
Daniel Dunbar3f279872009-01-29 01:32:56 +00001285 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001286 Result);
1287 } else {
1288 assert(SubExpr->getType()->isIntegerType() &&
1289 "Unexpected imaginary literal.");
1290
1291 llvm::APSInt Result;
1292 if (!EvaluateInteger(SubExpr, Result, Info))
1293 return APValue();
1294
1295 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1296 Zero = 0;
1297 return APValue(Zero, Result);
1298 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001299 }
1300
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001301 APValue VisitCastExpr(CastExpr *E) {
1302 Expr* SubExpr = E->getSubExpr();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001303 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1304 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001305
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001306 if (SubType->isRealFloatingType()) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001307 APFloat Result(0.0);
1308
1309 if (!EvaluateFloat(SubExpr, Result, Info))
1310 return APValue();
1311
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001312 // Apply float conversion if necessary.
1313 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbar8f826f02009-01-24 19:08:01 +00001314 return APValue(Result,
Daniel Dunbar3f279872009-01-29 01:32:56 +00001315 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001316 } else if (SubType->isIntegerType()) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001317 APSInt Result;
1318
1319 if (!EvaluateInteger(SubExpr, Result, Info))
1320 return APValue();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001321
1322 // Apply integer conversion if necessary.
1323 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001324 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1325 Zero = 0;
1326 return APValue(Result, Zero);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001327 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1328 APValue Src;
1329
1330 if (!EvaluateComplex(SubExpr, Src, Info))
1331 return APValue();
1332
1333 QualType SrcType = CT->getElementType();
1334
1335 if (Src.isComplexFloat()) {
1336 if (EltType->isRealFloatingType()) {
1337 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1338 Src.getComplexFloatReal(),
1339 Info.Ctx),
1340 HandleFloatToFloatCast(EltType, SrcType,
1341 Src.getComplexFloatImag(),
1342 Info.Ctx));
1343 } else {
1344 return APValue(HandleFloatToIntCast(EltType, SrcType,
1345 Src.getComplexFloatReal(),
1346 Info.Ctx),
1347 HandleFloatToIntCast(EltType, SrcType,
1348 Src.getComplexFloatImag(),
1349 Info.Ctx));
1350 }
1351 } else {
1352 assert(Src.isComplexInt() && "Invalid evaluate result.");
1353 if (EltType->isRealFloatingType()) {
1354 return APValue(HandleIntToFloatCast(EltType, SrcType,
1355 Src.getComplexIntReal(),
1356 Info.Ctx),
1357 HandleIntToFloatCast(EltType, SrcType,
1358 Src.getComplexIntImag(),
1359 Info.Ctx));
1360 } else {
1361 return APValue(HandleIntToIntCast(EltType, SrcType,
1362 Src.getComplexIntReal(),
1363 Info.Ctx),
1364 HandleIntToIntCast(EltType, SrcType,
1365 Src.getComplexIntImag(),
1366 Info.Ctx));
1367 }
1368 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001369 }
1370
1371 // FIXME: Handle more casts.
1372 return APValue();
1373 }
1374
1375 APValue VisitBinaryOperator(const BinaryOperator *E);
1376
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001377};
1378} // end anonymous namespace
1379
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001380static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001381{
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001382 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1383 assert((!Result.isComplexFloat() ||
1384 (&Result.getComplexFloatReal().getSemantics() ==
1385 &Result.getComplexFloatImag().getSemantics())) &&
1386 "Invalid complex evaluation.");
1387 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001388}
1389
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001390APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001391{
1392 APValue Result, RHS;
1393
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001394 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001395 return APValue();
1396
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001397 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001398 return APValue();
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001399
Daniel Dunbar3f279872009-01-29 01:32:56 +00001400 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1401 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001402 switch (E->getOpcode()) {
1403 default: return APValue();
1404 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001405 if (Result.isComplexFloat()) {
1406 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1407 APFloat::rmNearestTiesToEven);
1408 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1409 APFloat::rmNearestTiesToEven);
1410 } else {
1411 Result.getComplexIntReal() += RHS.getComplexIntReal();
1412 Result.getComplexIntImag() += RHS.getComplexIntImag();
1413 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001414 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001415 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001416 if (Result.isComplexFloat()) {
1417 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1418 APFloat::rmNearestTiesToEven);
1419 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1420 APFloat::rmNearestTiesToEven);
1421 } else {
1422 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1423 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1424 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00001425 break;
1426 case BinaryOperator::Mul:
1427 if (Result.isComplexFloat()) {
1428 APValue LHS = Result;
1429 APFloat &LHS_r = LHS.getComplexFloatReal();
1430 APFloat &LHS_i = LHS.getComplexFloatImag();
1431 APFloat &RHS_r = RHS.getComplexFloatReal();
1432 APFloat &RHS_i = RHS.getComplexFloatImag();
1433
1434 APFloat Tmp = LHS_r;
1435 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1436 Result.getComplexFloatReal() = Tmp;
1437 Tmp = LHS_i;
1438 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1439 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1440
1441 Tmp = LHS_r;
1442 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1443 Result.getComplexFloatImag() = Tmp;
1444 Tmp = LHS_i;
1445 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1446 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1447 } else {
1448 APValue LHS = Result;
1449 Result.getComplexIntReal() =
1450 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1451 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1452 Result.getComplexIntImag() =
1453 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1454 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1455 }
1456 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001457 }
1458
1459 return Result;
1460}
1461
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001462//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001463// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001464//===----------------------------------------------------------------------===//
1465
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001466/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner019f4e82008-10-06 05:28:25 +00001467/// any crazy technique (that has nothing to do with language standards) that
1468/// we want to. If this function returns true, it returns the folded constant
1469/// in Result.
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001470bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1471 EvalInfo Info(Ctx, Result);
Anders Carlsson54da0492008-11-30 16:38:33 +00001472
Nate Begeman59b5da62009-01-18 03:20:47 +00001473 if (getType()->isVectorType()) {
1474 if (!EvaluateVector(this, Result.Val, Info))
1475 return false;
1476 } else if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001477 llvm::APSInt sInt(32);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001478 if (!EvaluateInteger(this, sInt, Info))
1479 return false;
1480
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001481 Result.Val = APValue(sInt);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001482 } else if (getType()->isPointerType()) {
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001483 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001484 return false;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001485 } else if (getType()->isRealFloatingType()) {
1486 llvm::APFloat f(0.0);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001487 if (!EvaluateFloat(this, f, Info))
1488 return false;
1489
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001490 Result.Val = APValue(f);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001491 } else if (getType()->isAnyComplexType()) {
1492 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001493 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001494 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00001495 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00001496
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00001497 return true;
1498}
1499
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001500/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001501/// folded, but discard the result.
1502bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001503 EvalResult Result;
1504 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001505}
Anders Carlsson51fe9962008-11-22 21:04:56 +00001506
1507APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001508 EvalResult EvalResult;
1509 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00001510 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00001511 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001512 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00001513
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001514 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00001515}