blob: 87ee4651748eebfffe1bb071412ad3339013c1cd [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
532 if (!E->getLHS()->getType()->isIntegralType() ||
533 !E->getRHS()->getType()->isIntegralType()) {
534 // We can't continue from here for non-integral types, and they
535 // could potentially confuse the following operations.
536 // FIXME: Deal with EQ and friends.
537 return false;
538 }
539
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000540 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000541 llvm::APSInt RHS(32);
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000542 if (!Visit(E->getLHS())) {
Chris Lattner54176fd2008-07-12 00:14:42 +0000543 return false; // error in subexpression.
Chris Lattnerc8cc9cc2008-11-12 07:04:29 +0000544 }
Eli Friedmand9f4bcd2008-07-27 05:46:18 +0000545
546 // FIXME: Handle pointer subtraction
547
548 // FIXME Maybe we want to succeed even where we can't evaluate the
549 // right side of LAnd/LOr?
550 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner54176fd2008-07-12 00:14:42 +0000551 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000552 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +0000553
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000554 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000555 default:
556 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner54176fd2008-07-12 00:14:42 +0000557 case BinaryOperator::Mul: Result *= RHS; return true;
558 case BinaryOperator::Add: Result += RHS; return true;
559 case BinaryOperator::Sub: Result -= RHS; return true;
560 case BinaryOperator::And: Result &= RHS; return true;
561 case BinaryOperator::Xor: Result ^= RHS; return true;
562 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner75a48812008-07-11 22:15:16 +0000563 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +0000564 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000565 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
566 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000567 Result /= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000568 break;
Chris Lattner75a48812008-07-11 22:15:16 +0000569 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +0000570 if (RHS == 0)
Chris Lattner32fea9d2008-11-12 07:43:42 +0000571 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
572 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000573 Result %= RHS;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000574 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000575 case BinaryOperator::Shl:
Chris Lattner54176fd2008-07-12 00:14:42 +0000576 // FIXME: Warn about out of range shift amounts!
Chris Lattnerb542afe2008-07-11 19:10:17 +0000577 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000578 break;
579 case BinaryOperator::Shr:
Chris Lattnerb542afe2008-07-11 19:10:17 +0000580 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000581 break;
Chris Lattnerb542afe2008-07-11 19:10:17 +0000582
Chris Lattnerac7cb602008-07-11 19:29:32 +0000583 case BinaryOperator::LT:
584 Result = Result < RHS;
585 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
586 break;
587 case BinaryOperator::GT:
588 Result = Result > RHS;
589 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
590 break;
591 case BinaryOperator::LE:
592 Result = Result <= RHS;
593 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
594 break;
595 case BinaryOperator::GE:
596 Result = Result >= RHS;
597 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
598 break;
599 case BinaryOperator::EQ:
600 Result = Result == RHS;
601 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
602 break;
603 case BinaryOperator::NE:
604 Result = Result != RHS;
605 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
606 break;
Chris Lattner54176fd2008-07-12 00:14:42 +0000607 case BinaryOperator::LAnd:
608 Result = Result != 0 && RHS != 0;
609 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
610 break;
611 case BinaryOperator::LOr:
612 Result = Result != 0 || RHS != 0;
613 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
614 break;
Eli Friedmanb11e7782008-11-13 02:13:11 +0000615 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000616
617 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000618 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000619}
620
Sebastian Redl05189992008-11-11 17:56:53 +0000621/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
622/// expression's type.
623bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
624 QualType DstTy = E->getType();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000625 // Return the result in the right width.
626 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
627 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
628
Sebastian Redl05189992008-11-11 17:56:53 +0000629 QualType SrcTy = E->getTypeOfArgument();
630
Chris Lattnerfcee0012008-07-11 21:24:13 +0000631 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman4efaa272008-11-12 09:44:48 +0000632 if (SrcTy->isVoidType()) {
Chris Lattnerfcee0012008-07-11 21:24:13 +0000633 Result = 1;
Eli Friedman4efaa272008-11-12 09:44:48 +0000634 return true;
635 }
Chris Lattnerfcee0012008-07-11 21:24:13 +0000636
637 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman4efaa272008-11-12 09:44:48 +0000638 // FIXME: But alignof(vla) is!
Chris Lattnerfcee0012008-07-11 21:24:13 +0000639 if (!SrcTy->isConstantSizeType()) {
640 // FIXME: Should we attempt to evaluate this?
641 return false;
642 }
Sebastian Redl05189992008-11-11 17:56:53 +0000643
644 bool isSizeOf = E->isSizeOf();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000645
646 // GCC extension: sizeof(function) = 1.
647 if (SrcTy->isFunctionType()) {
648 // FIXME: AlignOf shouldn't be unconditionally 4!
649 Result = isSizeOf ? 1 : 4;
650 return true;
651 }
652
653 // Get information about the size or align.
Chris Lattner87eae5e2008-07-11 22:52:41 +0000654 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattnerfcee0012008-07-11 21:24:13 +0000655 if (isSizeOf)
Eli Friedman4efaa272008-11-12 09:44:48 +0000656 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000657 else
Chris Lattner87eae5e2008-07-11 22:52:41 +0000658 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattnerfcee0012008-07-11 21:24:13 +0000659 return true;
660}
661
Chris Lattnerb542afe2008-07-11 19:10:17 +0000662bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000663 // Special case unary operators that do not need their subexpression
664 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner75a48812008-07-11 22:15:16 +0000665 if (E->isOffsetOfOp()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000666 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner87eae5e2008-07-11 22:52:41 +0000667 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner75a48812008-07-11 22:15:16 +0000668 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
669 return true;
670 }
Eli Friedmana6afa762008-11-13 06:09:17 +0000671
672 if (E->getOpcode() == UnaryOperator::LNot) {
673 // LNot's operand isn't necessarily an integer, so we handle it specially.
674 bool bres;
675 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
676 return false;
677 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
678 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
679 Result = !bres;
680 return true;
681 }
682
Chris Lattner87eae5e2008-07-11 22:52:41 +0000683 // Get the operand value into 'Result'.
684 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +0000685 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000686
Chris Lattner75a48812008-07-11 22:15:16 +0000687 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000688 default:
Chris Lattner75a48812008-07-11 22:15:16 +0000689 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
690 // See C99 6.6p3.
Chris Lattner32fea9d2008-11-12 07:43:42 +0000691 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
692 E->getType());
Chris Lattner75a48812008-07-11 22:15:16 +0000693 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000694 // FIXME: Should extension allow i-c-e extension expressions in its scope?
695 // If so, we could clear the diagnostic ID.
Chris Lattner75a48812008-07-11 22:15:16 +0000696 case UnaryOperator::Plus:
Chris Lattner4c4867e2008-07-12 00:38:25 +0000697 // The result is always just the subexpr.
Chris Lattner75a48812008-07-11 22:15:16 +0000698 break;
699 case UnaryOperator::Minus:
700 Result = -Result;
701 break;
702 case UnaryOperator::Not:
703 Result = ~Result;
704 break;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000705 }
706
707 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnerb542afe2008-07-11 19:10:17 +0000708 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000709}
710
Chris Lattner732b2232008-07-12 01:15:53 +0000711/// HandleCast - This is used to evaluate implicit or explicit casts where the
712/// result type is integer.
713bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
714 Expr *SubExpr, QualType DestType) {
Chris Lattner7a767782008-07-11 19:24:49 +0000715 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000716
Eli Friedman4efaa272008-11-12 09:44:48 +0000717 if (DestType->isBooleanType()) {
718 bool BoolResult;
719 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
720 return false;
721 Result.zextOrTrunc(DestWidth);
722 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
723 Result = BoolResult;
724 return true;
725 }
726
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000727 // Handle simple integer->integer casts.
Eli Friedmana6afa762008-11-13 06:09:17 +0000728 if (SubExpr->getType()->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +0000729 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000730 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000731
732 // Figure out if this is a truncate, extend or noop cast.
733 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman4efaa272008-11-12 09:44:48 +0000734 Result.extOrTrunc(DestWidth);
Chris Lattner732b2232008-07-12 01:15:53 +0000735 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
736 return true;
737 }
738
739 // FIXME: Clean this up!
740 if (SubExpr->getType()->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000741 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000742 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +0000743 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000744
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000745 if (LV.getLValueBase())
Chris Lattnerb542afe2008-07-11 19:10:17 +0000746 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000747
Anders Carlsson559e56b2008-07-08 16:49:00 +0000748 Result.extOrTrunc(DestWidth);
749 Result = LV.getLValueOffset();
Chris Lattner732b2232008-07-12 01:15:53 +0000750 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
751 return true;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000752 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000753
Chris Lattner732b2232008-07-12 01:15:53 +0000754 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner32fea9d2008-11-12 07:43:42 +0000755 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000756
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000757 APFloat F(0.0);
758 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner32fea9d2008-11-12 07:43:42 +0000759 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattner732b2232008-07-12 01:15:53 +0000760
761 // Determine whether we are converting to unsigned or signed.
762 bool DestSigned = DestType->isSignedIntegerType();
763
764 // FIXME: Warning for overflow.
Dale Johannesenee5a7002008-10-09 23:02:32 +0000765 uint64_t Space[4];
766 bool ignored;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000767 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesenee5a7002008-10-09 23:02:32 +0000768 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattner732b2232008-07-12 01:15:53 +0000769 Result = llvm::APInt(DestWidth, 4, Space);
770 Result.setIsUnsigned(!DestSigned);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000771 return true;
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000772}
Anders Carlsson2bad1682008-07-08 14:30:00 +0000773
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000774//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000775// Float Evaluation
776//===----------------------------------------------------------------------===//
777
778namespace {
779class VISIBILITY_HIDDEN FloatExprEvaluator
780 : public StmtVisitor<FloatExprEvaluator, bool> {
781 EvalInfo &Info;
782 APFloat &Result;
783public:
784 FloatExprEvaluator(EvalInfo &info, APFloat &result)
785 : Info(info), Result(result) {}
786
787 bool VisitStmt(Stmt *S) {
788 return false;
789 }
790
791 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +0000792 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000793
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000794 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000795 bool VisitBinaryOperator(const BinaryOperator *E);
796 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000797 bool VisitCastExpr(CastExpr *E);
798 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000799};
800} // end anonymous namespace
801
802static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
803 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
804}
805
Chris Lattner019f4e82008-10-06 05:28:25 +0000806bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner019f4e82008-10-06 05:28:25 +0000807 switch (E->isBuiltinCall()) {
Chris Lattner34a74ab2008-10-06 05:53:16 +0000808 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +0000809 case Builtin::BI__builtin_huge_val:
810 case Builtin::BI__builtin_huge_valf:
811 case Builtin::BI__builtin_huge_vall:
812 case Builtin::BI__builtin_inf:
813 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000814 case Builtin::BI__builtin_infl: {
815 const llvm::fltSemantics &Sem =
816 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +0000817 Result = llvm::APFloat::getInf(Sem);
818 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000819 }
Chris Lattner9e621712008-10-06 06:31:58 +0000820
821 case Builtin::BI__builtin_nan:
822 case Builtin::BI__builtin_nanf:
823 case Builtin::BI__builtin_nanl:
824 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
825 // can't constant fold it.
826 if (const StringLiteral *S =
827 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
828 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar7cbed032008-10-14 05:41:12 +0000829 const llvm::fltSemantics &Sem =
830 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner9e621712008-10-06 06:31:58 +0000831 Result = llvm::APFloat::getNaN(Sem);
832 return true;
833 }
834 }
835 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000836
837 case Builtin::BI__builtin_fabs:
838 case Builtin::BI__builtin_fabsf:
839 case Builtin::BI__builtin_fabsl:
840 if (!EvaluateFloat(E->getArg(0), Result, Info))
841 return false;
842
843 if (Result.isNegative())
844 Result.changeSign();
845 return true;
846
847 case Builtin::BI__builtin_copysign:
848 case Builtin::BI__builtin_copysignf:
849 case Builtin::BI__builtin_copysignl: {
850 APFloat RHS(0.);
851 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
852 !EvaluateFloat(E->getArg(1), RHS, Info))
853 return false;
854 Result.copySign(RHS);
855 return true;
856 }
Chris Lattner019f4e82008-10-06 05:28:25 +0000857 }
858}
859
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000860bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
861 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
862 return false;
863
864 switch (E->getOpcode()) {
865 default: return false;
866 case UnaryOperator::Plus:
867 return true;
868 case UnaryOperator::Minus:
869 Result.changeSign();
870 return true;
871 }
872}
Chris Lattner019f4e82008-10-06 05:28:25 +0000873
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000874bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
875 // FIXME: Diagnostics? I really don't understand how the warnings
876 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +0000877 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000878 if (!EvaluateFloat(E->getLHS(), Result, Info))
879 return false;
880 if (!EvaluateFloat(E->getRHS(), RHS, Info))
881 return false;
882
883 switch (E->getOpcode()) {
884 default: return false;
885 case BinaryOperator::Mul:
886 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
887 return true;
888 case BinaryOperator::Add:
889 Result.add(RHS, APFloat::rmNearestTiesToEven);
890 return true;
891 case BinaryOperator::Sub:
892 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
893 return true;
894 case BinaryOperator::Div:
895 Result.divide(RHS, APFloat::rmNearestTiesToEven);
896 return true;
897 case BinaryOperator::Rem:
898 Result.mod(RHS, APFloat::rmNearestTiesToEven);
899 return true;
900 }
901}
902
903bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
904 Result = E->getValue();
905 return true;
906}
907
Eli Friedman4efaa272008-11-12 09:44:48 +0000908bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
909 Expr* SubExpr = E->getSubExpr();
910 const llvm::fltSemantics& destSemantics =
911 Info.Ctx.getFloatTypeSemantics(E->getType());
912 if (SubExpr->getType()->isIntegralType()) {
913 APSInt IntResult;
914 if (!EvaluateInteger(E, IntResult, Info))
915 return false;
916 Result = APFloat(destSemantics, 1);
917 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
918 APFloat::rmNearestTiesToEven);
919 return true;
920 }
921 if (SubExpr->getType()->isRealFloatingType()) {
922 if (!Visit(SubExpr))
923 return false;
924 bool ignored;
925 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
926 return true;
927 }
928
929 return false;
930}
931
932bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
933 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
934 return true;
935}
936
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000937//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000938// Top level TryEvaluate.
939//===----------------------------------------------------------------------===//
940
Chris Lattner019f4e82008-10-06 05:28:25 +0000941/// tryEvaluate - Return true if this is a constant which we can fold using
942/// any crazy technique (that has nothing to do with language standards) that
943/// we want to. If this function returns true, it returns the folded constant
944/// in Result.
Chris Lattnerb542afe2008-07-11 19:10:17 +0000945bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000946 EvalInfo Info(Ctx);
Anders Carlsson06a36752008-07-08 05:49:43 +0000947 if (getType()->isIntegerType()) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000948 llvm::APSInt sInt(32);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000949 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlsson06a36752008-07-08 05:49:43 +0000950 Result = APValue(sInt);
951 return true;
952 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000953 } else if (getType()->isPointerType()) {
954 if (EvaluatePointer(this, Result, Info)) {
955 return true;
956 }
957 } else if (getType()->isRealFloatingType()) {
958 llvm::APFloat f(0.0);
959 if (EvaluateFloat(this, f, Info)) {
960 Result = APValue(f);
961 return true;
962 }
963 }
Anders Carlsson165a70f2008-08-10 17:03:01 +0000964
Anders Carlssonc44eec62008-07-03 04:20:39 +0000965 return false;
966}
Chris Lattner45b6b9d2008-10-06 06:49:02 +0000967
968/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
969/// folded, but discard the result.
970bool Expr::isEvaluatable(ASTContext &Ctx) const {
971 APValue V;
972 return tryEvaluate(V, Ctx);
973}