blob: d6a4094520da2449aaf91a782fdd0eac65dc1f12 [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); }
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 Lattnera823ccf2008-07-11 18:11:29 +0000174// Pointer Evaluation
175//===----------------------------------------------------------------------===//
176
Anders Carlssoncad17b52008-07-08 05:13:58 +0000177namespace {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000178class VISIBILITY_HIDDEN PointerExprEvaluator
179 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner422373c2008-07-11 22:52:41 +0000180 EvalInfo &Info;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000181public:
Anders Carlsson02a34c32008-07-08 14:30:00 +0000182
Chris Lattner422373c2008-07-11 22:52:41 +0000183 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000184
Anders Carlsson02a34c32008-07-08 14:30:00 +0000185 APValue VisitStmt(Stmt *S) {
Anders Carlsson02a34c32008-07-08 14:30:00 +0000186 return APValue();
187 }
188
189 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
190
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000191 APValue VisitBinaryOperator(const BinaryOperator *E);
192 APValue VisitCastExpr(const CastExpr* E);
Eli Friedman7888b932008-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 Carlssonc43f44b2008-07-08 15:34:11 +0000197};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000198} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000199
Chris Lattner422373c2008-07-11 22:52:41 +0000200static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000201 if (!E->getType()->isPointerType())
202 return false;
Chris Lattner422373c2008-07-11 22:52:41 +0000203 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnera823ccf2008-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 Lattner422373c2008-07-11 22:52:41 +0000218 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000219 return APValue();
220
221 llvm::APSInt AdditionalOffset(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000222 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000223 return APValue();
224
Eli Friedman7888b932008-11-12 09:44:48 +0000225 QualType PointeeType = PExp->getType()->getAsPointerType()->getPointeeType();
226 uint64_t SizeOfPointee = Info.Ctx.getTypeSize(PointeeType) / 8;
227
Chris Lattnera823ccf2008-07-11 18:11:29 +0000228 uint64_t Offset = ResultLValue.getLValueOffset();
Eli Friedman7888b932008-11-12 09:44:48 +0000229
Chris Lattnera823ccf2008-07-11 18:11:29 +0000230 if (E->getOpcode() == BinaryOperator::Add)
Eli Friedman7888b932008-11-12 09:44:48 +0000231 Offset += AdditionalOffset.getLimitedValue() * SizeOfPointee;
Chris Lattnera823ccf2008-07-11 18:11:29 +0000232 else
Eli Friedman7888b932008-11-12 09:44:48 +0000233 Offset -= AdditionalOffset.getLimitedValue() * SizeOfPointee;
234
Chris Lattnera823ccf2008-07-11 18:11:29 +0000235 return APValue(ResultLValue.getLValueBase(), Offset);
236}
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000252
253
Chris Lattnera42f09a2008-07-11 19:10:17 +0000254APValue PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
Chris Lattnera823ccf2008-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 Lattner422373c2008-07-11 22:52:41 +0000260 if (EvaluatePointer(SubExpr, Result, Info))
Chris Lattnera823ccf2008-07-11 18:11:29 +0000261 return Result;
262 return APValue();
263 }
264
Eli Friedman3e64dd72008-07-27 05:46:18 +0000265 if (SubExpr->getType()->isIntegralType()) {
Chris Lattnera823ccf2008-07-11 18:11:29 +0000266 llvm::APSInt Result(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000267 if (EvaluateInteger(SubExpr, Result, Info)) {
268 Result.extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Chris Lattnera823ccf2008-07-11 18:11:29 +0000269 return APValue(0, Result.getZExtValue());
270 }
271 }
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000282 return APValue();
283}
284
Eli Friedman7888b932008-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 Lattnera823ccf2008-07-11 18:11:29 +0000297
298//===----------------------------------------------------------------------===//
299// Integer Evaluation
300//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000301
302namespace {
Anders Carlssoncad17b52008-07-08 05:13:58 +0000303class VISIBILITY_HIDDEN IntExprEvaluator
Chris Lattnera42f09a2008-07-11 19:10:17 +0000304 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner422373c2008-07-11 22:52:41 +0000305 EvalInfo &Info;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000306 APSInt &Result;
Anders Carlssoncad17b52008-07-08 05:13:58 +0000307public:
Chris Lattner422373c2008-07-11 22:52:41 +0000308 IntExprEvaluator(EvalInfo &info, APSInt &result)
309 : Info(info), Result(result) {}
Chris Lattnera823ccf2008-07-11 18:11:29 +0000310
Chris Lattner2c99c712008-07-11 19:24:49 +0000311 unsigned getIntTypeSizeInBits(QualType T) const {
Chris Lattner82437da2008-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 Lattner438f3b12008-11-12 07:43:42 +0000321 bool Error(SourceLocation L, diag::kind D, QualType ExprTy) {
Chris Lattner82437da2008-07-12 00:14:42 +0000322 // If this is in an unevaluated portion of the subexpression, ignore the
323 // error.
Chris Lattner438f3b12008-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 Lattner82437da2008-07-12 00:14:42 +0000329 return true;
Chris Lattner438f3b12008-11-12 07:43:42 +0000330 }
Chris Lattner82437da2008-07-12 00:14:42 +0000331
Chris Lattner438f3b12008-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 Lattner82437da2008-07-12 00:14:42 +0000337 return false;
Chris Lattner2c99c712008-07-11 19:24:49 +0000338 }
339
Anders Carlssoncad17b52008-07-08 05:13:58 +0000340 //===--------------------------------------------------------------------===//
341 // Visitor Methods
342 //===--------------------------------------------------------------------===//
Chris Lattner438f3b12008-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 Lattner2c99c712008-07-11 19:24:49 +0000348
Chris Lattner438f3b12008-11-12 07:43:42 +0000349 bool VisitExpr(Expr *E) {
350 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Anders Carlssoncad17b52008-07-08 05:13:58 +0000351 }
352
Chris Lattnera42f09a2008-07-11 19:10:17 +0000353 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssoncad17b52008-07-08 05:13:58 +0000354
Chris Lattner15e59112008-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 Dunbarda8ebd22008-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 Lattner15e59112008-07-12 00:38:25 +0000375 return true;
376 }
377 bool VisitDeclRefExpr(const DeclRefExpr *E);
378 bool VisitCallExpr(const CallExpr *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000379 bool VisitBinaryOperator(const BinaryOperator *E);
380 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000381
Chris Lattnerff579ff2008-07-12 01:15:53 +0000382 bool VisitCastExpr(CastExpr* E) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000383 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000384 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000385 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
386
Chris Lattner265a0892008-07-11 21:24:13 +0000387private:
Chris Lattnerff579ff2008-07-12 01:15:53 +0000388 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000389};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000390} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000391
Chris Lattner422373c2008-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 Carlssonc43f44b2008-07-08 15:34:11 +0000394}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000395
Chris Lattner15e59112008-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 Lattner438f3b12008-11-12 07:43:42 +0000404 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner15e59112008-07-12 00:38:25 +0000405}
406
Chris Lattner1eee9402008-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 Lattner15e59112008-07-12 00:38:25 +0000462bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
463 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000464
Chris Lattner87293782008-10-06 05:28:25 +0000465 switch (E->isBuiltinCall()) {
466 default:
Chris Lattner438f3b12008-11-12 07:43:42 +0000467 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner87293782008-10-06 05:28:25 +0000468 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000469 Result.setIsSigned(true);
470 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-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 Lattner15e59112008-07-12 00:38:25 +0000481}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000482
Chris Lattnera42f09a2008-07-11 19:10:17 +0000483bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000484 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000485 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000486 if (!Visit(E->getLHS())) {
487 // If the LHS is unfoldable, we generally can't fold this. However, if this
488 // is a logical operator like &&/||, and if we know that the RHS determines
489 // the outcome of the result (e.g. X && 0), return the outcome.
490 if (!E->isLogicalOp())
491 return false;
492
493 // If this is a logical op, see if the RHS determines the outcome.
494 EvalInfo Info2(Info.Ctx);
495 if (!EvaluateInteger(E->getRHS(), RHS, Info2))
496 return false;
497
498 // X && 0 -> 0, X || 1 -> 1.
Eli Friedman7888b932008-11-12 09:44:48 +0000499 if ((E->getOpcode() == BinaryOperator::LAnd && RHS == 0) ||
500 (E->getOpcode() == BinaryOperator::LOr && RHS != 0)) {
Chris Lattner40d2ae82008-11-12 07:04:29 +0000501 Result = RHS != 0;
502 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner438f3b12008-11-12 07:43:42 +0000503 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner40d2ae82008-11-12 07:04:29 +0000504 return true;
505 }
506
Chris Lattner82437da2008-07-12 00:14:42 +0000507 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000508 }
Chris Lattner82437da2008-07-12 00:14:42 +0000509
510 bool OldEval = Info.isEvaluated;
511
512 // The short-circuiting &&/|| operators don't necessarily evaluate their
513 // RHS. Make sure to pass isEvaluated down correctly.
514 if ((E->getOpcode() == BinaryOperator::LAnd && Result == 0) ||
515 (E->getOpcode() == BinaryOperator::LOr && Result != 0))
516 Info.isEvaluated = false;
Eli Friedman3e64dd72008-07-27 05:46:18 +0000517
518 // FIXME: Handle pointer subtraction
519
520 // FIXME Maybe we want to succeed even where we can't evaluate the
521 // right side of LAnd/LOr?
522 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000523 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000524 return false;
Chris Lattner82437da2008-07-12 00:14:42 +0000525 Info.isEvaluated = OldEval;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000526
527 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000528 default:
529 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner82437da2008-07-12 00:14:42 +0000530 case BinaryOperator::Mul: Result *= RHS; return true;
531 case BinaryOperator::Add: Result += RHS; return true;
532 case BinaryOperator::Sub: Result -= RHS; return true;
533 case BinaryOperator::And: Result &= RHS; return true;
534 case BinaryOperator::Xor: Result ^= RHS; return true;
535 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000536 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000537 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000538 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
539 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000540 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000541 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000542 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000543 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000544 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
545 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000546 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000547 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000548 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000549 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000550 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000551 break;
552 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000553 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000554 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000555
Chris Lattner045502c2008-07-11 19:29:32 +0000556 case BinaryOperator::LT:
557 Result = Result < RHS;
558 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
559 break;
560 case BinaryOperator::GT:
561 Result = Result > RHS;
562 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
563 break;
564 case BinaryOperator::LE:
565 Result = Result <= RHS;
566 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
567 break;
568 case BinaryOperator::GE:
569 Result = Result >= RHS;
570 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
571 break;
572 case BinaryOperator::EQ:
573 Result = Result == RHS;
574 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
575 break;
576 case BinaryOperator::NE:
577 Result = Result != RHS;
578 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
579 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000580 case BinaryOperator::LAnd:
581 Result = Result != 0 && RHS != 0;
582 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
583 break;
584 case BinaryOperator::LOr:
585 Result = Result != 0 || RHS != 0;
586 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
587 break;
Eli Friedmanb2935ab2008-11-13 02:13:11 +0000588
589
590 case BinaryOperator::Comma:
591 // Result of the comma is just the result of the RHS.
592 Result = RHS;
593
594 // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
595 // *except* when they are contained within a subexpression that is not
596 // evaluated". Note that Assignment can never happen due to constraints
597 // on the LHS subexpr, so we don't need to check it here.
598 if (!Info.isEvaluated)
599 return true;
600
601 // If the value is evaluated, we can accept it as an extension.
602 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
603 }
Anders Carlssond1aa5812008-07-08 14:35:21 +0000604
605 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000606 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000607}
608
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000609/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
610/// expression's type.
611bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
612 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000613 // Return the result in the right width.
614 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
615 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
616
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000617 QualType SrcTy = E->getTypeOfArgument();
618
Chris Lattner265a0892008-07-11 21:24:13 +0000619 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000620 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000621 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000622 return true;
623 }
Chris Lattner265a0892008-07-11 21:24:13 +0000624
625 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000626 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000627 if (!SrcTy->isConstantSizeType()) {
628 // FIXME: Should we attempt to evaluate this?
629 return false;
630 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000631
632 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000633
634 // GCC extension: sizeof(function) = 1.
635 if (SrcTy->isFunctionType()) {
636 // FIXME: AlignOf shouldn't be unconditionally 4!
637 Result = isSizeOf ? 1 : 4;
638 return true;
639 }
640
641 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000642 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000643 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000644 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000645 else
Chris Lattner422373c2008-07-11 22:52:41 +0000646 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000647 return true;
648}
649
Chris Lattnera42f09a2008-07-11 19:10:17 +0000650bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000651 // Special case unary operators that do not need their subexpression
652 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000653 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000654 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000655 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000656 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
657 return true;
658 }
659
Chris Lattner422373c2008-07-11 22:52:41 +0000660 // Get the operand value into 'Result'.
661 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000662 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000663
Chris Lattner400d7402008-07-11 22:15:16 +0000664 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000665 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000666 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
667 // See C99 6.6p3.
Chris Lattner438f3b12008-11-12 07:43:42 +0000668 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
669 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000670 case UnaryOperator::LNot: {
671 bool Val = Result == 0;
672 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
673 Result = Val;
674 break;
675 }
676 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000677 // FIXME: Should extension allow i-c-e extension expressions in its scope?
678 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000679 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000680 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000681 break;
682 case UnaryOperator::Minus:
683 Result = -Result;
684 break;
685 case UnaryOperator::Not:
686 Result = ~Result;
687 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000688 }
689
690 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000691 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000692}
693
Chris Lattnerff579ff2008-07-12 01:15:53 +0000694/// HandleCast - This is used to evaluate implicit or explicit casts where the
695/// result type is integer.
696bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
697 Expr *SubExpr, QualType DestType) {
Chris Lattner2c99c712008-07-11 19:24:49 +0000698 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000699
Eli Friedman7888b932008-11-12 09:44:48 +0000700 if (DestType->isBooleanType()) {
701 bool BoolResult;
702 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
703 return false;
704 Result.zextOrTrunc(DestWidth);
705 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
706 Result = BoolResult;
707 return true;
708 }
709
Anders Carlssond1aa5812008-07-08 14:35:21 +0000710 // Handle simple integer->integer casts.
711 if (SubExpr->getType()->isIntegerType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000712 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000713 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000714
715 // Figure out if this is a truncate, extend or noop cast.
716 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000717 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000718 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
719 return true;
720 }
721
722 // FIXME: Clean this up!
723 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000724 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000725 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000726 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000727
Anders Carlssond1aa5812008-07-08 14:35:21 +0000728 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000729 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000730
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000731 Result.extOrTrunc(DestWidth);
732 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000733 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
734 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000735 }
Eli Friedman7888b932008-11-12 09:44:48 +0000736
Chris Lattnerff579ff2008-07-12 01:15:53 +0000737 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner438f3b12008-11-12 07:43:42 +0000738 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000739
Eli Friedman2f445492008-08-22 00:06:13 +0000740 APFloat F(0.0);
741 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner438f3b12008-11-12 07:43:42 +0000742 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000743
744 // Determine whether we are converting to unsigned or signed.
745 bool DestSigned = DestType->isSignedIntegerType();
746
747 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000748 uint64_t Space[4];
749 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000750 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000751 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000752 Result = llvm::APInt(DestWidth, 4, Space);
753 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000754 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000755}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000756
Chris Lattnera823ccf2008-07-11 18:11:29 +0000757//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000758// Float Evaluation
759//===----------------------------------------------------------------------===//
760
761namespace {
762class VISIBILITY_HIDDEN FloatExprEvaluator
763 : public StmtVisitor<FloatExprEvaluator, bool> {
764 EvalInfo &Info;
765 APFloat &Result;
766public:
767 FloatExprEvaluator(EvalInfo &info, APFloat &result)
768 : Info(info), Result(result) {}
769
770 bool VisitStmt(Stmt *S) {
771 return false;
772 }
773
774 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000775 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000776
Daniel Dunbar804ead02008-10-16 03:51:50 +0000777 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000778 bool VisitBinaryOperator(const BinaryOperator *E);
779 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000780 bool VisitCastExpr(CastExpr *E);
781 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000782};
783} // end anonymous namespace
784
785static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
786 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
787}
788
Chris Lattner87293782008-10-06 05:28:25 +0000789bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000790 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000791 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000792 case Builtin::BI__builtin_huge_val:
793 case Builtin::BI__builtin_huge_valf:
794 case Builtin::BI__builtin_huge_vall:
795 case Builtin::BI__builtin_inf:
796 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000797 case Builtin::BI__builtin_infl: {
798 const llvm::fltSemantics &Sem =
799 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000800 Result = llvm::APFloat::getInf(Sem);
801 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000802 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000803
804 case Builtin::BI__builtin_nan:
805 case Builtin::BI__builtin_nanf:
806 case Builtin::BI__builtin_nanl:
807 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
808 // can't constant fold it.
809 if (const StringLiteral *S =
810 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
811 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000812 const llvm::fltSemantics &Sem =
813 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000814 Result = llvm::APFloat::getNaN(Sem);
815 return true;
816 }
817 }
818 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000819
820 case Builtin::BI__builtin_fabs:
821 case Builtin::BI__builtin_fabsf:
822 case Builtin::BI__builtin_fabsl:
823 if (!EvaluateFloat(E->getArg(0), Result, Info))
824 return false;
825
826 if (Result.isNegative())
827 Result.changeSign();
828 return true;
829
830 case Builtin::BI__builtin_copysign:
831 case Builtin::BI__builtin_copysignf:
832 case Builtin::BI__builtin_copysignl: {
833 APFloat RHS(0.);
834 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
835 !EvaluateFloat(E->getArg(1), RHS, Info))
836 return false;
837 Result.copySign(RHS);
838 return true;
839 }
Chris Lattner87293782008-10-06 05:28:25 +0000840 }
841}
842
Daniel Dunbar804ead02008-10-16 03:51:50 +0000843bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
844 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
845 return false;
846
847 switch (E->getOpcode()) {
848 default: return false;
849 case UnaryOperator::Plus:
850 return true;
851 case UnaryOperator::Minus:
852 Result.changeSign();
853 return true;
854 }
855}
Chris Lattner87293782008-10-06 05:28:25 +0000856
Eli Friedman2f445492008-08-22 00:06:13 +0000857bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
858 // FIXME: Diagnostics? I really don't understand how the warnings
859 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +0000860 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +0000861 if (!EvaluateFloat(E->getLHS(), Result, Info))
862 return false;
863 if (!EvaluateFloat(E->getRHS(), RHS, Info))
864 return false;
865
866 switch (E->getOpcode()) {
867 default: return false;
868 case BinaryOperator::Mul:
869 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
870 return true;
871 case BinaryOperator::Add:
872 Result.add(RHS, APFloat::rmNearestTiesToEven);
873 return true;
874 case BinaryOperator::Sub:
875 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
876 return true;
877 case BinaryOperator::Div:
878 Result.divide(RHS, APFloat::rmNearestTiesToEven);
879 return true;
880 case BinaryOperator::Rem:
881 Result.mod(RHS, APFloat::rmNearestTiesToEven);
882 return true;
883 }
884}
885
886bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
887 Result = E->getValue();
888 return true;
889}
890
Eli Friedman7888b932008-11-12 09:44:48 +0000891bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
892 Expr* SubExpr = E->getSubExpr();
893 const llvm::fltSemantics& destSemantics =
894 Info.Ctx.getFloatTypeSemantics(E->getType());
895 if (SubExpr->getType()->isIntegralType()) {
896 APSInt IntResult;
897 if (!EvaluateInteger(E, IntResult, Info))
898 return false;
899 Result = APFloat(destSemantics, 1);
900 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
901 APFloat::rmNearestTiesToEven);
902 return true;
903 }
904 if (SubExpr->getType()->isRealFloatingType()) {
905 if (!Visit(SubExpr))
906 return false;
907 bool ignored;
908 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
909 return true;
910 }
911
912 return false;
913}
914
915bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
916 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
917 return true;
918}
919
Eli Friedman2f445492008-08-22 00:06:13 +0000920//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000921// Top level TryEvaluate.
922//===----------------------------------------------------------------------===//
923
Chris Lattner87293782008-10-06 05:28:25 +0000924/// tryEvaluate - Return true if this is a constant which we can fold using
925/// any crazy technique (that has nothing to do with language standards) that
926/// we want to. If this function returns true, it returns the folded constant
927/// in Result.
Chris Lattnera42f09a2008-07-11 19:10:17 +0000928bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner422373c2008-07-11 22:52:41 +0000929 EvalInfo Info(Ctx);
Anders Carlssonc0328012008-07-08 05:49:43 +0000930 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +0000931 llvm::APSInt sInt(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000932 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlssonc0328012008-07-08 05:49:43 +0000933 Result = APValue(sInt);
934 return true;
935 }
Eli Friedman2f445492008-08-22 00:06:13 +0000936 } else if (getType()->isPointerType()) {
937 if (EvaluatePointer(this, Result, Info)) {
938 return true;
939 }
940 } else if (getType()->isRealFloatingType()) {
941 llvm::APFloat f(0.0);
942 if (EvaluateFloat(this, f, Info)) {
943 Result = APValue(f);
944 return true;
945 }
946 }
Anders Carlsson47968a92008-08-10 17:03:01 +0000947
Anders Carlssonc7436af2008-07-03 04:20:39 +0000948 return false;
949}
Chris Lattner2d9a3f62008-10-06 06:49:02 +0000950
951/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
952/// folded, but discard the result.
953bool Expr::isEvaluatable(ASTContext &Ctx) const {
954 APValue V;
955 return tryEvaluate(V, Ctx);
956}