blob: 08236836a701f243b2ab338ac47f281bc90d8e73 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Eli Friedman4efaa272008-11-12 09:44:48 +000016#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000017#include "clang/AST/StmtVisitor.h"
Chris Lattner54176fd2008-07-12 00:14:42 +000018#include "clang/Basic/Diagnostic.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000019#include "clang/Basic/TargetInfo.h"
Anders Carlssonc754aa62008-07-08 05:13:58 +000020#include "llvm/Support/Compiler.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000021using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000022using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000023using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000024
Chris Lattner87eae5e2008-07-11 22:52:41 +000025/// EvalInfo - This is a private struct used by the evaluator to capture
26/// information about a subexpression as it is folded. It retains information
27/// about the AST context, but also maintains information about the folded
28/// expression.
29///
30/// If an expression could be evaluated, it is still possible it is not a C
31/// "integer constant expression" or constant expression. If not, this struct
32/// captures information about how and why not.
33///
34/// One bit of information passed *into* the request for constant folding
35/// indicates whether the subexpression is "evaluated" or not according to C
36/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
37/// evaluate the expression regardless of what the RHS is, but C only allows
38/// certain things in certain situations.
39struct EvalInfo {
40 ASTContext &Ctx;
41
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 Lattner54176fd2008-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 Lattner87eae5e2008-07-11 22:52:41 +000053 ///
Chris Lattner54176fd2008-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 Lattner87eae5e2008-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 Friedman4efaa272008-11-12 09:44:48 +000066static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-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 Friedmand8bfe7f2008-08-22 00:06:13 +000069static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000070
71//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-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 Dunbar8a7b7c62008-11-12 21:52:46 +0000113#if 0
Eli Friedman4efaa272008-11-12 09:44:48 +0000114 // FIXME: Remove this when we support more expressions.
115 printf("Unhandled pointer statement\n");
116 S->dump();
Daniel Dunbar8a7b7c62008-11-12 21:52:46 +0000117#endif
Eli Friedman4efaa272008-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); }
127};
128} // end anonymous namespace
129
130static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
131 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
132 return Result.isLValue();
133}
134
135APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
136 if (E->isFileScope())
137 return APValue(E, 0);
138 return APValue();
139}
140
141APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
142 APValue result;
143 QualType Ty;
144 if (E->isArrow()) {
145 if (!EvaluatePointer(E->getBase(), result, Info))
146 return APValue();
147 Ty = E->getBase()->getType()->getAsPointerType()->getPointeeType();
148 } else {
149 result = Visit(E->getBase());
150 if (result.isUninit())
151 return APValue();
152 Ty = E->getBase()->getType();
153 }
154
155 RecordDecl *RD = Ty->getAsRecordType()->getDecl();
156 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
157 FieldDecl *FD = E->getMemberDecl();
158
159 // FIXME: This is linear time.
160 unsigned i = 0, e = 0;
161 for (i = 0, e = RD->getNumMembers(); i != e; i++) {
162 if (RD->getMember(i) == FD)
163 break;
164 }
165
166 result.setLValue(result.getLValueBase(),
167 result.getLValueOffset() + RL.getFieldOffset(i) / 8);
168
169 return result;
170}
171
172
173//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000174// Pointer Evaluation
175//===----------------------------------------------------------------------===//
176
Anders Carlssonc754aa62008-07-08 05:13:58 +0000177namespace {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000178class VISIBILITY_HIDDEN PointerExprEvaluator
179 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000180 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000181public:
Anders Carlsson2bad1682008-07-08 14:30:00 +0000182
Chris Lattner87eae5e2008-07-11 22:52:41 +0000183 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000184
Anders Carlsson2bad1682008-07-08 14:30:00 +0000185 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000186 return APValue();
187 }
188
189 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
190
Anders Carlsson650c92f2008-07-08 15:34:11 +0000191 APValue VisitBinaryOperator(const BinaryOperator *E);
192 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000193 APValue VisitUnaryOperator(const UnaryOperator *E);
194 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
195 { return APValue(E, 0); }
196 APValue VisitConditionalOperator(ConditionalOperator *E);
Anders Carlsson650c92f2008-07-08 15:34:11 +0000197};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000198} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000199
Chris Lattner87eae5e2008-07-11 22:52:41 +0000200static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000201 if (!E->getType()->isPointerType())
202 return false;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000203 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000204 return Result.isLValue();
205}
206
207APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
208 if (E->getOpcode() != BinaryOperator::Add &&
209 E->getOpcode() != BinaryOperator::Sub)
210 return APValue();
211
212 const Expr *PExp = E->getLHS();
213 const Expr *IExp = E->getRHS();
214 if (IExp->getType()->isPointerType())
215 std::swap(PExp, IExp);
216
217 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000218 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000219 return APValue();
220
221 llvm::APSInt AdditionalOffset(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000222 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000223 return APValue();
224
Eli Friedman4efaa272008-11-12 09:44:48 +0000225 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
226 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
227
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000228 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman4efaa272008-11-12 09:44:48 +0000229
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000230 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman4efaa272008-11-12 09:44:48 +0000231 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000232 else
Eli Friedman4efaa272008-11-12 09:44:48 +0000233 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
234
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000235 return APValue(ResultLValue.getLValueBase(), Offset);
236}
Eli Friedman4efaa272008-11-12 09:44:48 +0000237
238APValue PointerExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
239 if (E->getOpcode() == UnaryOperator::Extension) {
240 // FIXME: Deal with warnings?
241 return Visit(E->getSubExpr());
242 }
243
244 if (E->getOpcode() == UnaryOperator::AddrOf) {
245 APValue result;
246 if (EvaluateLValue(E->getSubExpr(), result, Info))
247 return result;
248 }
249
250 return APValue();
251}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000252
253
Chris Lattnerb542afe2008-07-11 19:10:17 +0000254APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000255 const Expr* SubExpr = E->getSubExpr();
256
257 // Check for pointer->pointer cast
258 if (SubExpr->getType()->isPointerType()) {
259 APValue Result;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000260 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000261 return Result;
262 return APValue();
263 }
264
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000265 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000266 llvm::APSInt Result(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000267 if (EvaluateInteger(SubExpr, Result, Info)) {
268 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000269 return APValue(0, Result.getZExtValue());
270 }
271 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000272
273 if (SubExpr->getType()->isFunctionType() ||
274 SubExpr->getType()->isArrayType()) {
275 APValue Result;
276 if (EvaluateLValue(SubExpr, Result, Info))
277 return Result;
278 return APValue();
279 }
280
281 //assert(0 && "Unhandled cast");
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000282 return APValue();
283}
284
Eli Friedman4efaa272008-11-12 09:44:48 +0000285APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
286 bool BoolResult;
287 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
288 return APValue();
289
290 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
291
292 APValue Result;
293 if (EvaluatePointer(EvalExpr, Result, Info))
294 return Result;
295 return APValue();
296}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000297
298//===----------------------------------------------------------------------===//
299// Integer Evaluation
300//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000301
302namespace {
Anders Carlssonc754aa62008-07-08 05:13:58 +0000303class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000304 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000305 EvalInfo &Info;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000306 APSInt &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000307public:
Chris Lattner87eae5e2008-07-11 22:52:41 +0000308 IntExprEvaluator(EvalInfo &info, APSInt &result)
309 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000310
Chris Lattner7a767782008-07-11 19:24:49 +0000311 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner54176fd2008-07-12 00:14:42 +0000312 return (unsigned)Info.Ctx.getIntWidth(T);
313 }
314
315 bool Extension(SourceLocation L, diag::kind D) {
316 Info.DiagLoc = L;
317 Info.ICEDiag = D;
318 return true; // still a constant.
319 }
320
Chris Lattner32fea9d2008-11-12 07:43:42 +0000321 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000322 // If this is in an unevaluated portion of the subexpression, ignore the
323 // error.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000324 if (!Info.isEvaluated) {
325 // If error is ignored because the value isn't evaluated, get the real
326 // type at least to prevent errors downstream.
327 Result.zextOrTrunc(getIntTypeSizeInBits(ExprTy));
328 Result.setIsUnsigned(ExprTy->isUnsignedIntegerType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000329 return true;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000330 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000331
Chris Lattner32fea9d2008-11-12 07:43:42 +0000332 // Take the first error.
333 if (Info.ICEDiag == 0) {
334 Info.DiagLoc = L;
335 Info.ICEDiag = D;
336 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000337 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000338 }
339
Anders Carlssonc754aa62008-07-08 05:13:58 +0000340 //===--------------------------------------------------------------------===//
341 // Visitor Methods
342 //===--------------------------------------------------------------------===//
Chris Lattner32fea9d2008-11-12 07:43:42 +0000343
344 bool VisitStmt(Stmt *) {
345 assert(0 && "This should be called on integers, stmts are not integers");
346 return false;
347 }
Chris Lattner7a767782008-07-11 19:24:49 +0000348
Chris Lattner32fea9d2008-11-12 07:43:42 +0000349 bool VisitExpr(Expr *E) {
350 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssonc754aa62008-07-08 05:13:58 +0000351 }
352
Chris Lattnerb542afe2008-07-11 19:10:17 +0000353 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000354
Chris Lattner4c4867e2008-07-12 00:38:25 +0000355 bool VisitIntegerLiteral(const IntegerLiteral *E) {
356 Result = E->getValue();
357 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
358 return true;
359 }
360 bool VisitCharacterLiteral(const CharacterLiteral *E) {
361 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
362 Result = E->getValue();
363 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
364 return true;
365 }
366 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
367 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Daniel Dunbarac620de2008-10-24 08:07:57 +0000368 // Per gcc docs "this built-in function ignores top level
369 // qualifiers". We need to use the canonical version to properly
370 // be able to strip CRV qualifiers from the type.
371 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
372 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
373 Result = Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
374 T1.getUnqualifiedType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000375 return true;
376 }
377 bool VisitDeclRefExpr(const DeclRefExpr *E);
378 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000379 bool VisitBinaryOperator(const BinaryOperator *E);
380 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000381
Chris Lattner732b2232008-07-12 01:15:53 +0000382 bool VisitCastExpr(CastExpr* E) {
Chris Lattner732b2232008-07-12 01:15:53 +0000383 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlsson650c92f2008-07-08 15:34:11 +0000384 }
Sebastian Redl05189992008-11-11 17:56:53 +0000385 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
386
Chris Lattnerfcee0012008-07-11 21:24:13 +0000387private:
Chris Lattner732b2232008-07-12 01:15:53 +0000388 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000389};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000390} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000391
Chris Lattner87eae5e2008-07-11 22:52:41 +0000392static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
393 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson650c92f2008-07-08 15:34:11 +0000394}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000395
Chris Lattner4c4867e2008-07-12 00:38:25 +0000396bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
397 // Enums are integer constant exprs.
398 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
399 Result = D->getInitVal();
400 return true;
401 }
402
403 // Otherwise, random variable references are not constants.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000404 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner4c4867e2008-07-12 00:38:25 +0000405}
406
Chris Lattnera4d55d82008-10-06 06:40:35 +0000407/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
408/// as GCC.
409static int EvaluateBuiltinClassifyType(const CallExpr *E) {
410 // The following enum mimics the values returned by GCC.
411 enum gcc_type_class {
412 no_type_class = -1,
413 void_type_class, integer_type_class, char_type_class,
414 enumeral_type_class, boolean_type_class,
415 pointer_type_class, reference_type_class, offset_type_class,
416 real_type_class, complex_type_class,
417 function_type_class, method_type_class,
418 record_type_class, union_type_class,
419 array_type_class, string_type_class,
420 lang_type_class
421 };
422
423 // If no argument was supplied, default to "no_type_class". This isn't
424 // ideal, however it is what gcc does.
425 if (E->getNumArgs() == 0)
426 return no_type_class;
427
428 QualType ArgTy = E->getArg(0)->getType();
429 if (ArgTy->isVoidType())
430 return void_type_class;
431 else if (ArgTy->isEnumeralType())
432 return enumeral_type_class;
433 else if (ArgTy->isBooleanType())
434 return boolean_type_class;
435 else if (ArgTy->isCharType())
436 return string_type_class; // gcc doesn't appear to use char_type_class
437 else if (ArgTy->isIntegerType())
438 return integer_type_class;
439 else if (ArgTy->isPointerType())
440 return pointer_type_class;
441 else if (ArgTy->isReferenceType())
442 return reference_type_class;
443 else if (ArgTy->isRealType())
444 return real_type_class;
445 else if (ArgTy->isComplexType())
446 return complex_type_class;
447 else if (ArgTy->isFunctionType())
448 return function_type_class;
449 else if (ArgTy->isStructureType())
450 return record_type_class;
451 else if (ArgTy->isUnionType())
452 return union_type_class;
453 else if (ArgTy->isArrayType())
454 return array_type_class;
455 else if (ArgTy->isUnionType())
456 return union_type_class;
457 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
458 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
459 return -1;
460}
461
Chris Lattner4c4867e2008-07-12 00:38:25 +0000462bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
463 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner4c4867e2008-07-12 00:38:25 +0000464
Chris Lattner019f4e82008-10-06 05:28:25 +0000465 switch (E->isBuiltinCall()) {
466 default:
Chris Lattner32fea9d2008-11-12 07:43:42 +0000467 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner019f4e82008-10-06 05:28:25 +0000468 case Builtin::BI__builtin_classify_type:
Chris Lattnera4d55d82008-10-06 06:40:35 +0000469 Result.setIsSigned(true);
470 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner019f4e82008-10-06 05:28:25 +0000471 return true;
472
473 case Builtin::BI__builtin_constant_p: {
474 // __builtin_constant_p always has one operand: it returns true if that
475 // operand can be folded, false otherwise.
476 APValue Res;
477 Result = E->getArg(0)->tryEvaluate(Res, Info.Ctx);
478 return true;
479 }
480 }
Chris Lattner4c4867e2008-07-12 00:38:25 +0000481}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000482
Chris Lattnerb542afe2008-07-11 19:10:17 +0000483bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000484 if (E->getOpcode() == BinaryOperator::Comma) {
485 // Evaluate the side that actually matters; this needs to be
486 // handled specially because calling Visit() on the LHS can
487 // have strange results when it doesn't have an integral type.
488 Visit(E->getRHS());
489
490 // Check for isEvaluated; the idea is that this might eventually
491 // be useful for isICE and other similar uses that care about
492 // whether a comma is evaluated. This isn't really used yet, though,
493 // and I'm not sure it really works as intended.
494 if (!Info.isEvaluated)
495 return true;
496
497 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
498 }
499
500 if (E->isLogicalOp()) {
501 // These need to be handled specially because the operands aren't
502 // necessarily integral
503 bool bres;
504 if (!HandleConversionToBool(E->getLHS(), bres, Info)) {
505 // We can't evaluate the LHS; however, sometimes the result
506 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
507 if (HandleConversionToBool(E->getRHS(), bres, Info) &&
508 bres == (E->getOpcode() == BinaryOperator::LOr)) {
509 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
510 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
511 Result = bres;
512 return true;
513 }
514
515 // Really can't evaluate
516 return false;
517 }
518
519 bool bres2;
520 if (HandleConversionToBool(E->getRHS(), bres2, Info)) {
521 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
522 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
523 if (E->getOpcode() == BinaryOperator::LOr)
524 Result = bres || bres2;
525 else
526 Result = bres && bres2;
527 return true;
528 }
529 return false;
530 }
531
Anders Carlsson286f85e2008-11-16 07:17:21 +0000532 QualType LHSTy = E->getLHS()->getType();
533 QualType RHSTy = E->getRHS()->getType();
534
535 if (LHSTy->isRealFloatingType() &&
536 RHSTy->isRealFloatingType()) {
537 APFloat RHS(0.0), LHS(0.0);
538
539 if (!EvaluateFloat(E->getRHS(), RHS, Info))
540 return false;
541
542 if (!EvaluateFloat(E->getLHS(), LHS, Info))
543 return false;
544
545 APFloat::cmpResult CR = LHS.compare(RHS);
546
547 switch (E->getOpcode()) {
548 default:
549 assert(0 && "Invalid binary operator!");
550 case BinaryOperator::LT:
551 Result = CR == APFloat::cmpLessThan;
552 break;
553 case BinaryOperator::GT:
554 Result = CR == APFloat::cmpGreaterThan;
555 break;
556 case BinaryOperator::LE:
557 Result = CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual;
558 break;
559 case BinaryOperator::GE:
560 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual;
561 break;
562 case BinaryOperator::EQ:
563 Result = CR == APFloat::cmpEqual;
564 break;
565 case BinaryOperator::NE:
566 Result = CR == APFloat::cmpGreaterThan || CR == APFloat::cmpLessThan;
567 break;
568 }
569
570 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
571 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
572 return true;
573 }
574
575 if (!LHSTy->isIntegralType() ||
576 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +0000577 // We can't continue from here for non-integral types, and they
578 // could potentially confuse the following operations.
579 // FIXME: Deal with EQ and friends.
580 return false;
581 }
582
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000583 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000584 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000585 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000586 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000587 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000588
589 // FIXME: Handle pointer subtraction
590
591 // FIXME Maybe we want to succeed even where we can't evaluate the
592 // right side of LAnd/LOr?
593 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000594 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000595 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000596
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000597 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000598 default:
599 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000600 case BinaryOperator::Mul: Result *= RHS; return true;
601 case BinaryOperator::Add: Result += RHS; return true;
602 case BinaryOperator::Sub: Result -= RHS; return true;
603 case BinaryOperator::And: Result &= RHS; return true;
604 case BinaryOperator::Xor: Result ^= RHS; return true;
605 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000606 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000607 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000608 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
609 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000610 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000611 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000612 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000613 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000614 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
615 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000616 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000617 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000618 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000619 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000620 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000621 break;
622 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000623 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000624 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000625
Chris Lattnerac7cb602008-07-11 19:29:32 +0000626 case BinaryOperator::LT:
627 Result = Result < RHS;
628 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
629 break;
630 case BinaryOperator::GT:
631 Result = Result > RHS;
632 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
633 break;
634 case BinaryOperator::LE:
635 Result = Result <= RHS;
636 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
637 break;
638 case BinaryOperator::GE:
639 Result = Result >= RHS;
640 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
641 break;
642 case BinaryOperator::EQ:
643 Result = Result == RHS;
644 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
645 break;
646 case BinaryOperator::NE:
647 Result = Result != RHS;
648 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
649 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000650 case BinaryOperator::LAnd:
651 Result = Result != 0 && RHS != 0;
652 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
653 break;
654 case BinaryOperator::LOr:
655 Result = Result != 0 || RHS != 0;
656 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
657 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000658 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000659
660 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000661 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000662}
663
Sebastian Redl05189992008-11-11 17:56:53 +0000664/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
665/// expression's type.
666bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
667 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000668 // Return the result in the right width.
669 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
670 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
671
Sebastian Redl05189992008-11-11 17:56:53 +0000672 QualType SrcTy = E->getTypeOfArgument();
673
Chris Lattnerfcee0012008-07-11 21:24:13 +0000674 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +0000675 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +0000676 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +0000677 return true;
678 }
Chris Lattnerfcee0012008-07-11 21:24:13 +0000679
680 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman4efaa272008-11-12 09:44:48 +0000681 // FIXME: But alignof(vla) is!
Chris Lattnerfcee0012008-07-11 21:24:13 +0000682 if (!SrcTy->isConstantSizeType()) {
683 // FIXME: Should we attempt to evaluate this?
684 return false;
685 }
Sebastian Redl05189992008-11-11 17:56:53 +0000686
687 bool isSizeOf = E->isSizeOf();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000688
689 // GCC extension: sizeof(function) = 1.
690 if (SrcTy->isFunctionType()) {
691 // FIXME: AlignOf shouldn't be unconditionally 4!
692 Result = isSizeOf ? 1 : 4;
693 return true;
694 }
695
696 // Get information about the size or align.
Chris Lattner87eae5e2008-07-11 22:52:41 +0000697 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000698 if (isSizeOf)
Eli Friedman4efaa272008-11-12 09:44:48 +0000699 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000700 else
Chris Lattner87eae5e2008-07-11 22:52:41 +0000701 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000702 return true;
703}
704
Chris Lattnerb542afe2008-07-11 19:10:17 +0000705bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000706 // Special case unary operators that do not need their subexpression
707 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +0000708 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000709 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +0000710 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +0000711 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
712 return true;
713 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000714
715 if (E->getOpcode() == UnaryOperator::LNot) {
716 // LNot's operand isn't necessarily an integer, so we handle it specially.
717 bool bres;
718 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
719 return false;
720 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
721 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
722 Result = !bres;
723 return true;
724 }
725
Chris Lattner87eae5e2008-07-11 22:52:41 +0000726 // Get the operand value into 'Result'.
727 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +0000728 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000729
Chris Lattner75a48812008-07-11 22:15:16 +0000730 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000731 default:
Chris Lattner75a48812008-07-11 22:15:16 +0000732 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
733 // See C99 6.6p3.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000734 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
735 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000736 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000737 // FIXME: Should extension allow i-c-e extension expressions in its scope?
738 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +0000739 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000740 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +0000741 break;
742 case UnaryOperator::Minus:
743 Result = -Result;
744 break;
745 case UnaryOperator::Not:
746 Result = ~Result;
747 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000748 }
749
750 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000751 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000752}
753
Chris Lattner732b2232008-07-12 01:15:53 +0000754/// HandleCast - This is used to evaluate implicit or explicit casts where the
755/// result type is integer.
756bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
757 Expr *SubExpr, QualType DestType) {
Chris Lattner7a767782008-07-11 19:24:49 +0000758 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000759
Eli Friedman4efaa272008-11-12 09:44:48 +0000760 if (DestType->isBooleanType()) {
761 bool BoolResult;
762 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
763 return false;
764 Result.zextOrTrunc(DestWidth);
765 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
766 Result = BoolResult;
767 return true;
768 }
769
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000770 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +0000771 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +0000772 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000773 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000774
775 // Figure out if this is a truncate, extend or noop cast.
776 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman4efaa272008-11-12 09:44:48 +0000777 Result.extOrTrunc(DestWidth);
Chris Lattner732b2232008-07-12 01:15:53 +0000778 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
779 return true;
780 }
781
782 // FIXME: Clean this up!
783 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000784 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000785 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000786 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000787
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000788 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +0000789 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000790
Anders Carlsson559e56b2008-07-08 16:49:00 +0000791 Result.extOrTrunc(DestWidth);
792 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +0000793 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
794 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000795 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000796
Chris Lattner732b2232008-07-12 01:15:53 +0000797 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner32fea9d2008-11-12 07:43:42 +0000798 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000799
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000800 APFloat F(0.0);
801 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner32fea9d2008-11-12 07:43:42 +0000802 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000803
804 // Determine whether we are converting to unsigned or signed.
805 bool DestSigned = DestType->isSignedIntegerType();
806
807 // FIXME: Warning for overflow.
Dale Johannesenee5a7002008-10-09 23:02:32 +0000808 uint64_t Space[4];
809 bool ignored;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000810 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesenee5a7002008-10-09 23:02:32 +0000811 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattner732b2232008-07-12 01:15:53 +0000812 Result = llvm::APInt(DestWidth, 4, Space);
813 Result.setIsUnsigned(!DestSigned);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000814 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000815}
Anders Carlsson2bad1682008-07-08 14:30:00 +0000816
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000817//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000818// Float Evaluation
819//===----------------------------------------------------------------------===//
820
821namespace {
822class VISIBILITY_HIDDEN FloatExprEvaluator
823 : public StmtVisitor<FloatExprEvaluator, bool> {
824 EvalInfo &Info;
825 APFloat &Result;
826public:
827 FloatExprEvaluator(EvalInfo &info, APFloat &result)
828 : Info(info), Result(result) {}
829
830 bool VisitStmt(Stmt *S) {
831 return false;
832 }
833
834 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +0000835 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000836
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000837 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000838 bool VisitBinaryOperator(const BinaryOperator *E);
839 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000840 bool VisitCastExpr(CastExpr *E);
841 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000842};
843} // end anonymous namespace
844
845static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
846 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
847}
848
Chris Lattner019f4e82008-10-06 05:28:25 +0000849bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000850 switch (E->isBuiltinCall()) {
Chris Lattner34a74ab2008-10-06 05:53:16 +0000851 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +0000852 case Builtin::BI__builtin_huge_val:
853 case Builtin::BI__builtin_huge_valf:
854 case Builtin::BI__builtin_huge_vall:
855 case Builtin::BI__builtin_inf:
856 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000857 case Builtin::BI__builtin_infl: {
858 const llvm::fltSemantics &Sem =
859 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +0000860 Result = llvm::APFloat::getInf(Sem);
861 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000862 }
Chris Lattner9e621712008-10-06 06:31:58 +0000863
864 case Builtin::BI__builtin_nan:
865 case Builtin::BI__builtin_nanf:
866 case Builtin::BI__builtin_nanl:
867 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
868 // can't constant fold it.
869 if (const StringLiteral *S =
870 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
871 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000872 const llvm::fltSemantics &Sem =
873 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +0000874 Result = llvm::APFloat::getNaN(Sem);
875 return true;
876 }
877 }
878 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000879
880 case Builtin::BI__builtin_fabs:
881 case Builtin::BI__builtin_fabsf:
882 case Builtin::BI__builtin_fabsl:
883 if (!EvaluateFloat(E->getArg(0), Result, Info))
884 return false;
885
886 if (Result.isNegative())
887 Result.changeSign();
888 return true;
889
890 case Builtin::BI__builtin_copysign:
891 case Builtin::BI__builtin_copysignf:
892 case Builtin::BI__builtin_copysignl: {
893 APFloat RHS(0.);
894 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
895 !EvaluateFloat(E->getArg(1), RHS, Info))
896 return false;
897 Result.copySign(RHS);
898 return true;
899 }
Chris Lattner019f4e82008-10-06 05:28:25 +0000900 }
901}
902
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000903bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
904 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
905 return false;
906
907 switch (E->getOpcode()) {
908 default: return false;
909 case UnaryOperator::Plus:
910 return true;
911 case UnaryOperator::Minus:
912 Result.changeSign();
913 return true;
914 }
915}
Chris Lattner019f4e82008-10-06 05:28:25 +0000916
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000917bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
918 // FIXME: Diagnostics? I really don't understand how the warnings
919 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000920 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000921 if (!EvaluateFloat(E->getLHS(), Result, Info))
922 return false;
923 if (!EvaluateFloat(E->getRHS(), RHS, Info))
924 return false;
925
926 switch (E->getOpcode()) {
927 default: return false;
928 case BinaryOperator::Mul:
929 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
930 return true;
931 case BinaryOperator::Add:
932 Result.add(RHS, APFloat::rmNearestTiesToEven);
933 return true;
934 case BinaryOperator::Sub:
935 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
936 return true;
937 case BinaryOperator::Div:
938 Result.divide(RHS, APFloat::rmNearestTiesToEven);
939 return true;
940 case BinaryOperator::Rem:
941 Result.mod(RHS, APFloat::rmNearestTiesToEven);
942 return true;
943 }
944}
945
946bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
947 Result = E->getValue();
948 return true;
949}
950
Eli Friedman4efaa272008-11-12 09:44:48 +0000951bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
952 Expr* SubExpr = E->getSubExpr();
953 const llvm::fltSemantics& destSemantics =
954 Info.Ctx.getFloatTypeSemantics(E->getType());
955 if (SubExpr->getType()->isIntegralType()) {
956 APSInt IntResult;
957 if (!EvaluateInteger(E, IntResult, Info))
958 return false;
959 Result = APFloat(destSemantics, 1);
960 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
961 APFloat::rmNearestTiesToEven);
962 return true;
963 }
964 if (SubExpr->getType()->isRealFloatingType()) {
965 if (!Visit(SubExpr))
966 return false;
967 bool ignored;
968 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
969 return true;
970 }
971
972 return false;
973}
974
975bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
976 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
977 return true;
978}
979
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000980//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000981// Top level TryEvaluate.
982//===----------------------------------------------------------------------===//
983
Chris Lattner019f4e82008-10-06 05:28:25 +0000984/// tryEvaluate - Return true if this is a constant which we can fold using
985/// any crazy technique (that has nothing to do with language standards) that
986/// we want to. If this function returns true, it returns the folded constant
987/// in Result.
Chris Lattnerb542afe2008-07-11 19:10:17 +0000988bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000989 EvalInfo Info(Ctx);
Anders Carlsson06a36752008-07-08 05:49:43 +0000990 if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000991 llvm::APSInt sInt(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000992 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlsson06a36752008-07-08 05:49:43 +0000993 Result = APValue(sInt);
994 return true;
995 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000996 } else if (getType()->isPointerType()) {
997 if (EvaluatePointer(this, Result, Info)) {
998 return true;
999 }
1000 } else if (getType()->isRealFloatingType()) {
1001 llvm::APFloat f(0.0);
1002 if (EvaluateFloat(this, f, Info)) {
1003 Result = APValue(f);
1004 return true;
1005 }
1006 }
Anders Carlsson165a70f2008-08-10 17:03:01 +00001007
Anders Carlssonc44eec62008-07-03 04:20:39 +00001008 return false;
1009}
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001010
1011/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
1012/// folded, but discard the result.
1013bool Expr::isEvaluatable(ASTContext &Ctx) const {
1014 APValue V;
1015 return tryEvaluate(V, Ctx);
1016}