blob: 0ffbf581a2c1901824b02a4a5a8ee6da52f58098 [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);
Chris Lattnera823ccf2008-07-11 18:11:29 +000070
71//===----------------------------------------------------------------------===//
Eli Friedman7888b932008-11-12 09:44:48 +000072// Misc utilities
73//===----------------------------------------------------------------------===//
74
75static bool HandleConversionToBool(Expr* E, bool& Result, EvalInfo &Info) {
76 if (E->getType()->isIntegralType()) {
77 APSInt IntResult;
78 if (!EvaluateInteger(E, IntResult, Info))
79 return false;
80 Result = IntResult != 0;
81 return true;
82 } else if (E->getType()->isRealFloatingType()) {
83 APFloat FloatResult(0.0);
84 if (!EvaluateFloat(E, FloatResult, Info))
85 return false;
86 Result = !FloatResult.isZero();
87 return true;
88 } else if (E->getType()->isPointerType()) {
89 APValue PointerResult;
90 if (!EvaluatePointer(E, PointerResult, Info))
91 return false;
92 // FIXME: Is this accurate for all kinds of bases? If not, what would
93 // the check look like?
94 Result = PointerResult.getLValueBase() || PointerResult.getLValueOffset();
95 return true;
96 }
97
98 return false;
99}
100
101//===----------------------------------------------------------------------===//
102// LValue Evaluation
103//===----------------------------------------------------------------------===//
104namespace {
105class VISIBILITY_HIDDEN LValueExprEvaluator
106 : public StmtVisitor<LValueExprEvaluator, APValue> {
107 EvalInfo &Info;
108public:
109
110 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
111
112 APValue VisitStmt(Stmt *S) {
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000113#if 0
Eli Friedman7888b932008-11-12 09:44:48 +0000114 // FIXME: Remove this when we support more expressions.
115 printf("Unhandled pointer statement\n");
116 S->dump();
Daniel Dunbarff59ed82008-11-12 21:52:46 +0000117#endif
Eli Friedman7888b932008-11-12 09:44:48 +0000118 return APValue();
119 }
120
121 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
122 APValue VisitDeclRefExpr(DeclRefExpr *E) { return APValue(E, 0); }
123 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E, 0); }
124 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
125 APValue VisitMemberExpr(MemberExpr *E);
126 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E, 0); }
Anders Carlsson027f2882008-11-16 19:01:22 +0000127 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000128};
129} // end anonymous namespace
130
131static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
132 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
133 return Result.isLValue();
134}
135
136APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
137 if (E->isFileScope())
138 return APValue(E, 0);
139 return APValue();
140}
141
142APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
143 APValue result;
144 QualType Ty;
145 if (E->isArrow()) {
146 if (!EvaluatePointer(E->getBase(), result, Info))
147 return APValue();
148 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
149 } else {
150 result = Visit(E->getBase());
151 if (result.isUninit())
152 return APValue();
153 Ty = E->getBase()->getType();
154 }
155
156 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
157 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
158 FieldDecl *FD = E->getMemberDecl();
159
160 // FIXME: This is linear time.
161 unsigned i = 0, e = 0;
162 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
163 if (RD->getMember(i) == FD)
164 break;
165 }
166
167 result.setLValue(result.getLValueBase(),
168 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
169
170 return result;
171}
172
Anders Carlsson027f2882008-11-16 19:01:22 +0000173APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E)
174{
175 APValue Result;
176
177 if (!EvaluatePointer(E->getBase(), Result, Info))
178 return APValue();
179
180 APSInt Index;
181 if (!EvaluateInteger(E->getIdx(), Index, Info))
182 return APValue();
183
184 uint64_t ElementSize = Info.Ctx.getTypeSize(E->getType()) / 8;
185
186 uint64_t Offset = Index.getSExtValue() * ElementSize;
187 Result.setLValue(Result.getLValueBase(),
188 Result.getLValueOffset() + Offset);
189 return Result;
190}
Eli Friedman7888b932008-11-12 09:44:48 +0000191
192//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000193// Pointer Evaluation
194//===----------------------------------------------------------------------===//
195
Anders Carlssoncad17b52008-07-08 05:13:58 +0000196namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000197class VISIBILITY_HIDDEN PointerExprEvaluator
198 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000199 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000200public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000201
Chris Lattner422373c2008-07-11 22:52:41 +0000202 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000203
Anders Carlsson02a34c32008-07-08 14:30:00 +0000204 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000205 return APValue();
206 }
207
208 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
209
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000210 APValue VisitBinaryOperator(const BinaryOperator *E);
211 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-11-12 09:44:48 +0000212 APValue VisitUnaryOperator(const UnaryOperator *E);
213 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
214 { return APValue(E, 0); }
215 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000216};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000217} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000218
Chris Lattner422373c2008-07-11 22:52:41 +0000219static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000220 if (!E->getType()->isPointerType())
221 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000222 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000223 return Result.isLValue();
224}
225
226APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
227 if (E->getOpcode() != BinaryOperator::Add &&
228 E->getOpcode() != BinaryOperator::Sub)
229 return APValue();
230
231 const Expr *PExp = E->getLHS();
232 const Expr *IExp = E->getRHS();
233 if (IExp->getType()->isPointerType())
234 std::swap(PExp, IExp);
235
236 APValue ResultLValue;
Chris Lattner422373c2008-07-11 22:52:41 +0000237 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000238 return APValue();
239
240 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000241 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000242 return APValue();
243
Eli Friedman7888b932008-11-12 09:44:48 +0000244 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
245 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
246
Chris Lattnera823ccf2008-07-11 18:11:29 +0000247 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000248
Chris Lattnera823ccf2008-07-11 18:11:29 +0000249 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000250 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000251 else
Eli Friedman7888b932008-11-12 09:44:48 +0000252 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
253
Chris Lattnera823ccf2008-07-11 18:11:29 +0000254 return APValue(ResultLValue.getLValueBase(), Offset);
255}
Eli Friedman7888b932008-11-12 09:44:48 +0000256
257APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
258 if (E->getOpcode() == UnaryOperator::Extension) {
259 // FIXME: Deal with warnings?
260 return Visit(E->getSubExpr());
261 }
262
263 if (E->getOpcode() == UnaryOperator::AddrOf) {
264 APValue result;
265 if (EvaluateLValue(E->getSubExpr(), result, Info))
266 return result;
267 }
268
269 return APValue();
270}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000271
272
Chris Lattnera42f09a2008-07-11 19:10:17 +0000273APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000274 const Expr* SubExpr = E->getSubExpr();
275
276 // Check for pointer->pointer cast
277 if (SubExpr->getType()->isPointerType()) {
278 APValue Result;
Chris Lattner422373c2008-07-11 22:52:41 +0000279 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000280 return Result;
281 return APValue();
282 }
283
Eli Friedman3e64dd72008-07-27 05:46:18 +0000284 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000285 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000286 if (EvaluateInteger(SubExpr, Result, Info)) {
287 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000288 return APValue(0, Result.getZExtValue());
289 }
290 }
Eli Friedman7888b932008-11-12 09:44:48 +0000291
292 if (SubExpr->getType()->isFunctionType() ||
293 SubExpr->getType()->isArrayType()) {
294 APValue Result;
295 if (EvaluateLValue(SubExpr, Result, Info))
296 return Result;
297 return APValue();
298 }
299
300 //assert(0 && "Unhandled cast");
Chris Lattnera823ccf2008-07-11 18:11:29 +0000301 return APValue();
302}
303
Eli Friedman7888b932008-11-12 09:44:48 +0000304APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
305 bool BoolResult;
306 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
307 return APValue();
308
309 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
310
311 APValue Result;
312 if (EvaluatePointer(EvalExpr, Result, Info))
313 return Result;
314 return APValue();
315}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000316
317//===----------------------------------------------------------------------===//
318// Integer Evaluation
319//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000320
321namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000322class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000323 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000324 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000325 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000326public:
Chris Lattner422373c2008-07-11 22:52:41 +0000327 IntExprEvaluator(EvalInfo &info, APSInt &result)
328 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000329
Chris Lattner2c99c712008-07-11 19:24:49 +0000330 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-07-12 00:14:42 +0000331 return (unsigned)Info.Ctx.getIntWidth(T);
332 }
333
334 bool Extension(SourceLocation L, diag::kind D) {
335 Info.DiagLoc = L;
336 Info.ICEDiag = D;
337 return true; // still a constant.
338 }
339
Chris Lattner438f3b12008-11-12 07:43:42 +0000340 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner82437da2008-07-12 00:14:42 +0000341 // If this is in an unevaluated portion of the subexpression, ignore the
342 // error.
Chris Lattner438f3b12008-11-12 07:43:42 +0000343 if (!Info.isEvaluated) {
344 // If error is ignored because the value isn't evaluated, get the real
345 // type at least to prevent errors downstream.
346 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
347 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner82437da2008-07-12 00:14:42 +0000348 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000349 }
Chris Lattner82437da2008-07-12 00:14:42 +0000350
Chris Lattner438f3b12008-11-12 07:43:42 +0000351 // Take the first error.
352 if (Info.ICEDiag == 0) {
353 Info.DiagLoc = L;
354 Info.ICEDiag = D;
355 }
Chris Lattner82437da2008-07-12 00:14:42 +0000356 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000357 }
358
Anders Carlssoncad17b52008-07-08 05:13:58 +0000359 //===--------------------------------------------------------------------===//
360 // Visitor Methods
361 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-11-12 07:43:42 +0000362
363 bool VisitStmt(Stmt *) {
364 assert(0 && "This should be called on integers, stmts are not integers");
365 return false;
366 }
Chris Lattner2c99c712008-07-11 19:24:49 +0000367
Chris Lattner438f3b12008-11-12 07:43:42 +0000368 bool VisitExpr(Expr *E) {
369 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssoncad17b52008-07-08 05:13:58 +0000370 }
371
Chris Lattnera42f09a2008-07-11 19:10:17 +0000372 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000373
Chris Lattner15e59112008-07-12 00:38:25 +0000374 bool VisitIntegerLiteral(const IntegerLiteral *E) {
375 Result = E->getValue();
376 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
377 return true;
378 }
379 bool VisitCharacterLiteral(const CharacterLiteral *E) {
380 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
381 Result = E->getValue();
382 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
383 return true;
384 }
385 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
386 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarda8ebd22008-10-24 08:07:57 +0000387 // Per gcc docs "this built-in function ignores top level
388 // qualifiers". We need to use the canonical version to properly
389 // be able to strip CRV qualifiers from the type.
390 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
391 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
392 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
393 T1.getUnqualifiedType());
Chris Lattner15e59112008-07-12 00:38:25 +0000394 return true;
395 }
396 bool VisitDeclRefExpr(const DeclRefExpr *E);
397 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000398 bool VisitBinaryOperator(const BinaryOperator *E);
399 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000400 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000401
Chris Lattnerff579ff2008-07-12 01:15:53 +0000402 bool VisitCastExpr(CastExpr* E) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000403 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000404 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000405 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
406
Anders Carlsson027f2882008-11-16 19:01:22 +0000407 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
408 Result = E->getValue();
409 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
410 return true;
411 }
412
413 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
414 Result = APSInt::getNullValue(getIntTypeSizeInBits(E->getType()));
415 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
416 return true;
417 }
418
Chris Lattner265a0892008-07-11 21:24:13 +0000419private:
Chris Lattnerff579ff2008-07-12 01:15:53 +0000420 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000421};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000422} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000423
Chris Lattner422373c2008-07-11 22:52:41 +0000424static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
425 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000426}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000427
Chris Lattner15e59112008-07-12 00:38:25 +0000428bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
429 // Enums are integer constant exprs.
430 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
431 Result = D->getInitVal();
432 return true;
433 }
434
435 // Otherwise, random variable references are not constants.
Chris Lattner438f3b12008-11-12 07:43:42 +0000436 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner15e59112008-07-12 00:38:25 +0000437}
438
Chris Lattner1eee9402008-10-06 06:40:35 +0000439/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
440/// as GCC.
441static int EvaluateBuiltinClassifyType(const CallExpr *E) {
442 // The following enum mimics the values returned by GCC.
443 enum gcc_type_class {
444 no_type_class = -1,
445 void_type_class, integer_type_class, char_type_class,
446 enumeral_type_class, boolean_type_class,
447 pointer_type_class, reference_type_class, offset_type_class,
448 real_type_class, complex_type_class,
449 function_type_class, method_type_class,
450 record_type_class, union_type_class,
451 array_type_class, string_type_class,
452 lang_type_class
453 };
454
455 // If no argument was supplied, default to "no_type_class". This isn't
456 // ideal, however it is what gcc does.
457 if (E->getNumArgs() == 0)
458 return no_type_class;
459
460 QualType ArgTy = E->getArg(0)->getType();
461 if (ArgTy->isVoidType())
462 return void_type_class;
463 else if (ArgTy->isEnumeralType())
464 return enumeral_type_class;
465 else if (ArgTy->isBooleanType())
466 return boolean_type_class;
467 else if (ArgTy->isCharType())
468 return string_type_class; // gcc doesn't appear to use char_type_class
469 else if (ArgTy->isIntegerType())
470 return integer_type_class;
471 else if (ArgTy->isPointerType())
472 return pointer_type_class;
473 else if (ArgTy->isReferenceType())
474 return reference_type_class;
475 else if (ArgTy->isRealType())
476 return real_type_class;
477 else if (ArgTy->isComplexType())
478 return complex_type_class;
479 else if (ArgTy->isFunctionType())
480 return function_type_class;
481 else if (ArgTy->isStructureType())
482 return record_type_class;
483 else if (ArgTy->isUnionType())
484 return union_type_class;
485 else if (ArgTy->isArrayType())
486 return array_type_class;
487 else if (ArgTy->isUnionType())
488 return union_type_class;
489 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
490 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
491 return -1;
492}
493
Chris Lattner15e59112008-07-12 00:38:25 +0000494bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
495 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000496
Chris Lattner87293782008-10-06 05:28:25 +0000497 switch (E->isBuiltinCall()) {
498 default:
Chris Lattner438f3b12008-11-12 07:43:42 +0000499 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner87293782008-10-06 05:28:25 +0000500 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000501 Result.setIsSigned(true);
502 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000503 return true;
504
505 case Builtin::BI__builtin_constant_p: {
506 // __builtin_constant_p always has one operand: it returns true if that
507 // operand can be folded, false otherwise.
508 APValue Res;
509 Result = E->getArg(0)->tryEvaluate(Res, Info.Ctx);
510 return true;
511 }
512 }
Chris Lattner15e59112008-07-12 00:38:25 +0000513}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000514
Chris Lattnera42f09a2008-07-11 19:10:17 +0000515bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000516 if (E->getOpcode() == BinaryOperator::Comma) {
517 // Evaluate the side that actually matters; this needs to be
518 // handled specially because calling Visit() on the LHS can
519 // have strange results when it doesn't have an integral type.
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000520 if (Visit(E->getRHS()))
521 return true;
Eli Friedman14cc7542008-11-13 06:09:17 +0000522
523 // Check for isEvaluated; the idea is that this might eventually
524 // be useful for isICE and other similar uses that care about
525 // whether a comma is evaluated. This isn't really used yet, though,
526 // and I'm not sure it really works as intended.
527 if (!Info.isEvaluated)
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000528 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
Eli Friedman14cc7542008-11-13 06:09:17 +0000529
Nuno Lopesd88cb9c2008-11-16 20:09:07 +0000530 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000531 }
532
533 if (E->isLogicalOp()) {
534 // These need to be handled specially because the operands aren't
535 // necessarily integral
536 bool bres;
537 if (!HandleConversionToBool(E->getLHS(), bres, Info)) {
538 // We can't evaluate the LHS; however, sometimes the result
539 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
540 if (HandleConversionToBool(E->getRHS(), bres, Info) &&
541 bres == (E->getOpcode() == BinaryOperator::LOr)) {
542 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
543 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
544 Result = bres;
545 return true;
546 }
547
548 // Really can't evaluate
549 return false;
550 }
551
552 bool bres2;
553 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
554 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
555 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
556 if (E->getOpcode() == BinaryOperator::LOr)
557 Result = bres || bres2;
558 else
559 Result = bres && bres2;
560 return true;
561 }
562 return false;
563 }
564
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000565 QualType LHSTy = E->getLHS()->getType();
566 QualType RHSTy = E->getRHS()->getType();
567
568 if (LHSTy->isRealFloatingType() &&
569 RHSTy->isRealFloatingType()) {
570 APFloat RHS(0.0), LHS(0.0);
571
572 if (!EvaluateFloat(E->getRHS(), RHS, Info))
573 return false;
574
575 if (!EvaluateFloat(E->getLHS(), LHS, Info))
576 return false;
577
578 APFloat::cmpResult CR = LHS.compare(RHS);
579
580 switch (E->getOpcode()) {
581 default:
582 assert(0 && "Invalid binary operator!");
583 case BinaryOperator::LT:
584 Result = CR == APFloat::cmpLessThan;
585 break;
586 case BinaryOperator::GT:
587 Result = CR == APFloat::cmpGreaterThan;
588 break;
589 case BinaryOperator::LE:
590 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
591 break;
592 case BinaryOperator::GE:
593 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
594 break;
595 case BinaryOperator::EQ:
596 Result = CR == APFloat::cmpEqual;
597 break;
598 case BinaryOperator::NE:
599 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
600 break;
601 }
602
603 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
604 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
605 return true;
606 }
607
Anders Carlsson027f2882008-11-16 19:01:22 +0000608 if (E->getOpcode() == BinaryOperator::Sub) {
609 if (LHSTy->isPointerType()) {
610 if (RHSTy->isIntegralType()) {
611 // pointer - int.
612 // FIXME: Implement.
613 }
614
615 assert(RHSTy->isPointerType() && "RHS not pointer!");
616
617 APValue LHSValue;
618 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
619 return false;
620
621 APValue RHSValue;
622 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
623 return false;
624
625 // FIXME: Is this correct? What if only one of the operands has a base?
626 if (LHSValue.getLValueBase() || RHSValue.getLValueBase())
627 return false;
628
629 const QualType Type = E->getLHS()->getType();
630 const QualType ElementType = Type->getAsPointerType()->getPointeeType();
631
632 uint64_t D = LHSValue.getLValueOffset() - RHSValue.getLValueOffset();
633 D /= Info.Ctx.getTypeSize(ElementType) / 8;
634
635 Result = D;
636 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
637 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
638
639 return true;
640 }
641 }
Anders Carlssonebfa6ed2008-11-16 07:17:21 +0000642 if (!LHSTy->isIntegralType() ||
643 !RHSTy->isIntegralType()) {
Eli Friedman14cc7542008-11-13 06:09:17 +0000644 // We can't continue from here for non-integral types, and they
645 // could potentially confuse the following operations.
646 // FIXME: Deal with EQ and friends.
647 return false;
648 }
649
Anders Carlssond1aa5812008-07-08 14:35:21 +0000650 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000651 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000652 if (!Visit(E->getLHS())) {
Chris Lattner82437da2008-07-12 00:14:42 +0000653 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000654 }
Eli Friedman3e64dd72008-07-27 05:46:18 +0000655
Eli Friedman3e64dd72008-07-27 05:46:18 +0000656
657 // FIXME Maybe we want to succeed even where we can't evaluate the
658 // right side of LAnd/LOr?
659 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000660 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000661 return false;
Eli Friedman14cc7542008-11-13 06:09:17 +0000662
Anders Carlssond1aa5812008-07-08 14:35:21 +0000663 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000664 default:
665 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner82437da2008-07-12 00:14:42 +0000666 case BinaryOperator::Mul: Result *= RHS; return true;
667 case BinaryOperator::Add: Result += RHS; return true;
668 case BinaryOperator::Sub: Result -= RHS; return true;
669 case BinaryOperator::And: Result &= RHS; return true;
670 case BinaryOperator::Xor: Result ^= RHS; return true;
671 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000672 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000673 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000674 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
675 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000676 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000677 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000678 case BinaryOperator::Rem:
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;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000684 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000685 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000686 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000687 break;
688 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000689 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000690 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000691
Chris Lattner045502c2008-07-11 19:29:32 +0000692 case BinaryOperator::LT:
693 Result = Result < RHS;
694 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
695 break;
696 case BinaryOperator::GT:
697 Result = Result > RHS;
698 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
699 break;
700 case BinaryOperator::LE:
701 Result = Result <= RHS;
702 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
703 break;
704 case BinaryOperator::GE:
705 Result = Result >= RHS;
706 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
707 break;
708 case BinaryOperator::EQ:
709 Result = Result == RHS;
710 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
711 break;
712 case BinaryOperator::NE:
713 Result = Result != RHS;
714 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
715 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000716 case BinaryOperator::LAnd:
717 Result = Result != 0 && RHS != 0;
718 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
719 break;
720 case BinaryOperator::LOr:
721 Result = Result != 0 || RHS != 0;
722 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
723 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000724 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000725
726 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000727 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000728}
729
Nuno Lopeseb35c0e2008-11-16 19:28:31 +0000730bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
731 llvm::APSInt Cond(32);
732 if (!EvaluateInteger(E->getCond(), Cond, Info))
733 return false;
734
735 return Visit(Cond != 0 ? E->getTrueExpr() : E->getFalseExpr());
736}
737
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000738/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
739/// expression's type.
740bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
741 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000742 // Return the result in the right width.
743 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
744 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
745
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000746 QualType SrcTy = E->getTypeOfArgument();
747
Chris Lattner265a0892008-07-11 21:24:13 +0000748 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000749 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000750 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000751 return true;
752 }
Chris Lattner265a0892008-07-11 21:24:13 +0000753
754 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000755 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000756 if (!SrcTy->isConstantSizeType()) {
757 // FIXME: Should we attempt to evaluate this?
758 return false;
759 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000760
761 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000762
763 // GCC extension: sizeof(function) = 1.
764 if (SrcTy->isFunctionType()) {
765 // FIXME: AlignOf shouldn't be unconditionally 4!
766 Result = isSizeOf ? 1 : 4;
767 return true;
768 }
769
770 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000771 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000772 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000773 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000774 else
Chris Lattner422373c2008-07-11 22:52:41 +0000775 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000776 return true;
777}
778
Chris Lattnera42f09a2008-07-11 19:10:17 +0000779bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000780 // Special case unary operators that do not need their subexpression
781 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000782 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000783 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000784 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000785 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
786 return true;
787 }
Eli Friedman14cc7542008-11-13 06:09:17 +0000788
789 if (E->getOpcode() == UnaryOperator::LNot) {
790 // LNot's operand isn't necessarily an integer, so we handle it specially.
791 bool bres;
792 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
793 return false;
794 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
795 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
796 Result = !bres;
797 return true;
798 }
799
Chris Lattner422373c2008-07-11 22:52:41 +0000800 // Get the operand value into 'Result'.
801 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000802 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000803
Chris Lattner400d7402008-07-11 22:15:16 +0000804 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000805 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000806 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
807 // See C99 6.6p3.
Chris Lattner438f3b12008-11-12 07:43:42 +0000808 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
809 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000810 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000811 // FIXME: Should extension allow i-c-e extension expressions in its scope?
812 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000813 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000814 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000815 break;
816 case UnaryOperator::Minus:
817 Result = -Result;
818 break;
819 case UnaryOperator::Not:
820 Result = ~Result;
821 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000822 }
823
824 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000825 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000826}
827
Chris Lattnerff579ff2008-07-12 01:15:53 +0000828/// HandleCast - This is used to evaluate implicit or explicit casts where the
829/// result type is integer.
830bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
831 Expr *SubExpr, QualType DestType) {
Chris Lattner2c99c712008-07-11 19:24:49 +0000832 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000833
Eli Friedman7888b932008-11-12 09:44:48 +0000834 if (DestType->isBooleanType()) {
835 bool BoolResult;
836 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
837 return false;
838 Result.zextOrTrunc(DestWidth);
839 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
840 Result = BoolResult;
841 return true;
842 }
843
Anders Carlssond1aa5812008-07-08 14:35:21 +0000844 // Handle simple integer->integer casts.
Eli Friedman14cc7542008-11-13 06:09:17 +0000845 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000846 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000847 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000848
849 // Figure out if this is a truncate, extend or noop cast.
850 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000851 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000852 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
853 return true;
854 }
855
856 // FIXME: Clean this up!
857 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000858 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000859 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000860 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000861
Anders Carlssond1aa5812008-07-08 14:35:21 +0000862 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000863 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000864
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000865 Result.extOrTrunc(DestWidth);
866 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000867 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
868 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000869 }
Eli Friedman7888b932008-11-12 09:44:48 +0000870
Chris Lattnerff579ff2008-07-12 01:15:53 +0000871 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner438f3b12008-11-12 07:43:42 +0000872 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000873
Eli Friedman2f445492008-08-22 00:06:13 +0000874 APFloat F(0.0);
875 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner438f3b12008-11-12 07:43:42 +0000876 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000877
878 // Determine whether we are converting to unsigned or signed.
879 bool DestSigned = DestType->isSignedIntegerType();
880
881 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000882 uint64_t Space[4];
883 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000884 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000885 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000886 Result = llvm::APInt(DestWidth, 4, Space);
887 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000888 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000889}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000890
Chris Lattnera823ccf2008-07-11 18:11:29 +0000891//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000892// Float Evaluation
893//===----------------------------------------------------------------------===//
894
895namespace {
896class VISIBILITY_HIDDEN FloatExprEvaluator
897 : public StmtVisitor<FloatExprEvaluator, bool> {
898 EvalInfo &Info;
899 APFloat &Result;
900public:
901 FloatExprEvaluator(EvalInfo &info, APFloat &result)
902 : Info(info), Result(result) {}
903
904 bool VisitStmt(Stmt *S) {
905 return false;
906 }
907
908 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000909 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000910
Daniel Dunbar804ead02008-10-16 03:51:50 +0000911 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000912 bool VisitBinaryOperator(const BinaryOperator *E);
913 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000914 bool VisitCastExpr(CastExpr *E);
915 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000916};
917} // end anonymous namespace
918
919static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
920 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
921}
922
Chris Lattner87293782008-10-06 05:28:25 +0000923bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000924 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000925 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000926 case Builtin::BI__builtin_huge_val:
927 case Builtin::BI__builtin_huge_valf:
928 case Builtin::BI__builtin_huge_vall:
929 case Builtin::BI__builtin_inf:
930 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000931 case Builtin::BI__builtin_infl: {
932 const llvm::fltSemantics &Sem =
933 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000934 Result = llvm::APFloat::getInf(Sem);
935 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000936 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000937
938 case Builtin::BI__builtin_nan:
939 case Builtin::BI__builtin_nanf:
940 case Builtin::BI__builtin_nanl:
941 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
942 // can't constant fold it.
943 if (const StringLiteral *S =
944 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
945 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000946 const llvm::fltSemantics &Sem =
947 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000948 Result = llvm::APFloat::getNaN(Sem);
949 return true;
950 }
951 }
952 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000953
954 case Builtin::BI__builtin_fabs:
955 case Builtin::BI__builtin_fabsf:
956 case Builtin::BI__builtin_fabsl:
957 if (!EvaluateFloat(E->getArg(0), Result, Info))
958 return false;
959
960 if (Result.isNegative())
961 Result.changeSign();
962 return true;
963
964 case Builtin::BI__builtin_copysign:
965 case Builtin::BI__builtin_copysignf:
966 case Builtin::BI__builtin_copysignl: {
967 APFloat RHS(0.);
968 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
969 !EvaluateFloat(E->getArg(1), RHS, Info))
970 return false;
971 Result.copySign(RHS);
972 return true;
973 }
Chris Lattner87293782008-10-06 05:28:25 +0000974 }
975}
976
Daniel Dunbar804ead02008-10-16 03:51:50 +0000977bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
978 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
979 return false;
980
981 switch (E->getOpcode()) {
982 default: return false;
983 case UnaryOperator::Plus:
984 return true;
985 case UnaryOperator::Minus:
986 Result.changeSign();
987 return true;
988 }
989}
Chris Lattner87293782008-10-06 05:28:25 +0000990
Eli Friedman2f445492008-08-22 00:06:13 +0000991bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
992 // FIXME: Diagnostics? I really don't understand how the warnings
993 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +0000994 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +0000995 if (!EvaluateFloat(E->getLHS(), Result, Info))
996 return false;
997 if (!EvaluateFloat(E->getRHS(), RHS, Info))
998 return false;
999
1000 switch (E->getOpcode()) {
1001 default: return false;
1002 case BinaryOperator::Mul:
1003 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1004 return true;
1005 case BinaryOperator::Add:
1006 Result.add(RHS, APFloat::rmNearestTiesToEven);
1007 return true;
1008 case BinaryOperator::Sub:
1009 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1010 return true;
1011 case BinaryOperator::Div:
1012 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1013 return true;
1014 case BinaryOperator::Rem:
1015 Result.mod(RHS, APFloat::rmNearestTiesToEven);
1016 return true;
1017 }
1018}
1019
1020bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1021 Result = E->getValue();
1022 return true;
1023}
1024
Eli Friedman7888b932008-11-12 09:44:48 +00001025bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1026 Expr* SubExpr = E->getSubExpr();
1027 const llvm::fltSemantics& destSemantics =
1028 Info.Ctx.getFloatTypeSemantics(E->getType());
1029 if (SubExpr->getType()->isIntegralType()) {
1030 APSInt IntResult;
1031 if (!EvaluateInteger(E, IntResult, Info))
1032 return false;
1033 Result = APFloat(destSemantics, 1);
1034 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
1035 APFloat::rmNearestTiesToEven);
1036 return true;
1037 }
1038 if (SubExpr->getType()->isRealFloatingType()) {
1039 if (!Visit(SubExpr))
1040 return false;
1041 bool ignored;
1042 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
1043 return true;
1044 }
1045
1046 return false;
1047}
1048
1049bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1050 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1051 return true;
1052}
1053
Eli Friedman2f445492008-08-22 00:06:13 +00001054//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +00001055// Top level TryEvaluate.
1056//===----------------------------------------------------------------------===//
1057
Chris Lattner87293782008-10-06 05:28:25 +00001058/// tryEvaluate - Return true if this is a constant which we can fold using
1059/// any crazy technique (that has nothing to do with language standards) that
1060/// we want to. If this function returns true, it returns the folded constant
1061/// in Result.
Chris Lattnera42f09a2008-07-11 19:10:17 +00001062bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner422373c2008-07-11 22:52:41 +00001063 EvalInfo Info(Ctx);
Anders Carlssonc0328012008-07-08 05:49:43 +00001064 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +00001065 llvm::APSInt sInt(32);
Chris Lattner422373c2008-07-11 22:52:41 +00001066 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlssonc0328012008-07-08 05:49:43 +00001067 Result = APValue(sInt);
1068 return true;
1069 }
Eli Friedman2f445492008-08-22 00:06:13 +00001070 } else if (getType()->isPointerType()) {
1071 if (EvaluatePointer(this, Result, Info)) {
1072 return true;
1073 }
1074 } else if (getType()->isRealFloatingType()) {
1075 llvm::APFloat f(0.0);
1076 if (EvaluateFloat(this, f, Info)) {
1077 Result = APValue(f);
1078 return true;
1079 }
1080 }
Anders Carlsson47968a92008-08-10 17:03:01 +00001081
Anders Carlssonc7436af2008-07-03 04:20:39 +00001082 return false;
1083}
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001084
1085/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
1086/// folded, but discard the result.
1087bool Expr::isEvaluatable(ASTContext &Ctx) const {
1088 APValue V;
1089 return tryEvaluate(V, Ctx);
1090}