blob: 3430b8826e6f8d0511e6f6859d5d7d7d03fdf6a6 [file] [log] [blame]
Chris Lattnera42f09a2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc7436af2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Eli Friedman7888b932008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeonefddb9c2008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner545f39e2009-01-29 05:15:15 +000018#include "clang/AST/ASTDiagnostic.h"
Anders Carlssonc0328012008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssoncad17b52008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnera823ccf2008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedman2f445492008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc7436af2008-07-03 04:20:39 +000024
Chris Lattner422373c2008-07-11 22:52:41 +000025/// EvalInfo - This is a private struct used by the evaluator to capture
26/// information about a subexpression as it is folded. It retains information
27/// about the AST context, but also maintains information about the folded
28/// expression.
29///
30/// If an expression could be evaluated, it is still possible it is not a C
31/// "integer constant expression" or constant expression. If not, this struct
32/// captures information about how and why not.
33///
34/// One bit of information passed *into* the request for constant folding
35/// indicates whether the subexpression is "evaluated" or not according to C
36/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
37/// evaluate the expression regardless of what the RHS is, but C only allows
38/// certain things in certain situations.
39struct EvalInfo {
40 ASTContext &Ctx;
41
Anders Carlssondd8d41f2008-11-30 16:38:33 +000042 /// EvalResult - Contains information about the evaluation.
43 Expr::EvalResult &EvalResult;
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000044
45 /// ShortCircuit - will be greater than zero if the current subexpression has
46 /// will not be evaluated because it's short-circuited (according to C rules).
47 unsigned ShortCircuit;
Chris Lattner422373c2008-07-11 22:52:41 +000048
Anders Carlssondd8d41f2008-11-30 16:38:33 +000049 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult) : Ctx(ctx),
Anders Carlsson6c1a9e22008-11-30 18:26:25 +000050 EvalResult(evalresult), ShortCircuit(0) {}
Chris Lattner422373c2008-07-11 22:52:41 +000051};
52
53
Eli Friedman7888b932008-11-12 09:44:48 +000054static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner422373c2008-07-11 22:52:41 +000055static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
56static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Eli Friedman2f445492008-08-22 00:06:13 +000057static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +000058static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000059
60//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-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 Dunbaraffa0e32009-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 Friedman7888b932008-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 Dunbarff59ed82008-11-12 21:52:46 +0000145#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000146 // FIXME: Remove this when we support more expressions.
147 printf("Unhandled pointer statement\n");
148 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000149#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000150 return APValue();
151 }
152
153 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssone284ebe2008-11-24 04:41:22 +0000154 APValue VisitDeclRefExpr(DeclRefExpr *E);
Eli Friedman7888b932008-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 Carlsson027f2882008-11-16 19:01:22 +0000159 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman7888b932008-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 Carlssone284ebe2008-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 Friedman7888b932008-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 Gregor82d44772008-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 Friedman7888b932008-11-12 09:44:48 +0000202
203 // FIXME: This is linear time.
Douglas Gregor8acb7272008-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 Friedman7888b932008-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 Carlsson027f2882008-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 Friedman7888b932008-11-12 09:44:48 +0000236
237//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000238// Pointer Evaluation
239//===----------------------------------------------------------------------===//
240
Anders Carlssoncad17b52008-07-08 05:13:58 +0000241namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000242class VISIBILITY_HIDDEN PointerExprEvaluator
243 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000244 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000245public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000246
Chris Lattner422373c2008-07-11 22:52:41 +0000247 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000248
Anders Carlsson02a34c32008-07-08 14:30:00 +0000249 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000250 return APValue();
251 }
252
253 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
254
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000255 APValue VisitBinaryOperator(const BinaryOperator *E);
256 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000257 APValue VisitUnaryOperator(const UnaryOperator *E);
258 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
259 { return APValue(E, 0); }
Eli Friedmanf1941132009-01-25 01:21:06 +0000260 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
261 { return APValue(E, 0); }
Eli Friedman67f4ac52009-01-25 01:54:01 +0000262 APValue VisitCallExpr(CallExpr *E);
Mike Stumpd55240e2009-02-19 01:01:04 +0000263 APValue VisitBlockExpr(BlockExpr *E) { return APValue(E, 0); }
Eli Friedman7888b932008-11-12 09:44:48 +0000264 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000265};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000266} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000267
Chris Lattner422373c2008-07-11 22:52:41 +0000268static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Mike Stump5b601ff2009-02-18 21:44:49 +0000269 if (!E->getType()->isPointerType()
270 && !E->getType()->isBlockPointerType())
Chris Lattnera823ccf2008-07-11 18:11:29 +0000271 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000272 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000273 return Result.isLValue();
274}
275
276APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
277 if (E->getOpcode() != BinaryOperator::Add &&
278 E->getOpcode() != BinaryOperator::Sub)
279 return APValue();
280
281 const Expr *PExp = E->getLHS();
282 const Expr *IExp = E->getRHS();
283 if (IExp->getType()->isPointerType())
284 std::swap(PExp, IExp);
285
286 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000287 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000288 return APValue();
289
290 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000291 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000292 return APValue();
293
Eli Friedman7888b932008-11-12 09:44:48 +0000294 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
Anders Carlsson4fbb52c2009-02-19 04:55:58 +0000295 uint64_t SizeOfPointee;
296
297 // Explicitly handle GNU void* and function pointer arithmetic extensions.
298 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
299 SizeOfPointee = 1;
300 else
301 SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
Eli Friedman7888b932008-11-12 09:44:48 +0000302
Chris Lattnera823ccf2008-07-11 18:11:29 +0000303 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000304
Chris Lattnera823ccf2008-07-11 18:11:29 +0000305 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000306 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000307 else
Eli Friedman7888b932008-11-12 09:44:48 +0000308 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
309
Chris Lattnera823ccf2008-07-11 18:11:29 +0000310 return APValue(ResultLValue.getLValueBase(), Offset);
311}
Eli Friedman7888b932008-11-12 09:44:48 +0000312
313APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
314 if (E->getOpcode() == UnaryOperator::Extension) {
315 // FIXME: Deal with warnings?
316 return Visit(E->getSubExpr());
317 }
318
319 if (E->getOpcode() == UnaryOperator::AddrOf) {
320 APValue result;
321 if (EvaluateLValue(E->getSubExpr(), result, Info))
322 return result;
323 }
324
325 return APValue();
326}
Anders Carlsson4ab88da2008-12-05 05:24:13 +0000327
Chris Lattnera823ccf2008-07-11 18:11:29 +0000328
Chris Lattnera42f09a2008-07-11 19:10:17 +0000329APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000330 const Expr* SubExpr = E->getSubExpr();
331
332 // Check for pointer->pointer cast
333 if (SubExpr->getType()->isPointerType()) {
334 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000335 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000336 return Result;
337 return APValue();
338 }
339
Eli Friedman3e64dd72008-07-27 05:46:18 +0000340 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000341 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000342 if (EvaluateInteger(SubExpr, Result, Info)) {
343 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000344 return APValue(0, Result.getZExtValue());
345 }
346 }
Eli Friedman7888b932008-11-12 09:44:48 +0000347
348 if (SubExpr->getType()->isFunctionType() ||
349 SubExpr->getType()->isArrayType()) {
350 APValue Result;
351 if (EvaluateLValue(SubExpr, Result, Info))
352 return Result;
353 return APValue();
354 }
355
356 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000357 return APValue();
358}
359
Eli Friedman67f4ac52009-01-25 01:54:01 +0000360APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000361 if (E->isBuiltinCall(Info.Ctx) ==
362 Builtin::BI__builtin___CFStringMakeConstantString)
Eli Friedman67f4ac52009-01-25 01:54:01 +0000363 return APValue(E, 0);
364 return APValue();
365}
366
Eli Friedman7888b932008-11-12 09:44:48 +0000367APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
368 bool BoolResult;
369 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
370 return APValue();
371
372 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
373
374 APValue Result;
375 if (EvaluatePointer(EvalExpr, Result, Info))
376 return Result;
377 return APValue();
378}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000379
380//===----------------------------------------------------------------------===//
Nate Begemand6d2f772009-01-18 03:20:47 +0000381// Vector Evaluation
382//===----------------------------------------------------------------------===//
383
384namespace {
385 class VISIBILITY_HIDDEN VectorExprEvaluator
386 : public StmtVisitor<VectorExprEvaluator, APValue> {
387 EvalInfo &Info;
388 public:
389
390 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
391
392 APValue VisitStmt(Stmt *S) {
393 return APValue();
394 }
395
396 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
397 APValue VisitCastExpr(const CastExpr* E);
398 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
399 APValue VisitInitListExpr(const InitListExpr *E);
400 };
401} // end anonymous namespace
402
403static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
404 if (!E->getType()->isVectorType())
405 return false;
406 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
407 return !Result.isUninit();
408}
409
410APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
411 const Expr* SE = E->getSubExpr();
412
413 // Check for vector->vector bitcast.
414 if (SE->getType()->isVectorType())
415 return this->Visit(const_cast<Expr*>(SE));
416
417 return APValue();
418}
419
420APValue
421VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
422 return this->Visit(const_cast<Expr*>(E->getInitializer()));
423}
424
425APValue
426VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
427 const VectorType *VT = E->getType()->getAsVectorType();
428 unsigned NumInits = E->getNumInits();
429
430 if (!VT || VT->getNumElements() != NumInits)
431 return APValue();
432
433 QualType EltTy = VT->getElementType();
434 llvm::SmallVector<APValue, 4> Elements;
435
436 for (unsigned i = 0; i < NumInits; i++) {
437 if (EltTy->isIntegerType()) {
438 llvm::APSInt sInt(32);
439 if (!EvaluateInteger(E->getInit(i), sInt, Info))
440 return APValue();
441 Elements.push_back(APValue(sInt));
442 } else {
443 llvm::APFloat f(0.0);
444 if (!EvaluateFloat(E->getInit(i), f, Info))
445 return APValue();
446 Elements.push_back(APValue(f));
447 }
448 }
449 return APValue(&Elements[0], Elements.size());
450}
451
452//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000453// Integer Evaluation
454//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000455
456namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000457class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000458 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000459 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000460 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000461public:
Chris Lattner422373c2008-07-11 22:52:41 +0000462 IntExprEvaluator(EvalInfo &info, APSInt &result)
463 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000464
Anders Carlssonfa76d822008-11-30 18:14:57 +0000465 bool Extension(SourceLocation L, diag::kind D, const Expr *E) {
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000466 Info.EvalResult.DiagLoc = L;
467 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000468 Info.EvalResult.DiagExpr = E;
Chris Lattner82437da2008-07-12 00:14:42 +0000469 return true; // still a constant.
470 }
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000471
472 bool Success(const llvm::APInt &I, const Expr *E) {
473 Result = I;
474 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
475 return true;
476 }
477
478 bool Success(uint64_t Value, const Expr *E) {
479 Result = Info.Ctx.MakeIntValue(Value, E->getType());
480 return true;
481 }
482
Anders Carlssonfa76d822008-11-30 18:14:57 +0000483 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner82437da2008-07-12 00:14:42 +0000484 // If this is in an unevaluated portion of the subexpression, ignore the
485 // error.
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000486 if (Info.ShortCircuit) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000487 // If error is ignored because the value isn't evaluated, get the real
488 // type at least to prevent errors downstream.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000489 return Success(0, E);
Chris Lattner438f3b12008-11-12 07:43:42 +0000490 }
Chris Lattner82437da2008-07-12 00:14:42 +0000491
Chris Lattner438f3b12008-11-12 07:43:42 +0000492 // Take the first error.
Anders Carlssondd8d41f2008-11-30 16:38:33 +0000493 if (Info.EvalResult.Diag == 0) {
494 Info.EvalResult.DiagLoc = L;
495 Info.EvalResult.Diag = D;
Anders Carlssonfa76d822008-11-30 18:14:57 +0000496 Info.EvalResult.DiagExpr = E;
Chris Lattner438f3b12008-11-12 07:43:42 +0000497 }
Chris Lattner82437da2008-07-12 00:14:42 +0000498 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000499 }
500
Anders Carlssoncad17b52008-07-08 05:13:58 +0000501 //===--------------------------------------------------------------------===//
502 // Visitor Methods
503 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000504
505 bool VisitStmt(Stmt *) {
506 assert(0 && "This should be called on integers, stmts are not integers");
507 return false;
508 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000509
Chris Lattner438f3b12008-11-12 07:43:42 +0000510 bool VisitExpr(Expr *E) {
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000511 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssoncad17b52008-07-08 05:13:58 +0000512 }
513
Chris Lattnera42f09a2008-07-11 19:10:17 +0000514 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000515
Chris Lattner15e59112008-07-12 00:38:25 +0000516 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000517 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000518 }
519 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000520 return Success(E->getValue(), E);
Chris Lattner15e59112008-07-12 00:38:25 +0000521 }
522 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000523 // Per gcc docs "this built-in function ignores top level
524 // qualifiers". We need to use the canonical version to properly
525 // be able to strip CRV qualifiers from the type.
526 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
527 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000528 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
529 T1.getUnqualifiedType()),
530 E);
Chris Lattner15e59112008-07-12 00:38:25 +0000531 }
532 bool VisitDeclRefExpr(const DeclRefExpr *E);
533 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000534 bool VisitBinaryOperator(const BinaryOperator *E);
535 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000536 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000537
Daniel Dunbaraffa0e32009-01-29 06:16:07 +0000538 bool VisitCastExpr(CastExpr* E);
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000539 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
540
Anders Carlsson027f2882008-11-16 19:01:22 +0000541 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000542 return Success(E->getValue(), E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000543 }
544
Anders Carlsson774f9c72008-12-21 22:39:40 +0000545 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000546 return Success(0, E);
Anders Carlsson774f9c72008-12-21 22:39:40 +0000547 }
548
Anders Carlsson027f2882008-11-16 19:01:22 +0000549 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000550 return Success(0, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000551 }
552
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000553 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000554 return Success(E->EvaluateTrait(), E);
Sebastian Redl39c0f6f2009-01-05 20:52:13 +0000555 }
556
Chris Lattner265a0892008-07-11 21:24:13 +0000557private:
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000558 unsigned GetAlignOfExpr(const Expr *E);
559 unsigned GetAlignOfType(QualType T);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000560};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000561} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000562
Chris Lattner422373c2008-07-11 22:52:41 +0000563static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
564 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000565}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000566
Chris Lattner15e59112008-07-12 00:38:25 +0000567bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
568 // Enums are integer constant exprs.
569 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
570 Result = D->getInitVal();
Eli Friedman8b10a232008-12-08 02:21:03 +0000571 // FIXME: This is an ugly hack around the fact that enums don't set their
572 // signedness consistently; see PR3173
573 Result.setIsUnsigned(!E->getType()->isSignedIntegerType());
Chris Lattner15e59112008-07-12 00:38:25 +0000574 return true;
575 }
Sebastian Redl410dd872009-02-08 15:51:17 +0000576
577 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
578 if (Info.Ctx.getLangOptions().CPlusPlus &&
579 E->getType().getCVRQualifiers() == QualType::Const) {
580 if (const VarDecl *D = dyn_cast<VarDecl>(E->getDecl())) {
581 if (const Expr *Init = D->getInit())
582 return Visit(const_cast<Expr*>(Init));
583 }
584 }
585
Chris Lattner15e59112008-07-12 00:38:25 +0000586 // Otherwise, random variable references are not constants.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000587 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner15e59112008-07-12 00:38:25 +0000588}
589
Chris Lattner1eee9402008-10-06 06:40:35 +0000590/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
591/// as GCC.
592static int EvaluateBuiltinClassifyType(const CallExpr *E) {
593 // The following enum mimics the values returned by GCC.
594 enum gcc_type_class {
595 no_type_class = -1,
596 void_type_class, integer_type_class, char_type_class,
597 enumeral_type_class, boolean_type_class,
598 pointer_type_class, reference_type_class, offset_type_class,
599 real_type_class, complex_type_class,
600 function_type_class, method_type_class,
601 record_type_class, union_type_class,
602 array_type_class, string_type_class,
603 lang_type_class
604 };
605
606 // If no argument was supplied, default to "no_type_class". This isn't
607 // ideal, however it is what gcc does.
608 if (E->getNumArgs() == 0)
609 return no_type_class;
610
611 QualType ArgTy = E->getArg(0)->getType();
612 if (ArgTy->isVoidType())
613 return void_type_class;
614 else if (ArgTy->isEnumeralType())
615 return enumeral_type_class;
616 else if (ArgTy->isBooleanType())
617 return boolean_type_class;
618 else if (ArgTy->isCharType())
619 return string_type_class; // gcc doesn't appear to use char_type_class
620 else if (ArgTy->isIntegerType())
621 return integer_type_class;
622 else if (ArgTy->isPointerType())
623 return pointer_type_class;
624 else if (ArgTy->isReferenceType())
625 return reference_type_class;
626 else if (ArgTy->isRealType())
627 return real_type_class;
628 else if (ArgTy->isComplexType())
629 return complex_type_class;
630 else if (ArgTy->isFunctionType())
631 return function_type_class;
632 else if (ArgTy->isStructureType())
633 return record_type_class;
634 else if (ArgTy->isUnionType())
635 return union_type_class;
636 else if (ArgTy->isArrayType())
637 return array_type_class;
638 else if (ArgTy->isUnionType())
639 return union_type_class;
640 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
641 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
642 return -1;
643}
644
Chris Lattner15e59112008-07-12 00:38:25 +0000645bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +0000646 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner87293782008-10-06 05:28:25 +0000647 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000648 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner87293782008-10-06 05:28:25 +0000649 case Builtin::BI__builtin_classify_type:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000650 return Success(EvaluateBuiltinClassifyType(E), E);
Chris Lattner87293782008-10-06 05:28:25 +0000651
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000652 case Builtin::BI__builtin_constant_p:
Chris Lattner87293782008-10-06 05:28:25 +0000653 // __builtin_constant_p always has one operand: it returns true if that
654 // operand can be folded, false otherwise.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000655 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner87293782008-10-06 05:28:25 +0000656 }
Chris Lattner15e59112008-07-12 00:38:25 +0000657}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000658
Chris Lattnera42f09a2008-07-11 19:10:17 +0000659bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000660 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000661 if (!Visit(E->getRHS()))
662 return false;
Anders Carlsson197f6f72008-12-01 06:44:05 +0000663
664 if (!Info.ShortCircuit) {
665 // If we can't evaluate the LHS, it must be because it has
666 // side effects.
667 if (!E->getLHS()->isEvaluatable(Info.Ctx))
668 Info.EvalResult.HasSideEffects = true;
669
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000670 return Extension(E->getOperatorLoc(), diag::note_comma_in_ice, E);
Anders Carlsson197f6f72008-12-01 06:44:05 +0000671 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000672
Anders Carlssonb1112ad2008-12-01 02:07:06 +0000673 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000674 }
675
676 if (E->isLogicalOp()) {
677 // These need to be handled specially because the operands aren't
678 // necessarily integral
Anders Carlsson501da1f2008-11-30 16:51:17 +0000679 bool lhsResult, rhsResult;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000680
Anders Carlsson501da1f2008-11-30 16:51:17 +0000681 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000682 // We were able to evaluate the LHS, see if we can get away with not
683 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Anders Carlsson501da1f2008-11-30 16:51:17 +0000684 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
685 !lhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000686 Result = Info.Ctx.MakeIntValue(lhsResult, E->getType());
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000687
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000688 Info.ShortCircuit++;
Anders Carlsson501da1f2008-11-30 16:51:17 +0000689 bool rhsEvaluated = HandleConversionToBool(E->getRHS(), rhsResult, Info);
Anders Carlsson6c1a9e22008-11-30 18:26:25 +0000690 Info.ShortCircuit--;
691
Anders Carlsson501da1f2008-11-30 16:51:17 +0000692 if (rhsEvaluated)
693 return true;
694
695 // FIXME: Return an extension warning saying that the RHS could not be
696 // evaluated.
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000697 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000698 }
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000699
Anders Carlsson501da1f2008-11-30 16:51:17 +0000700 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000701 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000702 return Success(lhsResult || rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000703 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000704 return Success(lhsResult && rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000705 }
706 } else {
Anders Carlsson501da1f2008-11-30 16:51:17 +0000707 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000708 // We can't evaluate the LHS; however, sometimes the result
709 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlsson501da1f2008-11-30 16:51:17 +0000710 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
711 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000712 // Since we weren't able to evaluate the left hand side, it
Anders Carlsson501da1f2008-11-30 16:51:17 +0000713 // must have had side effects.
714 Info.EvalResult.HasSideEffects = true;
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000715
716 return Success(rhsResult, E);
Anders Carlsson8bce31a2008-11-24 04:21:33 +0000717 }
718 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000719 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000720
Eli Friedman14cc7542008-11-13 06:09:17 +0000721 return false;
722 }
723
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000724 QualType LHSTy = E->getLHS()->getType();
725 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000726
727 if (LHSTy->isAnyComplexType()) {
728 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
729 APValue LHS, RHS;
730
731 if (!EvaluateComplex(E->getLHS(), LHS, Info))
732 return false;
733
734 if (!EvaluateComplex(E->getRHS(), RHS, Info))
735 return false;
736
737 if (LHS.isComplexFloat()) {
738 APFloat::cmpResult CR_r =
739 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
740 APFloat::cmpResult CR_i =
741 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
742
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000743 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000744 return Success((CR_r == APFloat::cmpEqual &&
745 CR_i == APFloat::cmpEqual), E);
746 else {
747 assert(E->getOpcode() == BinaryOperator::NE &&
748 "Invalid complex comparison.");
749 return Success(((CR_r == APFloat::cmpGreaterThan ||
750 CR_r == APFloat::cmpLessThan) &&
751 (CR_i == APFloat::cmpGreaterThan ||
752 CR_i == APFloat::cmpLessThan)), E);
753 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000754 } else {
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000755 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000756 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
757 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
758 else {
759 assert(E->getOpcode() == BinaryOperator::NE &&
760 "Invalid compex comparison.");
761 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
762 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
763 }
Daniel Dunbarf6060d62009-01-29 06:43:41 +0000764 }
765 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000766
767 if (LHSTy->isRealFloatingType() &&
768 RHSTy->isRealFloatingType()) {
769 APFloat RHS(0.0), LHS(0.0);
770
771 if (!EvaluateFloat(E->getRHS(), RHS, Info))
772 return false;
773
774 if (!EvaluateFloat(E->getLHS(), LHS, Info))
775 return false;
776
777 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000778
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000779 switch (E->getOpcode()) {
780 default:
781 assert(0 && "Invalid binary operator!");
782 case BinaryOperator::LT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000783 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000784 case BinaryOperator::GT:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000785 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000786 case BinaryOperator::LE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000787 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000788 case BinaryOperator::GE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000789 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
790 E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000791 case BinaryOperator::EQ:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000792 return Success(CR == APFloat::cmpEqual, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000793 case BinaryOperator::NE:
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000794 return Success(CR == APFloat::cmpGreaterThan
795 || CR == APFloat::cmpLessThan, E);
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000796 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000797 }
798
Anders Carlsson027f2882008-11-16 19:01:22 +0000799 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000800 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000801 APValue LHSValue;
802 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
803 return false;
804
805 APValue RHSValue;
806 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
807 return false;
808
809 // FIXME: Is this correct? What if only one of the operands has a base?
810 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
811 return false;
812
813 const QualType Type = E->getLHS()->getType();
814 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
815
816 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
817 D /= Info.Ctx.getTypeSize(ElementType) / 8;
818
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000819 return Success(D, E);
Anders Carlsson027f2882008-11-16 19:01:22 +0000820 }
821 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000822 if (!LHSTy->isIntegralType() ||
823 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000824 // We can't continue from here for non-integral types, and they
825 // could potentially confuse the following operations.
826 // FIXME: Deal with EQ and friends.
827 return false;
828 }
829
Anders Carlssond1aa5812008-07-08 14:35:21 +0000830 // The LHS of a constant expr is always evaluated and needed.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000831 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000832 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000833 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000834
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000835 llvm::APSInt RHS;
Chris Lattner82437da2008-07-12 00:14:42 +0000836 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000837 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000838
Anders Carlssond1aa5812008-07-08 14:35:21 +0000839 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000840 default:
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000841 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner82437da2008-07-12 00:14:42 +0000842 case BinaryOperator::Mul: Result *= RHS; return true;
843 case BinaryOperator::Add: Result += RHS; return true;
844 case BinaryOperator::Sub: Result -= RHS; return true;
845 case BinaryOperator::And: Result &= RHS; return true;
846 case BinaryOperator::Xor: Result ^= RHS; return true;
847 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000848 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000849 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000850 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000851 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000852 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000853 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000854 if (RHS == 0)
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000855 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000856 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000857 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000858 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000859 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000860 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000861 break;
862 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000863 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000864 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000865
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000866 case BinaryOperator::LT: return Success(Result < RHS, E);
867 case BinaryOperator::GT: return Success(Result > RHS, E);
868 case BinaryOperator::LE: return Success(Result <= RHS, E);
869 case BinaryOperator::GE: return Success(Result >= RHS, E);
870 case BinaryOperator::EQ: return Success(Result == RHS, E);
871 case BinaryOperator::NE: return Success(Result != RHS, E);
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000872 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000873
874 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000875 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000876}
877
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000878bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000879 bool Cond;
880 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000881 return false;
882
Nuno Lopes308de752008-11-16 22:06:39 +0000883 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000884}
885
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000886unsigned IntExprEvaluator::GetAlignOfType(QualType T) {
Chris Lattnere3f61e12009-01-24 21:09:06 +0000887 const Type *Ty = Info.Ctx.getCanonicalType(T).getTypePtr();
888
889 // __alignof__(void) = 1 as a gcc extension.
890 if (Ty->isVoidType())
891 return 1;
892
893 // GCC extension: alignof(function) = 4.
894 // FIXME: AlignOf shouldn't be unconditionally 4! It should listen to the
895 // attribute(align) directive.
896 if (Ty->isFunctionType())
897 return 4;
898
Fariborz Jahanianb60352a2009-02-17 18:27:45 +0000899 if (const ExtQualType *EXTQT = dyn_cast<ExtQualType>(Ty))
900 return GetAlignOfType(QualType(EXTQT->getBaseType(), 0));
Chris Lattnere3f61e12009-01-24 21:09:06 +0000901
902 // alignof VLA/incomplete array.
903 if (const ArrayType *VAT = dyn_cast<ArrayType>(Ty))
904 return GetAlignOfType(VAT->getElementType());
905
906 // sizeof (objc class)?
907 if (isa<ObjCInterfaceType>(Ty))
908 return 1; // FIXME: This probably isn't right.
909
910 // Get information about the alignment.
911 unsigned CharSize = Info.Ctx.Target.getCharWidth();
912 return Info.Ctx.getTypeAlign(Ty) / CharSize;
913}
914
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000915unsigned IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
916 E = E->IgnoreParens();
917
918 // alignof decl is always accepted, even if it doesn't make sense: we default
919 // to 1 in those cases.
920 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000921 return Info.Ctx.getDeclAlignInBytes(DRE->getDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000922
923 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Daniel Dunbar96d1f1b2009-02-17 22:16:19 +0000924 return Info.Ctx.getDeclAlignInBytes(ME->getMemberDecl());
Chris Lattnerbd3153e2009-01-24 21:53:27 +0000925
Chris Lattnere3f61e12009-01-24 21:09:06 +0000926 return GetAlignOfType(E->getType());
927}
928
929
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000930/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
931/// expression's type.
932bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
933 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000934
Chris Lattnere3f61e12009-01-24 21:09:06 +0000935 // Handle alignof separately.
936 if (!E->isSizeOf()) {
937 if (E->isArgumentType())
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000938 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000939 else
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000940 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere3f61e12009-01-24 21:09:06 +0000941 }
942
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000943 QualType SrcTy = E->getTypeOfArgument();
944
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000945 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
946 // extension.
947 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
948 return Success(1, E);
Chris Lattner265a0892008-07-11 21:24:13 +0000949
950 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere3f61e12009-01-24 21:09:06 +0000951 if (!SrcTy->isConstantSizeType())
Chris Lattner265a0892008-07-11 21:24:13 +0000952 return false;
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000953
954 if (SrcTy->isObjCInterfaceType()) {
955 // Slightly unusual case: the size of an ObjC interface type is the
956 // size of the class. This code intentionally falls through to the normal
957 // case.
958 ObjCInterfaceDecl *OI = SrcTy->getAsObjCInterfaceType()->getDecl();
959 RecordDecl *RD = const_cast<RecordDecl*>(Info.Ctx.addRecordToClass(OI));
960 SrcTy = Info.Ctx.getTagDeclType(static_cast<TagDecl*>(RD));
961 }
962
Chris Lattnere3f61e12009-01-24 21:09:06 +0000963 // Get information about the size.
Chris Lattner422373c2008-07-11 22:52:41 +0000964 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000965 return Success(Info.Ctx.getTypeSize(SrcTy) / CharSize, E);
Chris Lattner265a0892008-07-11 21:24:13 +0000966}
967
Chris Lattnera42f09a2008-07-11 19:10:17 +0000968bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000969 // Special case unary operators that do not need their subexpression
970 // evaluated. offsetof/sizeof/alignof are all special.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000971 if (E->isOffsetOfOp())
972 return Success(E->evaluateOffsetOf(Info.Ctx), E);
Eli Friedman14cc7542008-11-13 06:09:17 +0000973
974 if (E->getOpcode() == UnaryOperator::LNot) {
975 // LNot's operand isn't necessarily an integer, so we handle it specially.
976 bool bres;
977 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
978 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000979 return Success(!bres, E);
Eli Friedman14cc7542008-11-13 06:09:17 +0000980 }
981
Chris Lattner422373c2008-07-11 22:52:41 +0000982 // Get the operand value into 'Result'.
983 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000984 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000985
Chris Lattner400d7402008-07-11 22:15:16 +0000986 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000987 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000988 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
989 // See C99 6.6p3.
Anders Carlsson38bb18c2008-11-30 18:37:00 +0000990 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner400d7402008-07-11 22:15:16 +0000991 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000992 // FIXME: Should extension allow i-c-e extension expressions in its scope?
993 // If so, we could clear the diagnostic ID.
Daniel Dunbarf91896e2009-02-19 09:06:44 +0000994 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000995 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000996 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000997 break;
998 case UnaryOperator::Minus:
999 Result = -Result;
1000 break;
1001 case UnaryOperator::Not:
1002 Result = ~Result;
1003 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001004 }
1005
1006 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +00001007 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001008}
1009
Chris Lattnerff579ff2008-07-12 01:15:53 +00001010/// HandleCast - This is used to evaluate implicit or explicit casts where the
1011/// result type is integer.
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001012bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlssonfa76d822008-11-30 18:14:57 +00001013 Expr *SubExpr = E->getSubExpr();
1014 QualType DestType = E->getType();
1015
Eli Friedman7888b932008-11-12 09:44:48 +00001016 if (DestType->isBooleanType()) {
1017 bool BoolResult;
1018 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1019 return false;
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001020 return Success(BoolResult, E);
Eli Friedman7888b932008-11-12 09:44:48 +00001021 }
1022
Anders Carlssond1aa5812008-07-08 14:35:21 +00001023 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +00001024 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +00001025 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001026 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001027
1028 Result = HandleIntToIntCast(DestType, SubExpr->getType(), Result, Info.Ctx);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001029 return true;
1030 }
1031
1032 // FIXME: Clean this up!
1033 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +00001034 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +00001035 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +00001036 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001037
Anders Carlssond1aa5812008-07-08 14:35:21 +00001038 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +00001039 return false;
Eli Friedman7888b932008-11-12 09:44:48 +00001040
Daniel Dunbarf91896e2009-02-19 09:06:44 +00001041 return Success(LV.getLValueOffset(), E);
Anders Carlsson02a34c32008-07-08 14:30:00 +00001042 }
Eli Friedman7888b932008-11-12 09:44:48 +00001043
Chris Lattnerff579ff2008-07-12 01:15:53 +00001044 if (!SubExpr->getType()->isRealFloatingType())
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001045 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001046
Eli Friedman2f445492008-08-22 00:06:13 +00001047 APFloat F(0.0);
1048 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson38bb18c2008-11-30 18:37:00 +00001049 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerff579ff2008-07-12 01:15:53 +00001050
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001051 Result = HandleFloatToIntCast(DestType, SubExpr->getType(), F, Info.Ctx);
Chris Lattnera42f09a2008-07-11 19:10:17 +00001052 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +00001053}
Anders Carlsson02a34c32008-07-08 14:30:00 +00001054
Chris Lattnera823ccf2008-07-11 18:11:29 +00001055//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +00001056// Float Evaluation
1057//===----------------------------------------------------------------------===//
1058
1059namespace {
1060class VISIBILITY_HIDDEN FloatExprEvaluator
1061 : public StmtVisitor<FloatExprEvaluator, bool> {
1062 EvalInfo &Info;
1063 APFloat &Result;
1064public:
1065 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1066 : Info(info), Result(result) {}
1067
1068 bool VisitStmt(Stmt *S) {
1069 return false;
1070 }
1071
1072 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +00001073 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001074
Daniel Dunbar804ead02008-10-16 03:51:50 +00001075 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001076 bool VisitBinaryOperator(const BinaryOperator *E);
1077 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +00001078 bool VisitCastExpr(CastExpr *E);
1079 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +00001080};
1081} // end anonymous namespace
1082
1083static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
1084 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1085}
1086
Chris Lattner87293782008-10-06 05:28:25 +00001087bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregorb5af7382009-02-14 18:57:46 +00001088 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner27cde262008-10-06 05:53:16 +00001089 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +00001090 case Builtin::BI__builtin_huge_val:
1091 case Builtin::BI__builtin_huge_valf:
1092 case Builtin::BI__builtin_huge_vall:
1093 case Builtin::BI__builtin_inf:
1094 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001095 case Builtin::BI__builtin_infl: {
1096 const llvm::fltSemantics &Sem =
1097 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +00001098 Result = llvm::APFloat::getInf(Sem);
1099 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001100 }
Chris Lattner667e1ee2008-10-06 06:31:58 +00001101
1102 case Builtin::BI__builtin_nan:
1103 case Builtin::BI__builtin_nanf:
1104 case Builtin::BI__builtin_nanl:
1105 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
1106 // can't constant fold it.
1107 if (const StringLiteral *S =
1108 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
1109 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +00001110 const llvm::fltSemantics &Sem =
1111 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +00001112 Result = llvm::APFloat::getNaN(Sem);
1113 return true;
1114 }
1115 }
1116 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +00001117
1118 case Builtin::BI__builtin_fabs:
1119 case Builtin::BI__builtin_fabsf:
1120 case Builtin::BI__builtin_fabsl:
1121 if (!EvaluateFloat(E->getArg(0), Result, Info))
1122 return false;
1123
1124 if (Result.isNegative())
1125 Result.changeSign();
1126 return true;
1127
1128 case Builtin::BI__builtin_copysign:
1129 case Builtin::BI__builtin_copysignf:
1130 case Builtin::BI__builtin_copysignl: {
1131 APFloat RHS(0.);
1132 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1133 !EvaluateFloat(E->getArg(1), RHS, Info))
1134 return false;
1135 Result.copySign(RHS);
1136 return true;
1137 }
Chris Lattner87293782008-10-06 05:28:25 +00001138 }
1139}
1140
Daniel Dunbar804ead02008-10-16 03:51:50 +00001141bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +00001142 if (E->getOpcode() == UnaryOperator::Deref)
1143 return false;
1144
Daniel Dunbar804ead02008-10-16 03:51:50 +00001145 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1146 return false;
1147
1148 switch (E->getOpcode()) {
1149 default: return false;
1150 case UnaryOperator::Plus:
1151 return true;
1152 case UnaryOperator::Minus:
1153 Result.changeSign();
1154 return true;
1155 }
1156}
Chris Lattner87293782008-10-06 05:28:25 +00001157
Eli Friedman2f445492008-08-22 00:06:13 +00001158bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1159 // FIXME: Diagnostics? I really don't understand how the warnings
1160 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001161 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001162 if (!EvaluateFloat(E->getLHS(), Result, Info))
1163 return false;
1164 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1165 return false;
1166
1167 switch (E->getOpcode()) {
1168 default: return false;
1169 case BinaryOperator::Mul:
1170 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1171 return true;
1172 case BinaryOperator::Add:
1173 Result.add(RHS, APFloat::rmNearestTiesToEven);
1174 return true;
1175 case BinaryOperator::Sub:
1176 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1177 return true;
1178 case BinaryOperator::Div:
1179 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1180 return true;
1181 case BinaryOperator::Rem:
1182 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1183 return true;
1184 }
1185}
1186
1187bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1188 Result = E->getValue();
1189 return true;
1190}
1191
Eli Friedman7888b932008-11-12 09:44:48 +00001192bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1193 Expr* SubExpr = E->getSubExpr();
Nate Begemand6d2f772009-01-18 03:20:47 +00001194
Eli Friedman7888b932008-11-12 09:44:48 +00001195 if (SubExpr->getType()->isIntegralType()) {
1196 APSInt IntResult;
1197 if (!EvaluateInteger(E, IntResult, Info))
1198 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001199 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
1200 IntResult, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001201 return true;
1202 }
1203 if (SubExpr->getType()->isRealFloatingType()) {
1204 if (!Visit(SubExpr))
1205 return false;
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001206 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1207 Result, Info.Ctx);
Eli Friedman7888b932008-11-12 09:44:48 +00001208 return true;
1209 }
1210
1211 return false;
1212}
1213
1214bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1215 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1216 return true;
1217}
1218
Eli Friedman2f445492008-08-22 00:06:13 +00001219//===----------------------------------------------------------------------===//
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001220// Complex Evaluation (for float and integer)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001221//===----------------------------------------------------------------------===//
1222
1223namespace {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001224class VISIBILITY_HIDDEN ComplexExprEvaluator
1225 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001226 EvalInfo &Info;
1227
1228public:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001229 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001230
1231 //===--------------------------------------------------------------------===//
1232 // Visitor Methods
1233 //===--------------------------------------------------------------------===//
1234
1235 APValue VisitStmt(Stmt *S) {
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001236 return APValue();
1237 }
1238
1239 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1240
1241 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001242 Expr* SubExpr = E->getSubExpr();
1243
1244 if (SubExpr->getType()->isRealFloatingType()) {
1245 APFloat Result(0.0);
1246
1247 if (!EvaluateFloat(SubExpr, Result, Info))
1248 return APValue();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001249
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001250 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001251 Result);
1252 } else {
1253 assert(SubExpr->getType()->isIntegerType() &&
1254 "Unexpected imaginary literal.");
1255
1256 llvm::APSInt Result;
1257 if (!EvaluateInteger(SubExpr, Result, Info))
1258 return APValue();
1259
1260 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1261 Zero = 0;
1262 return APValue(Zero, Result);
1263 }
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001264 }
1265
Anders Carlssonad2794c2008-11-16 21:51:21 +00001266 APValue VisitCastExpr(CastExpr *E) {
1267 Expr* SubExpr = E->getSubExpr();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001268 QualType EltType = E->getType()->getAsComplexType()->getElementType();
1269 QualType SubType = SubExpr->getType();
Anders Carlssonad2794c2008-11-16 21:51:21 +00001270
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001271 if (SubType->isRealFloatingType()) {
Anders Carlssonad2794c2008-11-16 21:51:21 +00001272 APFloat Result(0.0);
1273
1274 if (!EvaluateFloat(SubExpr, Result, Info))
1275 return APValue();
1276
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001277 // Apply float conversion if necessary.
1278 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbarf8abb942009-01-24 19:08:01 +00001279 return APValue(Result,
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001280 APFloat(Result.getSemantics(), APFloat::fcZero, false));
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001281 } else if (SubType->isIntegerType()) {
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001282 APSInt Result;
1283
1284 if (!EvaluateInteger(SubExpr, Result, Info))
1285 return APValue();
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001286
1287 // Apply integer conversion if necessary.
1288 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001289 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1290 Zero = 0;
1291 return APValue(Result, Zero);
Daniel Dunbaraffa0e32009-01-29 06:16:07 +00001292 } else if (const ComplexType *CT = SubType->getAsComplexType()) {
1293 APValue Src;
1294
1295 if (!EvaluateComplex(SubExpr, Src, Info))
1296 return APValue();
1297
1298 QualType SrcType = CT->getElementType();
1299
1300 if (Src.isComplexFloat()) {
1301 if (EltType->isRealFloatingType()) {
1302 return APValue(HandleFloatToFloatCast(EltType, SrcType,
1303 Src.getComplexFloatReal(),
1304 Info.Ctx),
1305 HandleFloatToFloatCast(EltType, SrcType,
1306 Src.getComplexFloatImag(),
1307 Info.Ctx));
1308 } else {
1309 return APValue(HandleFloatToIntCast(EltType, SrcType,
1310 Src.getComplexFloatReal(),
1311 Info.Ctx),
1312 HandleFloatToIntCast(EltType, SrcType,
1313 Src.getComplexFloatImag(),
1314 Info.Ctx));
1315 }
1316 } else {
1317 assert(Src.isComplexInt() && "Invalid evaluate result.");
1318 if (EltType->isRealFloatingType()) {
1319 return APValue(HandleIntToFloatCast(EltType, SrcType,
1320 Src.getComplexIntReal(),
1321 Info.Ctx),
1322 HandleIntToFloatCast(EltType, SrcType,
1323 Src.getComplexIntImag(),
1324 Info.Ctx));
1325 } else {
1326 return APValue(HandleIntToIntCast(EltType, SrcType,
1327 Src.getComplexIntReal(),
1328 Info.Ctx),
1329 HandleIntToIntCast(EltType, SrcType,
1330 Src.getComplexIntImag(),
1331 Info.Ctx));
1332 }
1333 }
Anders Carlssonad2794c2008-11-16 21:51:21 +00001334 }
1335
1336 // FIXME: Handle more casts.
1337 return APValue();
1338 }
1339
1340 APValue VisitBinaryOperator(const BinaryOperator *E);
1341
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001342};
1343} // end anonymous namespace
1344
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001345static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info)
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001346{
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001347 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1348 assert((!Result.isComplexFloat() ||
1349 (&Result.getComplexFloatReal().getSemantics() ==
1350 &Result.getComplexFloatImag().getSemantics())) &&
1351 "Invalid complex evaluation.");
1352 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001353}
1354
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001355APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
Anders Carlssonad2794c2008-11-16 21:51:21 +00001356{
1357 APValue Result, RHS;
1358
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001359 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001360 return APValue();
1361
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001362 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlssonad2794c2008-11-16 21:51:21 +00001363 return APValue();
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001364
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001365 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1366 "Invalid operands to binary operator.");
Anders Carlssonad2794c2008-11-16 21:51:21 +00001367 switch (E->getOpcode()) {
1368 default: return APValue();
1369 case BinaryOperator::Add:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001370 if (Result.isComplexFloat()) {
1371 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1372 APFloat::rmNearestTiesToEven);
1373 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1374 APFloat::rmNearestTiesToEven);
1375 } else {
1376 Result.getComplexIntReal() += RHS.getComplexIntReal();
1377 Result.getComplexIntImag() += RHS.getComplexIntImag();
1378 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001379 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001380 case BinaryOperator::Sub:
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001381 if (Result.isComplexFloat()) {
1382 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1383 APFloat::rmNearestTiesToEven);
1384 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1385 APFloat::rmNearestTiesToEven);
1386 } else {
1387 Result.getComplexIntReal() -= RHS.getComplexIntReal();
1388 Result.getComplexIntImag() -= RHS.getComplexIntImag();
1389 }
Daniel Dunbar00a9aad2009-01-29 01:32:56 +00001390 break;
1391 case BinaryOperator::Mul:
1392 if (Result.isComplexFloat()) {
1393 APValue LHS = Result;
1394 APFloat &LHS_r = LHS.getComplexFloatReal();
1395 APFloat &LHS_i = LHS.getComplexFloatImag();
1396 APFloat &RHS_r = RHS.getComplexFloatReal();
1397 APFloat &RHS_i = RHS.getComplexFloatImag();
1398
1399 APFloat Tmp = LHS_r;
1400 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1401 Result.getComplexFloatReal() = Tmp;
1402 Tmp = LHS_i;
1403 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1404 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
1405
1406 Tmp = LHS_r;
1407 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
1408 Result.getComplexFloatImag() = Tmp;
1409 Tmp = LHS_i;
1410 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
1411 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
1412 } else {
1413 APValue LHS = Result;
1414 Result.getComplexIntReal() =
1415 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
1416 LHS.getComplexIntImag() * RHS.getComplexIntImag());
1417 Result.getComplexIntImag() =
1418 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
1419 LHS.getComplexIntImag() * RHS.getComplexIntReal());
1420 }
1421 break;
Anders Carlssonad2794c2008-11-16 21:51:21 +00001422 }
1423
1424 return Result;
1425}
1426
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001427//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001428// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001429//===----------------------------------------------------------------------===//
1430
Chris Lattneref069662008-11-16 21:24:15 +00001431/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001432/// any crazy technique (that has nothing to do with language standards) that
1433/// we want to. If this function returns true, it returns the folded constant
1434/// in Result.
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001435bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
1436 EvalInfo Info(Ctx, Result);
Anders Carlssondd8d41f2008-11-30 16:38:33 +00001437
Nate Begemand6d2f772009-01-18 03:20:47 +00001438 if (getType()->isVectorType()) {
1439 if (!EvaluateVector(this, Result.Val, Info))
1440 return false;
1441 } else if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001442 llvm::APSInt sInt(32);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001443 if (!EvaluateInteger(this, sInt, Info))
1444 return false;
1445
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001446 Result.Val = APValue(sInt);
Mike Stump5b601ff2009-02-18 21:44:49 +00001447 } else if (getType()->isPointerType()
1448 || getType()->isBlockPointerType()) {
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001449 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001450 return false;
Eli Friedman2f445492008-08-22 00:06:13 +00001451 } else if (getType()->isRealFloatingType()) {
1452 llvm::APFloat f(0.0);
Anders Carlssonb96c2062008-11-22 21:50:49 +00001453 if (!EvaluateFloat(this, f, Info))
1454 return false;
1455
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001456 Result.Val = APValue(f);
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001457 } else if (getType()->isAnyComplexType()) {
1458 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlssonb96c2062008-11-22 21:50:49 +00001459 return false;
Daniel Dunbaraf781bb2009-01-28 22:24:07 +00001460 } else
Anders Carlssoncb6a2e82008-11-22 22:56:32 +00001461 return false;
Anders Carlssonb96c2062008-11-22 21:50:49 +00001462
Anders Carlsson7f5a96e2008-11-30 16:58:53 +00001463 return true;
1464}
1465
Chris Lattneref069662008-11-16 21:24:15 +00001466/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001467/// folded, but discard the result.
1468bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson197f6f72008-12-01 06:44:05 +00001469 EvalResult Result;
1470 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001471}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001472
1473APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson8c3de802008-12-19 20:58:05 +00001474 EvalResult EvalResult;
1475 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarddebeca2009-01-15 18:32:35 +00001476 Result = Result;
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001477 assert(Result && "Could not evaluate expression");
Anders Carlsson8c3de802008-12-19 20:58:05 +00001478 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001479
Anders Carlsson8c3de802008-12-19 20:58:05 +00001480 return EvalResult.Val.getInt();
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001481}