blob: 35cec0f3442c7a19ab06fd05d6366cbe187368b0 [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 Lattner82437da2008-07-12 00:14:42 +000018#include "clang/Basic/Diagnostic.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
42 /// isEvaluated - True if the subexpression is required to be evaluated, false
43 /// if it is short-circuited (according to C rules).
44 bool isEvaluated;
45
Chris Lattner82437da2008-07-12 00:14:42 +000046 /// ICEDiag - If the expression is unfoldable, then ICEDiag contains the
47 /// error diagnostic indicating why it is not foldable and DiagLoc indicates a
48 /// caret position for the error. If it is foldable, but the expression is
49 /// not an integer constant expression, ICEDiag contains the extension
50 /// diagnostic to emit which describes why it isn't an integer constant
51 /// expression. If this expression *is* an integer-constant-expr, then
52 /// ICEDiag is zero.
Chris Lattner422373c2008-07-11 22:52:41 +000053 ///
Chris Lattner82437da2008-07-12 00:14:42 +000054 /// The caller can choose to emit this diagnostic or not, depending on whether
55 /// they require an i-c-e or a constant or not. DiagLoc indicates the caret
56 /// position for the report.
57 ///
58 /// If ICEDiag is zero, then this expression is an i-c-e.
Chris Lattner422373c2008-07-11 22:52:41 +000059 unsigned ICEDiag;
60 SourceLocation DiagLoc;
61
62 EvalInfo(ASTContext &ctx) : Ctx(ctx), isEvaluated(true), ICEDiag(0) {}
63};
64
65
Eli Friedman7888b932008-11-12 09:44:48 +000066static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner422373c2008-07-11 22:52:41 +000067static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
68static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Eli Friedman2f445492008-08-22 00:06:13 +000069static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Anders Carlssonf1bb2962008-11-16 20:27:53 +000070static bool EvaluateComplexFloat(const Expr *E, APValue &Result,
71 EvalInfo &Info);
Chris Lattnera823ccf2008-07-11 18:11:29 +000072
73//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000074// Misc utilities
75//===----------------------------------------------------------------------===//
76
77static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
78 if (E->getType()->isIntegralType()) {
79 APSInt IntResult;
80 if (!EvaluateInteger(E, IntResult, Info))
81 return false;
82 Result = IntResult != 0;
83 return true;
84 } else if (E->getType()->isRealFloatingType()) {
85 APFloat FloatResult(0.0);
86 if (!EvaluateFloat(E, FloatResult, Info))
87 return false;
88 Result = !FloatResult.isZero();
89 return true;
90 } else if (E->getType()->isPointerType()) {
91 APValue PointerResult;
92 if (!EvaluatePointer(E, PointerResult, Info))
93 return false;
94 // FIXME: Is this accurate for all kinds of bases? If not, what would
95 // the check look like?
96 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
97 return true;
98 }
99
100 return false;
101}
102
103//===----------------------------------------------------------------------===//
104// LValue Evaluation
105//===----------------------------------------------------------------------===//
106namespace {
107class VISIBILITY_HIDDEN LValueExprEvaluator
108 : public StmtVisitor<LValueExprEvaluator, APValue> {
109 EvalInfo &Info;
110public:
111
112 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
113
114 APValue VisitStmt(Stmt *S) {
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000115#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000116 // FIXME: Remove this when we support more expressions.
117 printf("Unhandled pointer statement\n");
118 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000119#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000120 return APValue();
121 }
122
123 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
124 APValue VisitDeclRefExpr(DeclRefExpr *E) { return APValue(E, 0); }
125 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
126 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
127 APValue VisitMemberExpr(MemberExpr *E);
128 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson027f2882008-11-16 19:01:22 +0000129 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000130};
131} // end anonymous namespace
132
133static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
134 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
135 return Result.isLValue();
136}
137
138APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
139 if (E->isFileScope())
140 return APValue(E, 0);
141 return APValue();
142}
143
144APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
145 APValue result;
146 QualType Ty;
147 if (E->isArrow()) {
148 if (!EvaluatePointer(E->getBase(), result, Info))
149 return APValue();
150 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
151 } else {
152 result = Visit(E->getBase());
153 if (result.isUninit())
154 return APValue();
155 Ty = E->getBase()->getType();
156 }
157
158 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
159 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
160 FieldDecl *FD = E->getMemberDecl();
161
162 // FIXME: This is linear time.
163 unsigned i = 0, e = 0;
164 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
165 if (RD->getMember(i) == FD)
166 break;
167 }
168
169 result.setLValue(result.getLValueBase(),
170 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
171
172 return result;
173}
174
Anders Carlsson027f2882008-11-16 19:01:22 +0000175APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
176{
177 APValue Result;
178
179 if (!EvaluatePointer(E->getBase(), Result, Info))
180 return APValue();
181
182 APSInt Index;
183 if (!EvaluateInteger(E->getIdx(), Index, Info))
184 return APValue();
185
186 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
187
188 uint64_t Offset = Index.getSExtValue() * ElementSize;
189 Result.setLValue(Result.getLValueBase(),
190 Result.getLValueOffset() + Offset);
191 return Result;
192}
Eli Friedman7888b932008-11-12 09:44:48 +0000193
194//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000195// Pointer Evaluation
196//===----------------------------------------------------------------------===//
197
Anders Carlssoncad17b52008-07-08 05:13:58 +0000198namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000199class VISIBILITY_HIDDEN PointerExprEvaluator
200 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000201 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000202public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000203
Chris Lattner422373c2008-07-11 22:52:41 +0000204 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000205
Anders Carlsson02a34c32008-07-08 14:30:00 +0000206 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000207 return APValue();
208 }
209
210 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
211
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000212 APValue VisitBinaryOperator(const BinaryOperator *E);
213 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000214 APValue VisitUnaryOperator(const UnaryOperator *E);
215 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
216 { return APValue(E, 0); }
217 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000218};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000219} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000220
Chris Lattner422373c2008-07-11 22:52:41 +0000221static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000222 if (!E->getType()->isPointerType())
223 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000224 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000225 return Result.isLValue();
226}
227
228APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
229 if (E->getOpcode() != BinaryOperator::Add &&
230 E->getOpcode() != BinaryOperator::Sub)
231 return APValue();
232
233 const Expr *PExp = E->getLHS();
234 const Expr *IExp = E->getRHS();
235 if (IExp->getType()->isPointerType())
236 std::swap(PExp, IExp);
237
238 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000239 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000240 return APValue();
241
242 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000243 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000244 return APValue();
245
Eli Friedman7888b932008-11-12 09:44:48 +0000246 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
247 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
248
Chris Lattnera823ccf2008-07-11 18:11:29 +0000249 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000250
Chris Lattnera823ccf2008-07-11 18:11:29 +0000251 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000252 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000253 else
Eli Friedman7888b932008-11-12 09:44:48 +0000254 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
255
Chris Lattnera823ccf2008-07-11 18:11:29 +0000256 return APValue(ResultLValue.getLValueBase(), Offset);
257}
Eli Friedman7888b932008-11-12 09:44:48 +0000258
259APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
260 if (E->getOpcode() == UnaryOperator::Extension) {
261 // FIXME: Deal with warnings?
262 return Visit(E->getSubExpr());
263 }
264
265 if (E->getOpcode() == UnaryOperator::AddrOf) {
266 APValue result;
267 if (EvaluateLValue(E->getSubExpr(), result, Info))
268 return result;
269 }
270
271 return APValue();
272}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000273
274
Chris Lattnera42f09a2008-07-11 19:10:17 +0000275APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000276 const Expr* SubExpr = E->getSubExpr();
277
278 // Check for pointer->pointer cast
279 if (SubExpr->getType()->isPointerType()) {
280 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000281 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000282 return Result;
283 return APValue();
284 }
285
Eli Friedman3e64dd72008-07-27 05:46:18 +0000286 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000287 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000288 if (EvaluateInteger(SubExpr, Result, Info)) {
289 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000290 return APValue(0, Result.getZExtValue());
291 }
292 }
Eli Friedman7888b932008-11-12 09:44:48 +0000293
294 if (SubExpr->getType()->isFunctionType() ||
295 SubExpr->getType()->isArrayType()) {
296 APValue Result;
297 if (EvaluateLValue(SubExpr, Result, Info))
298 return Result;
299 return APValue();
300 }
301
302 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000303 return APValue();
304}
305
Eli Friedman7888b932008-11-12 09:44:48 +0000306APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
307 bool BoolResult;
308 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
309 return APValue();
310
311 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
312
313 APValue Result;
314 if (EvaluatePointer(EvalExpr, Result, Info))
315 return Result;
316 return APValue();
317}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000318
319//===----------------------------------------------------------------------===//
320// Integer Evaluation
321//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000322
323namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000324class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000325 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000326 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000327 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000328public:
Chris Lattner422373c2008-07-11 22:52:41 +0000329 IntExprEvaluator(EvalInfo &info, APSInt &result)
330 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000331
Chris Lattner2c99c712008-07-11 19:24:49 +0000332 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-07-12 00:14:42 +0000333 return (unsigned)Info.Ctx.getIntWidth(T);
334 }
335
336 bool Extension(SourceLocation L, diag::kind D) {
337 Info.DiagLoc = L;
338 Info.ICEDiag = D;
339 return true; // still a constant.
340 }
341
Chris Lattner438f3b12008-11-12 07:43:42 +0000342 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner82437da2008-07-12 00:14:42 +0000343 // If this is in an unevaluated portion of the subexpression, ignore the
344 // error.
Chris Lattner438f3b12008-11-12 07:43:42 +0000345 if (!Info.isEvaluated) {
346 // If error is ignored because the value isn't evaluated, get the real
347 // type at least to prevent errors downstream.
348 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
349 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000350 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000351 }
Chris Lattner82437da2008-07-12 00:14:42 +0000352
Chris Lattner438f3b12008-11-12 07:43:42 +0000353 // Take the first error.
354 if (Info.ICEDiag == 0) {
355 Info.DiagLoc = L;
356 Info.ICEDiag = D;
357 }
Chris Lattner82437da2008-07-12 00:14:42 +0000358 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000359 }
360
Anders Carlssoncad17b52008-07-08 05:13:58 +0000361 //===--------------------------------------------------------------------===//
362 // Visitor Methods
363 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000364
365 bool VisitStmt(Stmt *) {
366 assert(0 && "This should be called on integers, stmts are not integers");
367 return false;
368 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000369
Chris Lattner438f3b12008-11-12 07:43:42 +0000370 bool VisitExpr(Expr *E) {
371 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssoncad17b52008-07-08 05:13:58 +0000372 }
373
Chris Lattnera42f09a2008-07-11 19:10:17 +0000374 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000375
Chris Lattner15e59112008-07-12 00:38:25 +0000376 bool VisitIntegerLiteral(const IntegerLiteral *E) {
377 Result = E->getValue();
378 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
379 return true;
380 }
381 bool VisitCharacterLiteral(const CharacterLiteral *E) {
382 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
383 Result = E->getValue();
384 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
385 return true;
386 }
387 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
388 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000389 // Per gcc docs "this built-in function ignores top level
390 // qualifiers". We need to use the canonical version to properly
391 // be able to strip CRV qualifiers from the type.
392 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
393 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
394 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
395 T1.getUnqualifiedType());
Chris Lattner15e59112008-07-12 00:38:25 +0000396 return true;
397 }
398 bool VisitDeclRefExpr(const DeclRefExpr *E);
399 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000400 bool VisitBinaryOperator(const BinaryOperator *E);
401 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000402 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000403
Chris Lattnerff579ff2008-07-12 01:15:53 +0000404 bool VisitCastExpr(CastExpr* E) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000405 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000406 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000407 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
408
Anders Carlsson027f2882008-11-16 19:01:22 +0000409 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000410 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson027f2882008-11-16 19:01:22 +0000411 Result = E->getValue();
412 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
413 return true;
414 }
415
416 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
417 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
418 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
419 return true;
420 }
421
Chris Lattner265a0892008-07-11 21:24:13 +0000422private:
Chris Lattnerff579ff2008-07-12 01:15:53 +0000423 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000424};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000425} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000426
Chris Lattner422373c2008-07-11 22:52:41 +0000427static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
428 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000429}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000430
Chris Lattner15e59112008-07-12 00:38:25 +0000431bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
432 // Enums are integer constant exprs.
433 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
434 Result = D->getInitVal();
435 return true;
436 }
437
438 // Otherwise, random variable references are not constants.
Chris Lattner438f3b12008-11-12 07:43:42 +0000439 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner15e59112008-07-12 00:38:25 +0000440}
441
Chris Lattner1eee9402008-10-06 06:40:35 +0000442/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
443/// as GCC.
444static int EvaluateBuiltinClassifyType(const CallExpr *E) {
445 // The following enum mimics the values returned by GCC.
446 enum gcc_type_class {
447 no_type_class = -1,
448 void_type_class, integer_type_class, char_type_class,
449 enumeral_type_class, boolean_type_class,
450 pointer_type_class, reference_type_class, offset_type_class,
451 real_type_class, complex_type_class,
452 function_type_class, method_type_class,
453 record_type_class, union_type_class,
454 array_type_class, string_type_class,
455 lang_type_class
456 };
457
458 // If no argument was supplied, default to "no_type_class". This isn't
459 // ideal, however it is what gcc does.
460 if (E->getNumArgs() == 0)
461 return no_type_class;
462
463 QualType ArgTy = E->getArg(0)->getType();
464 if (ArgTy->isVoidType())
465 return void_type_class;
466 else if (ArgTy->isEnumeralType())
467 return enumeral_type_class;
468 else if (ArgTy->isBooleanType())
469 return boolean_type_class;
470 else if (ArgTy->isCharType())
471 return string_type_class; // gcc doesn't appear to use char_type_class
472 else if (ArgTy->isIntegerType())
473 return integer_type_class;
474 else if (ArgTy->isPointerType())
475 return pointer_type_class;
476 else if (ArgTy->isReferenceType())
477 return reference_type_class;
478 else if (ArgTy->isRealType())
479 return real_type_class;
480 else if (ArgTy->isComplexType())
481 return complex_type_class;
482 else if (ArgTy->isFunctionType())
483 return function_type_class;
484 else if (ArgTy->isStructureType())
485 return record_type_class;
486 else if (ArgTy->isUnionType())
487 return union_type_class;
488 else if (ArgTy->isArrayType())
489 return array_type_class;
490 else if (ArgTy->isUnionType())
491 return union_type_class;
492 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
493 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
494 return -1;
495}
496
Chris Lattner15e59112008-07-12 00:38:25 +0000497bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
498 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000499
Chris Lattner87293782008-10-06 05:28:25 +0000500 switch (E->isBuiltinCall()) {
501 default:
Chris Lattner438f3b12008-11-12 07:43:42 +0000502 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner87293782008-10-06 05:28:25 +0000503 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000504 Result.setIsSigned(true);
505 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000506 return true;
507
508 case Builtin::BI__builtin_constant_p: {
509 // __builtin_constant_p always has one operand: it returns true if that
510 // operand can be folded, false otherwise.
511 APValue Res;
Chris Lattneref069662008-11-16 21:24:15 +0000512 Result = E->getArg(0)->Evaluate(Res, Info.Ctx);
Chris Lattner87293782008-10-06 05:28:25 +0000513 return true;
514 }
515 }
Chris Lattner15e59112008-07-12 00:38:25 +0000516}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000517
Chris Lattnera42f09a2008-07-11 19:10:17 +0000518bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000519 if (E->getOpcode() == BinaryOperator::Comma) {
520 // Evaluate the side that actually matters; this needs to be
521 // handled specially because calling Visit() on the LHS can
522 // have strange results when it doesn't have an integral type.
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000523 if (Visit(E->getRHS()))
524 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000525
526 // Check for isEvaluated; the idea is that this might eventually
527 // be useful for isICE and other similar uses that care about
528 // whether a comma is evaluated. This isn't really used yet, though,
529 // and I'm not sure it really works as intended.
530 if (!Info.isEvaluated)
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000531 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
Eli Friedman14cc7542008-11-13 06:09:17 +0000532
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000533 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000534 }
535
536 if (E->isLogicalOp()) {
537 // These need to be handled specially because the operands aren't
538 // necessarily integral
539 bool bres;
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000540
541 if (HandleConversionToBool(E->getLHS(), bres, Info)) {
542 // We were able to evaluate the LHS, see if we can get away with not
543 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
544 } else {
Eli Friedman14cc7542008-11-13 06:09:17 +0000545 // We can't evaluate the LHS; however, sometimes the result
546 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000547 if (!HandleConversionToBool(E->getRHS(), bres, Info)) {
548 // We can't evaluate.
549 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000550 }
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000551 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000552
Anders Carlssone8bd9f22008-11-22 21:04:56 +0000553 // FIXME: If we evaluate the RHS, we need to check if the LHS has
554 // any side effects.
555
556 if (bres == (E->getOpcode() == BinaryOperator::LOr) ||
557 !bres == (E->getOpcode() == BinaryOperator::LAnd)) {
558 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
559 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
560 Result = bres;
561 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000562 }
563
564 bool bres2;
565 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
566 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
567 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
568 if (E->getOpcode() == BinaryOperator::LOr)
569 Result = bres || bres2;
570 else
571 Result = bres && bres2;
572 return true;
573 }
574 return false;
575 }
576
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000577 QualType LHSTy = E->getLHS()->getType();
578 QualType RHSTy = E->getRHS()->getType();
579
580 if (LHSTy->isRealFloatingType() &&
581 RHSTy->isRealFloatingType()) {
582 APFloat RHS(0.0), LHS(0.0);
583
584 if (!EvaluateFloat(E->getRHS(), RHS, Info))
585 return false;
586
587 if (!EvaluateFloat(E->getLHS(), LHS, Info))
588 return false;
589
590 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000591
592 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
593
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000594 switch (E->getOpcode()) {
595 default:
596 assert(0 && "Invalid binary operator!");
597 case BinaryOperator::LT:
598 Result = CR == APFloat::cmpLessThan;
599 break;
600 case BinaryOperator::GT:
601 Result = CR == APFloat::cmpGreaterThan;
602 break;
603 case BinaryOperator::LE:
604 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
605 break;
606 case BinaryOperator::GE:
607 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
608 break;
609 case BinaryOperator::EQ:
610 Result = CR == APFloat::cmpEqual;
611 break;
612 case BinaryOperator::NE:
613 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
614 break;
615 }
616
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000617 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
618 return true;
619 }
620
Anders Carlsson027f2882008-11-16 19:01:22 +0000621 if (E->getOpcode() == BinaryOperator::Sub) {
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000622 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Anders Carlsson027f2882008-11-16 19:01:22 +0000623 APValue LHSValue;
624 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
625 return false;
626
627 APValue RHSValue;
628 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
629 return false;
630
631 // FIXME: Is this correct? What if only one of the operands has a base?
632 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
633 return false;
634
635 const QualType Type = E->getLHS()->getType();
636 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
637
638 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
639 D /= Info.Ctx.getTypeSize(ElementType) / 8;
640
Anders Carlsson027f2882008-11-16 19:01:22 +0000641 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Anders Carlsson02bb9c32008-11-16 22:46:56 +0000642 Result = D;
Anders Carlsson027f2882008-11-16 19:01:22 +0000643 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
644
645 return true;
646 }
647 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000648 if (!LHSTy->isIntegralType() ||
649 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000650 // We can't continue from here for non-integral types, and they
651 // could potentially confuse the following operations.
652 // FIXME: Deal with EQ and friends.
653 return false;
654 }
655
Anders Carlssond1aa5812008-07-08 14:35:21 +0000656 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000657 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000658 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000659 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000660 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000661
Eli Friedman3e64dd72008-07-27 05:46:18 +0000662
663 // FIXME Maybe we want to succeed even where we can't evaluate the
664 // right side of LAnd/LOr?
665 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000666 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000667 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000668
Anders Carlssond1aa5812008-07-08 14:35:21 +0000669 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000670 default:
671 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner82437da2008-07-12 00:14:42 +0000672 case BinaryOperator::Mul: Result *= RHS; return true;
673 case BinaryOperator::Add: Result += RHS; return true;
674 case BinaryOperator::Sub: Result -= RHS; return true;
675 case BinaryOperator::And: Result &= RHS; return true;
676 case BinaryOperator::Xor: Result ^= RHS; return true;
677 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000678 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000679 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000680 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
681 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000682 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000683 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000684 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000685 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000686 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
687 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000688 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000689 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000690 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000691 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000692 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000693 break;
694 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000695 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000696 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000697
Chris Lattner045502c2008-07-11 19:29:32 +0000698 case BinaryOperator::LT:
699 Result = Result < RHS;
700 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
701 break;
702 case BinaryOperator::GT:
703 Result = Result > RHS;
704 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
705 break;
706 case BinaryOperator::LE:
707 Result = Result <= RHS;
708 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
709 break;
710 case BinaryOperator::GE:
711 Result = Result >= RHS;
712 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
713 break;
714 case BinaryOperator::EQ:
715 Result = Result == RHS;
716 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
717 break;
718 case BinaryOperator::NE:
719 Result = Result != RHS;
720 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
721 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000722 case BinaryOperator::LAnd:
723 Result = Result != 0 && RHS != 0;
724 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
725 break;
726 case BinaryOperator::LOr:
727 Result = Result != 0 || RHS != 0;
728 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
729 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000730 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000731
732 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000733 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000734}
735
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000736bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes308de752008-11-16 22:06:39 +0000737 bool Cond;
738 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000739 return false;
740
Nuno Lopes308de752008-11-16 22:06:39 +0000741 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000742}
743
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000744/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
745/// expression's type.
746bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
747 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000748 // Return the result in the right width.
749 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
750 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
751
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000752 QualType SrcTy = E->getTypeOfArgument();
753
Chris Lattner265a0892008-07-11 21:24:13 +0000754 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000755 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000756 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000757 return true;
758 }
Chris Lattner265a0892008-07-11 21:24:13 +0000759
760 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000761 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000762 if (!SrcTy->isConstantSizeType()) {
763 // FIXME: Should we attempt to evaluate this?
764 return false;
765 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000766
767 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000768
769 // GCC extension: sizeof(function) = 1.
770 if (SrcTy->isFunctionType()) {
771 // FIXME: AlignOf shouldn't be unconditionally 4!
772 Result = isSizeOf ? 1 : 4;
773 return true;
774 }
775
776 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000777 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000778 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000779 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000780 else
Chris Lattner422373c2008-07-11 22:52:41 +0000781 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000782 return true;
783}
784
Chris Lattnera42f09a2008-07-11 19:10:17 +0000785bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000786 // Special case unary operators that do not need their subexpression
787 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000788 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000789 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000790 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000791 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
792 return true;
793 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000794
795 if (E->getOpcode() == UnaryOperator::LNot) {
796 // LNot's operand isn't necessarily an integer, so we handle it specially.
797 bool bres;
798 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
799 return false;
800 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
801 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
802 Result = !bres;
803 return true;
804 }
805
Chris Lattner422373c2008-07-11 22:52:41 +0000806 // Get the operand value into 'Result'.
807 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000808 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000809
Chris Lattner400d7402008-07-11 22:15:16 +0000810 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000811 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000812 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
813 // See C99 6.6p3.
Chris Lattner438f3b12008-11-12 07:43:42 +0000814 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
815 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000816 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000817 // FIXME: Should extension allow i-c-e extension expressions in its scope?
818 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000819 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000820 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000821 break;
822 case UnaryOperator::Minus:
823 Result = -Result;
824 break;
825 case UnaryOperator::Not:
826 Result = ~Result;
827 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000828 }
829
830 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000831 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000832}
833
Chris Lattnerff579ff2008-07-12 01:15:53 +0000834/// HandleCast - This is used to evaluate implicit or explicit casts where the
835/// result type is integer.
836bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
837 Expr *SubExpr, QualType DestType) {
Chris Lattner2c99c712008-07-11 19:24:49 +0000838 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000839
Eli Friedman7888b932008-11-12 09:44:48 +0000840 if (DestType->isBooleanType()) {
841 bool BoolResult;
842 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
843 return false;
844 Result.zextOrTrunc(DestWidth);
845 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
846 Result = BoolResult;
847 return true;
848 }
849
Anders Carlssond1aa5812008-07-08 14:35:21 +0000850 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +0000851 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000852 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000853 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000854
855 // Figure out if this is a truncate, extend or noop cast.
856 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000857 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000858 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
859 return true;
860 }
861
862 // FIXME: Clean this up!
863 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000864 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000865 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000866 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000867
Anders Carlssond1aa5812008-07-08 14:35:21 +0000868 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000869 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000870
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000871 Result.extOrTrunc(DestWidth);
872 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000873 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
874 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000875 }
Eli Friedman7888b932008-11-12 09:44:48 +0000876
Chris Lattnerff579ff2008-07-12 01:15:53 +0000877 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner438f3b12008-11-12 07:43:42 +0000878 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000879
Eli Friedman2f445492008-08-22 00:06:13 +0000880 APFloat F(0.0);
881 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner438f3b12008-11-12 07:43:42 +0000882 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000883
884 // Determine whether we are converting to unsigned or signed.
885 bool DestSigned = DestType->isSignedIntegerType();
886
887 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000888 uint64_t Space[4];
889 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000890 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000891 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000892 Result = llvm::APInt(DestWidth, 4, Space);
893 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000894 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000895}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000896
Chris Lattnera823ccf2008-07-11 18:11:29 +0000897//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000898// Float Evaluation
899//===----------------------------------------------------------------------===//
900
901namespace {
902class VISIBILITY_HIDDEN FloatExprEvaluator
903 : public StmtVisitor<FloatExprEvaluator, bool> {
904 EvalInfo &Info;
905 APFloat &Result;
906public:
907 FloatExprEvaluator(EvalInfo &info, APFloat &result)
908 : Info(info), Result(result) {}
909
910 bool VisitStmt(Stmt *S) {
911 return false;
912 }
913
914 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000915 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000916
Daniel Dunbar804ead02008-10-16 03:51:50 +0000917 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000918 bool VisitBinaryOperator(const BinaryOperator *E);
919 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000920 bool VisitCastExpr(CastExpr *E);
921 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000922};
923} // end anonymous namespace
924
925static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
926 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
927}
928
Chris Lattner87293782008-10-06 05:28:25 +0000929bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000930 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000931 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000932 case Builtin::BI__builtin_huge_val:
933 case Builtin::BI__builtin_huge_valf:
934 case Builtin::BI__builtin_huge_vall:
935 case Builtin::BI__builtin_inf:
936 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000937 case Builtin::BI__builtin_infl: {
938 const llvm::fltSemantics &Sem =
939 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000940 Result = llvm::APFloat::getInf(Sem);
941 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000942 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000943
944 case Builtin::BI__builtin_nan:
945 case Builtin::BI__builtin_nanf:
946 case Builtin::BI__builtin_nanl:
947 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
948 // can't constant fold it.
949 if (const StringLiteral *S =
950 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
951 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000952 const llvm::fltSemantics &Sem =
953 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000954 Result = llvm::APFloat::getNaN(Sem);
955 return true;
956 }
957 }
958 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000959
960 case Builtin::BI__builtin_fabs:
961 case Builtin::BI__builtin_fabsf:
962 case Builtin::BI__builtin_fabsl:
963 if (!EvaluateFloat(E->getArg(0), Result, Info))
964 return false;
965
966 if (Result.isNegative())
967 Result.changeSign();
968 return true;
969
970 case Builtin::BI__builtin_copysign:
971 case Builtin::BI__builtin_copysignf:
972 case Builtin::BI__builtin_copysignl: {
973 APFloat RHS(0.);
974 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
975 !EvaluateFloat(E->getArg(1), RHS, Info))
976 return false;
977 Result.copySign(RHS);
978 return true;
979 }
Chris Lattner87293782008-10-06 05:28:25 +0000980 }
981}
982
Daniel Dunbar804ead02008-10-16 03:51:50 +0000983bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes1cea4f42008-11-19 17:44:31 +0000984 if (E->getOpcode() == UnaryOperator::Deref)
985 return false;
986
Daniel Dunbar804ead02008-10-16 03:51:50 +0000987 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
988 return false;
989
990 switch (E->getOpcode()) {
991 default: return false;
992 case UnaryOperator::Plus:
993 return true;
994 case UnaryOperator::Minus:
995 Result.changeSign();
996 return true;
997 }
998}
Chris Lattner87293782008-10-06 05:28:25 +0000999
Eli Friedman2f445492008-08-22 00:06:13 +00001000bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
1001 // FIXME: Diagnostics? I really don't understand how the warnings
1002 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +00001003 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +00001004 if (!EvaluateFloat(E->getLHS(), Result, Info))
1005 return false;
1006 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1007 return false;
1008
1009 switch (E->getOpcode()) {
1010 default: return false;
1011 case BinaryOperator::Mul:
1012 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1013 return true;
1014 case BinaryOperator::Add:
1015 Result.add(RHS, APFloat::rmNearestTiesToEven);
1016 return true;
1017 case BinaryOperator::Sub:
1018 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1019 return true;
1020 case BinaryOperator::Div:
1021 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1022 return true;
1023 case BinaryOperator::Rem:
1024 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1025 return true;
1026 }
1027}
1028
1029bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1030 Result = E->getValue();
1031 return true;
1032}
1033
Eli Friedman7888b932008-11-12 09:44:48 +00001034bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1035 Expr* SubExpr = E->getSubExpr();
1036 const llvm::fltSemantics& destSemantics =
1037 Info.Ctx.getFloatTypeSemantics(E->getType());
1038 if (SubExpr->getType()->isIntegralType()) {
1039 APSInt IntResult;
1040 if (!EvaluateInteger(E, IntResult, Info))
1041 return false;
1042 Result = APFloat(destSemantics, 1);
1043 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1044 APFloat::rmNearestTiesToEven);
1045 return true;
1046 }
1047 if (SubExpr->getType()->isRealFloatingType()) {
1048 if (!Visit(SubExpr))
1049 return false;
1050 bool ignored;
1051 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1052 return true;
1053 }
1054
1055 return false;
1056}
1057
1058bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1059 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1060 return true;
1061}
1062
Eli Friedman2f445492008-08-22 00:06:13 +00001063//===----------------------------------------------------------------------===//
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001064// Complex Float Evaluation
1065//===----------------------------------------------------------------------===//
1066
1067namespace {
1068class VISIBILITY_HIDDEN ComplexFloatExprEvaluator
1069 : public StmtVisitor<ComplexFloatExprEvaluator, APValue> {
1070 EvalInfo &Info;
1071
1072public:
1073 ComplexFloatExprEvaluator(EvalInfo &info) : Info(info) {}
1074
1075 //===--------------------------------------------------------------------===//
1076 // Visitor Methods
1077 //===--------------------------------------------------------------------===//
1078
1079 APValue VisitStmt(Stmt *S) {
1080 assert(0 && "This should be called on complex floats");
1081 return APValue();
1082 }
1083
1084 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1085
1086 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
1087 APFloat Result(0.0);
1088 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1089 return APValue();
1090
1091 return APValue(APFloat(0.0), Result);
1092 }
1093
Anders Carlssonad2794c2008-11-16 21:51:21 +00001094 APValue VisitCastExpr(CastExpr *E) {
1095 Expr* SubExpr = E->getSubExpr();
1096
1097 if (SubExpr->getType()->isRealFloatingType()) {
1098 APFloat Result(0.0);
1099
1100 if (!EvaluateFloat(SubExpr, Result, Info))
1101 return APValue();
1102
1103 return APValue(Result, APFloat(0.0));
1104 }
1105
1106 // FIXME: Handle more casts.
1107 return APValue();
1108 }
1109
1110 APValue VisitBinaryOperator(const BinaryOperator *E);
1111
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001112};
1113} // end anonymous namespace
1114
1115static bool EvaluateComplexFloat(const Expr *E, APValue &Result, EvalInfo &Info)
1116{
1117 Result = ComplexFloatExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1118 return Result.isComplexFloat();
1119}
1120
Anders Carlssonad2794c2008-11-16 21:51:21 +00001121APValue ComplexFloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E)
1122{
1123 APValue Result, RHS;
1124
1125 if (!EvaluateComplexFloat(E->getLHS(), Result, Info))
1126 return APValue();
1127
1128 if (!EvaluateComplexFloat(E->getRHS(), RHS, Info))
1129 return APValue();
1130
1131 switch (E->getOpcode()) {
1132 default: return APValue();
1133 case BinaryOperator::Add:
1134 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
1135 APFloat::rmNearestTiesToEven);
1136 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
1137 APFloat::rmNearestTiesToEven);
1138 case BinaryOperator::Sub:
1139 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
1140 APFloat::rmNearestTiesToEven);
1141 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
1142 APFloat::rmNearestTiesToEven);
1143 }
1144
1145 return Result;
1146}
1147
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001148//===----------------------------------------------------------------------===//
Chris Lattneref069662008-11-16 21:24:15 +00001149// Top level Expr::Evaluate method.
Chris Lattnera823ccf2008-07-11 18:11:29 +00001150//===----------------------------------------------------------------------===//
1151
Chris Lattneref069662008-11-16 21:24:15 +00001152/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner87293782008-10-06 05:28:25 +00001153/// any crazy technique (that has nothing to do with language standards) that
1154/// we want to. If this function returns true, it returns the folded constant
1155/// in Result.
Chris Lattneref069662008-11-16 21:24:15 +00001156bool Expr::Evaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner422373c2008-07-11 22:52:41 +00001157 EvalInfo Info(Ctx);
Anders Carlssonc0328012008-07-08 05:49:43 +00001158 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001159 llvm::APSInt sInt(32);
Chris Lattner422373c2008-07-11 22:52:41 +00001160 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlssonc0328012008-07-08 05:49:43 +00001161 Result = APValue(sInt);
1162 return true;
1163 }
Eli Friedman2f445492008-08-22 00:06:13 +00001164 } else if (getType()->isPointerType()) {
1165 if (EvaluatePointer(this, Result, Info)) {
1166 return true;
1167 }
1168 } else if (getType()->isRealFloatingType()) {
1169 llvm::APFloat f(0.0);
1170 if (EvaluateFloat(this, f, Info)) {
1171 Result = APValue(f);
1172 return true;
1173 }
Anders Carlssonf1bb2962008-11-16 20:27:53 +00001174 } else if (getType()->isComplexType()) {
1175 if (EvaluateComplexFloat(this, Result, Info))
1176 return true;
1177 }
Anders Carlsson47968a92008-08-10 17:03:01 +00001178
Anders Carlssonc7436af2008-07-03 04:20:39 +00001179 return false;
1180}
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001181
Chris Lattneref069662008-11-16 21:24:15 +00001182/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001183/// folded, but discard the result.
1184bool Expr::isEvaluatable(ASTContext &Ctx) const {
1185 APValue V;
Chris Lattneref069662008-11-16 21:24:15 +00001186 return Evaluate(V, Ctx);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001187}
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001188
1189APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
1190 APValue V;
1191 bool Result = Evaluate(V, Ctx);
1192 assert(Result && "Could not evaluate expression");
1193 assert(V.isInt() && "Expression did not evaluate to integer");
1194
1195 return V.getInt();
1196}