blob: f5477f30b30b78dce62f7b09984b4baafdade88d [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);
Daniel Dunbar750c01b2008-11-13 00:03:19 +0000379 bool VisitBinOpComma(const BinaryOperator *E);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000380 bool VisitBinaryOperator(const BinaryOperator *E);
381 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlssonc0328012008-07-08 05:49:43 +0000382
Chris Lattnerff579ff2008-07-12 01:15:53 +0000383 bool VisitCastExpr(CastExpr* E) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000384 return HandleCast(E->getLocStart(), E->getSubExpr(), E->getType());
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000385 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000386 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
387
Chris Lattner265a0892008-07-11 21:24:13 +0000388private:
Chris Lattnerff579ff2008-07-12 01:15:53 +0000389 bool HandleCast(SourceLocation CastLoc, Expr *SubExpr, QualType DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000390};
Chris Lattnera823ccf2008-07-11 18:11:29 +0000391} // end anonymous namespace
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000392
Chris Lattner422373c2008-07-11 22:52:41 +0000393static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
394 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000395}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000396
Chris Lattner15e59112008-07-12 00:38:25 +0000397bool IntExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
398 // Enums are integer constant exprs.
399 if (const EnumConstantDecl *D = dyn_cast<EnumConstantDecl>(E->getDecl())) {
400 Result = D->getInitVal();
401 return true;
402 }
403
404 // Otherwise, random variable references are not constants.
Chris Lattner438f3b12008-11-12 07:43:42 +0000405 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner15e59112008-07-12 00:38:25 +0000406}
407
Chris Lattner1eee9402008-10-06 06:40:35 +0000408/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
409/// as GCC.
410static int EvaluateBuiltinClassifyType(const CallExpr *E) {
411 // The following enum mimics the values returned by GCC.
412 enum gcc_type_class {
413 no_type_class = -1,
414 void_type_class, integer_type_class, char_type_class,
415 enumeral_type_class, boolean_type_class,
416 pointer_type_class, reference_type_class, offset_type_class,
417 real_type_class, complex_type_class,
418 function_type_class, method_type_class,
419 record_type_class, union_type_class,
420 array_type_class, string_type_class,
421 lang_type_class
422 };
423
424 // If no argument was supplied, default to "no_type_class". This isn't
425 // ideal, however it is what gcc does.
426 if (E->getNumArgs() == 0)
427 return no_type_class;
428
429 QualType ArgTy = E->getArg(0)->getType();
430 if (ArgTy->isVoidType())
431 return void_type_class;
432 else if (ArgTy->isEnumeralType())
433 return enumeral_type_class;
434 else if (ArgTy->isBooleanType())
435 return boolean_type_class;
436 else if (ArgTy->isCharType())
437 return string_type_class; // gcc doesn't appear to use char_type_class
438 else if (ArgTy->isIntegerType())
439 return integer_type_class;
440 else if (ArgTy->isPointerType())
441 return pointer_type_class;
442 else if (ArgTy->isReferenceType())
443 return reference_type_class;
444 else if (ArgTy->isRealType())
445 return real_type_class;
446 else if (ArgTy->isComplexType())
447 return complex_type_class;
448 else if (ArgTy->isFunctionType())
449 return function_type_class;
450 else if (ArgTy->isStructureType())
451 return record_type_class;
452 else if (ArgTy->isUnionType())
453 return union_type_class;
454 else if (ArgTy->isArrayType())
455 return array_type_class;
456 else if (ArgTy->isUnionType())
457 return union_type_class;
458 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
459 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
460 return -1;
461}
462
Chris Lattner15e59112008-07-12 00:38:25 +0000463bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
464 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner15e59112008-07-12 00:38:25 +0000465
Chris Lattner87293782008-10-06 05:28:25 +0000466 switch (E->isBuiltinCall()) {
467 default:
Chris Lattner438f3b12008-11-12 07:43:42 +0000468 return Error(E->getLocStart(), diag::err_expr_not_constant, E->getType());
Chris Lattner87293782008-10-06 05:28:25 +0000469 case Builtin::BI__builtin_classify_type:
Chris Lattner1eee9402008-10-06 06:40:35 +0000470 Result.setIsSigned(true);
471 Result = EvaluateBuiltinClassifyType(E);
Chris Lattner87293782008-10-06 05:28:25 +0000472 return true;
473
474 case Builtin::BI__builtin_constant_p: {
475 // __builtin_constant_p always has one operand: it returns true if that
476 // operand can be folded, false otherwise.
477 APValue Res;
478 Result = E->getArg(0)->tryEvaluate(Res, Info.Ctx);
479 return true;
480 }
481 }
Chris Lattner15e59112008-07-12 00:38:25 +0000482}
Anders Carlssonc43f44b2008-07-08 15:34:11 +0000483
Daniel Dunbar750c01b2008-11-13 00:03:19 +0000484bool IntExprEvaluator::VisitBinOpComma(const BinaryOperator *E) {
485 llvm::APSInt RHS(32);
486
487 // Require that we be able to evaluate the LHS.
488 if (!E->getLHS()->isEvaluatable(Info.Ctx))
489 return false;
490
491 bool OldEval = Info.isEvaluated;
492 if (!EvaluateInteger(E->getRHS(), RHS, Info))
493 return false;
494 Info.isEvaluated = OldEval;
495
496 // Result of the comma is just the result of the RHS.
497 Result = RHS;
498
499 // C99 6.6p3: "shall not contain assignment, ..., or comma operators,
500 // *except* when they are contained within a subexpression that is not
501 // evaluated". Note that Assignment can never happen due to constraints
502 // on the LHS subexpr, so we don't need to check it here.
503 if (!Info.isEvaluated)
504 return true;
505
506 // If the value is evaluated, we can accept it as an extension.
507 return Extension(E->getOperatorLoc(), diag::ext_comma_in_constant_expr);
508}
509
Chris Lattnera42f09a2008-07-11 19:10:17 +0000510bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Daniel Dunbar750c01b2008-11-13 00:03:19 +0000511 // Comma operator requires special handling.
512 if (E->getOpcode() == BinaryOperator::Comma)
513 return VisitBinOpComma(E);
514
Anders Carlssond1aa5812008-07-08 14:35:21 +0000515 // The LHS of a constant expr is always evaluated and needed.
Anders Carlssond1aa5812008-07-08 14:35:21 +0000516 llvm::APSInt RHS(32);
Chris Lattner40d2ae82008-11-12 07:04:29 +0000517 if (!Visit(E->getLHS())) {
518 // If the LHS is unfoldable, we generally can't fold this. However, if this
519 // is a logical operator like &&/||, and if we know that the RHS determines
520 // the outcome of the result (e.g. X && 0), return the outcome.
521 if (!E->isLogicalOp())
522 return false;
523
524 // If this is a logical op, see if the RHS determines the outcome.
525 EvalInfo Info2(Info.Ctx);
526 if (!EvaluateInteger(E->getRHS(), RHS, Info2))
527 return false;
528
529 // X && 0 -> 0, X || 1 -> 1.
Eli Friedman7888b932008-11-12 09:44:48 +0000530 if ((E->getOpcode() == BinaryOperator::LAnd && RHS == 0) ||
531 (E->getOpcode() == BinaryOperator::LOr && RHS != 0)) {
Chris Lattner40d2ae82008-11-12 07:04:29 +0000532 Result = RHS != 0;
533 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner438f3b12008-11-12 07:43:42 +0000534 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattner40d2ae82008-11-12 07:04:29 +0000535 return true;
536 }
537
Chris Lattner82437da2008-07-12 00:14:42 +0000538 return false; // error in subexpression.
Chris Lattner40d2ae82008-11-12 07:04:29 +0000539 }
Chris Lattner82437da2008-07-12 00:14:42 +0000540
541 bool OldEval = Info.isEvaluated;
542
543 // The short-circuiting &&/|| operators don't necessarily evaluate their
544 // RHS. Make sure to pass isEvaluated down correctly.
545 if ((E->getOpcode() == BinaryOperator::LAnd && Result == 0) ||
546 (E->getOpcode() == BinaryOperator::LOr && Result != 0))
547 Info.isEvaluated = false;
Eli Friedman3e64dd72008-07-27 05:46:18 +0000548
549 // FIXME: Handle pointer subtraction
550
551 // FIXME Maybe we want to succeed even where we can't evaluate the
552 // right side of LAnd/LOr?
553 // For example, see http://llvm.org/bugs/show_bug.cgi?id=2525
Chris Lattner82437da2008-07-12 00:14:42 +0000554 if (!EvaluateInteger(E->getRHS(), RHS, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000555 return false;
Chris Lattner82437da2008-07-12 00:14:42 +0000556 Info.isEvaluated = OldEval;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000557
558 switch (E->getOpcode()) {
Chris Lattner438f3b12008-11-12 07:43:42 +0000559 default:
560 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,E->getType());
Chris Lattner82437da2008-07-12 00:14:42 +0000561 case BinaryOperator::Mul: Result *= RHS; return true;
562 case BinaryOperator::Add: Result += RHS; return true;
563 case BinaryOperator::Sub: Result -= RHS; return true;
564 case BinaryOperator::And: Result &= RHS; return true;
565 case BinaryOperator::Xor: Result ^= RHS; return true;
566 case BinaryOperator::Or: Result |= RHS; return true;
Chris Lattner400d7402008-07-11 22:15:16 +0000567 case BinaryOperator::Div:
Chris Lattner82437da2008-07-12 00:14:42 +0000568 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000569 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
570 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000571 Result /= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000572 break;
Chris Lattner400d7402008-07-11 22:15:16 +0000573 case BinaryOperator::Rem:
Chris Lattner82437da2008-07-12 00:14:42 +0000574 if (RHS == 0)
Chris Lattner438f3b12008-11-12 07:43:42 +0000575 return Error(E->getOperatorLoc(), diag::err_expr_divide_by_zero,
576 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000577 Result %= RHS;
Chris Lattner438f3b12008-11-12 07:43:42 +0000578 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000579 case BinaryOperator::Shl:
Chris Lattner82437da2008-07-12 00:14:42 +0000580 // FIXME: Warn about out of range shift amounts!
Chris Lattnera42f09a2008-07-11 19:10:17 +0000581 Result <<= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000582 break;
583 case BinaryOperator::Shr:
Chris Lattnera42f09a2008-07-11 19:10:17 +0000584 Result >>= (unsigned)RHS.getLimitedValue(Result.getBitWidth()-1);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000585 break;
Chris Lattnera42f09a2008-07-11 19:10:17 +0000586
Chris Lattner045502c2008-07-11 19:29:32 +0000587 case BinaryOperator::LT:
588 Result = Result < RHS;
589 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
590 break;
591 case BinaryOperator::GT:
592 Result = Result > RHS;
593 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
594 break;
595 case BinaryOperator::LE:
596 Result = Result <= RHS;
597 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
598 break;
599 case BinaryOperator::GE:
600 Result = Result >= RHS;
601 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
602 break;
603 case BinaryOperator::EQ:
604 Result = Result == RHS;
605 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
606 break;
607 case BinaryOperator::NE:
608 Result = Result != RHS;
609 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
610 break;
Chris Lattner82437da2008-07-12 00:14:42 +0000611 case BinaryOperator::LAnd:
612 Result = Result != 0 && RHS != 0;
613 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
614 break;
615 case BinaryOperator::LOr:
616 Result = Result != 0 || RHS != 0;
617 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
618 break;
Daniel Dunbar750c01b2008-11-13 00:03:19 +0000619}
Anders Carlssond1aa5812008-07-08 14:35:21 +0000620
621 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000622 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000623}
624
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000625/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
626/// expression's type.
627bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
628 QualType DstTy = E->getType();
Chris Lattner265a0892008-07-11 21:24:13 +0000629 // Return the result in the right width.
630 Result.zextOrTrunc(getIntTypeSizeInBits(DstTy));
631 Result.setIsUnsigned(DstTy->isUnsignedIntegerType());
632
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000633 QualType SrcTy = E->getTypeOfArgument();
634
Chris Lattner265a0892008-07-11 21:24:13 +0000635 // sizeof(void) and __alignof__(void) = 1 as a gcc extension.
Eli Friedman7888b932008-11-12 09:44:48 +0000636 if (SrcTy->isVoidType()) {
Chris Lattner265a0892008-07-11 21:24:13 +0000637 Result = 1;
Eli Friedman7888b932008-11-12 09:44:48 +0000638 return true;
639 }
Chris Lattner265a0892008-07-11 21:24:13 +0000640
641 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Eli Friedman7888b932008-11-12 09:44:48 +0000642 // FIXME: But alignof(vla) is!
Chris Lattner265a0892008-07-11 21:24:13 +0000643 if (!SrcTy->isConstantSizeType()) {
644 // FIXME: Should we attempt to evaluate this?
645 return false;
646 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000647
648 bool isSizeOf = E->isSizeOf();
Chris Lattner265a0892008-07-11 21:24:13 +0000649
650 // GCC extension: sizeof(function) = 1.
651 if (SrcTy->isFunctionType()) {
652 // FIXME: AlignOf shouldn't be unconditionally 4!
653 Result = isSizeOf ? 1 : 4;
654 return true;
655 }
656
657 // Get information about the size or align.
Chris Lattner422373c2008-07-11 22:52:41 +0000658 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Chris Lattner265a0892008-07-11 21:24:13 +0000659 if (isSizeOf)
Eli Friedman7888b932008-11-12 09:44:48 +0000660 Result = Info.Ctx.getTypeSize(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000661 else
Chris Lattner422373c2008-07-11 22:52:41 +0000662 Result = Info.Ctx.getTypeAlign(SrcTy) / CharSize;
Chris Lattner265a0892008-07-11 21:24:13 +0000663 return true;
664}
665
Chris Lattnera42f09a2008-07-11 19:10:17 +0000666bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner15e59112008-07-12 00:38:25 +0000667 // Special case unary operators that do not need their subexpression
668 // evaluated. offsetof/sizeof/alignof are all special.
Chris Lattner400d7402008-07-11 22:15:16 +0000669 if (E->isOffsetOfOp()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000670 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
Chris Lattner422373c2008-07-11 22:52:41 +0000671 Result = E->evaluateOffsetOf(Info.Ctx);
Chris Lattner400d7402008-07-11 22:15:16 +0000672 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
673 return true;
674 }
675
Chris Lattner422373c2008-07-11 22:52:41 +0000676 // Get the operand value into 'Result'.
677 if (!Visit(E->getSubExpr()))
Chris Lattner400d7402008-07-11 22:15:16 +0000678 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000679
Chris Lattner400d7402008-07-11 22:15:16 +0000680 switch (E->getOpcode()) {
Chris Lattner15e59112008-07-12 00:38:25 +0000681 default:
Chris Lattner400d7402008-07-11 22:15:16 +0000682 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
683 // See C99 6.6p3.
Chris Lattner438f3b12008-11-12 07:43:42 +0000684 return Error(E->getOperatorLoc(), diag::err_expr_not_constant,
685 E->getType());
Chris Lattner400d7402008-07-11 22:15:16 +0000686 case UnaryOperator::LNot: {
687 bool Val = Result == 0;
688 Result.zextOrTrunc(getIntTypeSizeInBits(E->getType()));
689 Result = Val;
690 break;
691 }
692 case UnaryOperator::Extension:
Chris Lattner15e59112008-07-12 00:38:25 +0000693 // FIXME: Should extension allow i-c-e extension expressions in its scope?
694 // If so, we could clear the diagnostic ID.
Chris Lattner400d7402008-07-11 22:15:16 +0000695 case UnaryOperator::Plus:
Chris Lattner15e59112008-07-12 00:38:25 +0000696 // The result is always just the subexpr.
Chris Lattner400d7402008-07-11 22:15:16 +0000697 break;
698 case UnaryOperator::Minus:
699 Result = -Result;
700 break;
701 case UnaryOperator::Not:
702 Result = ~Result;
703 break;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000704 }
705
706 Result.setIsUnsigned(E->getType()->isUnsignedIntegerType());
Chris Lattnera42f09a2008-07-11 19:10:17 +0000707 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000708}
709
Chris Lattnerff579ff2008-07-12 01:15:53 +0000710/// HandleCast - This is used to evaluate implicit or explicit casts where the
711/// result type is integer.
712bool IntExprEvaluator::HandleCast(SourceLocation CastLoc,
713 Expr *SubExpr, QualType DestType) {
Chris Lattner2c99c712008-07-11 19:24:49 +0000714 unsigned DestWidth = getIntTypeSizeInBits(DestType);
Anders Carlssond1aa5812008-07-08 14:35:21 +0000715
Eli Friedman7888b932008-11-12 09:44:48 +0000716 if (DestType->isBooleanType()) {
717 bool BoolResult;
718 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
719 return false;
720 Result.zextOrTrunc(DestWidth);
721 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
722 Result = BoolResult;
723 return true;
724 }
725
Anders Carlssond1aa5812008-07-08 14:35:21 +0000726 // Handle simple integer->integer casts.
727 if (SubExpr->getType()->isIntegerType()) {
Chris Lattnerff579ff2008-07-12 01:15:53 +0000728 if (!Visit(SubExpr))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000729 return false;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000730
731 // Figure out if this is a truncate, extend or noop cast.
732 // If the input is signed, do a sign extend, noop, or truncate.
Eli Friedman7888b932008-11-12 09:44:48 +0000733 Result.extOrTrunc(DestWidth);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000734 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
735 return true;
736 }
737
738 // FIXME: Clean this up!
739 if (SubExpr->getType()->isPointerType()) {
Anders Carlssond1aa5812008-07-08 14:35:21 +0000740 APValue LV;
Chris Lattner422373c2008-07-11 22:52:41 +0000741 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnera42f09a2008-07-11 19:10:17 +0000742 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000743
Anders Carlssond1aa5812008-07-08 14:35:21 +0000744 if (LV.getLValueBase())
Chris Lattnera42f09a2008-07-11 19:10:17 +0000745 return false;
Eli Friedman7888b932008-11-12 09:44:48 +0000746
Anders Carlsson8ab15c82008-07-08 16:49:00 +0000747 Result.extOrTrunc(DestWidth);
748 Result = LV.getLValueOffset();
Chris Lattnerff579ff2008-07-12 01:15:53 +0000749 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
750 return true;
Anders Carlsson02a34c32008-07-08 14:30:00 +0000751 }
Eli Friedman7888b932008-11-12 09:44:48 +0000752
Chris Lattnerff579ff2008-07-12 01:15:53 +0000753 if (!SubExpr->getType()->isRealFloatingType())
Chris Lattner438f3b12008-11-12 07:43:42 +0000754 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000755
Eli Friedman2f445492008-08-22 00:06:13 +0000756 APFloat F(0.0);
757 if (!EvaluateFloat(SubExpr, F, Info))
Chris Lattner438f3b12008-11-12 07:43:42 +0000758 return Error(CastLoc, diag::err_expr_not_constant, DestType);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000759
760 // Determine whether we are converting to unsigned or signed.
761 bool DestSigned = DestType->isSignedIntegerType();
762
763 // FIXME: Warning for overflow.
Dale Johannesen2461f612008-10-09 23:02:32 +0000764 uint64_t Space[4];
765 bool ignored;
Eli Friedman2f445492008-08-22 00:06:13 +0000766 (void)F.convertToInteger(Space, DestWidth, DestSigned,
Dale Johannesen2461f612008-10-09 23:02:32 +0000767 llvm::APFloat::rmTowardZero, &ignored);
Chris Lattnerff579ff2008-07-12 01:15:53 +0000768 Result = llvm::APInt(DestWidth, 4, Space);
769 Result.setIsUnsigned(!DestSigned);
Chris Lattnera42f09a2008-07-11 19:10:17 +0000770 return true;
Anders Carlssond1aa5812008-07-08 14:35:21 +0000771}
Anders Carlsson02a34c32008-07-08 14:30:00 +0000772
Chris Lattnera823ccf2008-07-11 18:11:29 +0000773//===----------------------------------------------------------------------===//
Eli Friedman2f445492008-08-22 00:06:13 +0000774// Float Evaluation
775//===----------------------------------------------------------------------===//
776
777namespace {
778class VISIBILITY_HIDDEN FloatExprEvaluator
779 : public StmtVisitor<FloatExprEvaluator, bool> {
780 EvalInfo &Info;
781 APFloat &Result;
782public:
783 FloatExprEvaluator(EvalInfo &info, APFloat &result)
784 : Info(info), Result(result) {}
785
786 bool VisitStmt(Stmt *S) {
787 return false;
788 }
789
790 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner87293782008-10-06 05:28:25 +0000791 bool VisitCallExpr(const CallExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000792
Daniel Dunbar804ead02008-10-16 03:51:50 +0000793 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000794 bool VisitBinaryOperator(const BinaryOperator *E);
795 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman7888b932008-11-12 09:44:48 +0000796 bool VisitCastExpr(CastExpr *E);
797 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman2f445492008-08-22 00:06:13 +0000798};
799} // end anonymous namespace
800
801static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
802 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
803}
804
Chris Lattner87293782008-10-06 05:28:25 +0000805bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Chris Lattner87293782008-10-06 05:28:25 +0000806 switch (E->isBuiltinCall()) {
Chris Lattner27cde262008-10-06 05:53:16 +0000807 default: return false;
Chris Lattner87293782008-10-06 05:28:25 +0000808 case Builtin::BI__builtin_huge_val:
809 case Builtin::BI__builtin_huge_valf:
810 case Builtin::BI__builtin_huge_vall:
811 case Builtin::BI__builtin_inf:
812 case Builtin::BI__builtin_inff:
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000813 case Builtin::BI__builtin_infl: {
814 const llvm::fltSemantics &Sem =
815 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner27cde262008-10-06 05:53:16 +0000816 Result = llvm::APFloat::getInf(Sem);
817 return true;
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000818 }
Chris Lattner667e1ee2008-10-06 06:31:58 +0000819
820 case Builtin::BI__builtin_nan:
821 case Builtin::BI__builtin_nanf:
822 case Builtin::BI__builtin_nanl:
823 // If this is __builtin_nan("") turn this into a simple nan, otherwise we
824 // can't constant fold it.
825 if (const StringLiteral *S =
826 dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts())) {
827 if (!S->isWide() && S->getByteLength() == 0) { // empty string.
Daniel Dunbar0b3efb42008-10-14 05:41:12 +0000828 const llvm::fltSemantics &Sem =
829 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner667e1ee2008-10-06 06:31:58 +0000830 Result = llvm::APFloat::getNaN(Sem);
831 return true;
832 }
833 }
834 return false;
Daniel Dunbar804ead02008-10-16 03:51:50 +0000835
836 case Builtin::BI__builtin_fabs:
837 case Builtin::BI__builtin_fabsf:
838 case Builtin::BI__builtin_fabsl:
839 if (!EvaluateFloat(E->getArg(0), Result, Info))
840 return false;
841
842 if (Result.isNegative())
843 Result.changeSign();
844 return true;
845
846 case Builtin::BI__builtin_copysign:
847 case Builtin::BI__builtin_copysignf:
848 case Builtin::BI__builtin_copysignl: {
849 APFloat RHS(0.);
850 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
851 !EvaluateFloat(E->getArg(1), RHS, Info))
852 return false;
853 Result.copySign(RHS);
854 return true;
855 }
Chris Lattner87293782008-10-06 05:28:25 +0000856 }
857}
858
Daniel Dunbar804ead02008-10-16 03:51:50 +0000859bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
860 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
861 return false;
862
863 switch (E->getOpcode()) {
864 default: return false;
865 case UnaryOperator::Plus:
866 return true;
867 case UnaryOperator::Minus:
868 Result.changeSign();
869 return true;
870 }
871}
Chris Lattner87293782008-10-06 05:28:25 +0000872
Eli Friedman2f445492008-08-22 00:06:13 +0000873bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
874 // FIXME: Diagnostics? I really don't understand how the warnings
875 // and errors are supposed to work.
Daniel Dunbar804ead02008-10-16 03:51:50 +0000876 APFloat RHS(0.0);
Eli Friedman2f445492008-08-22 00:06:13 +0000877 if (!EvaluateFloat(E->getLHS(), Result, Info))
878 return false;
879 if (!EvaluateFloat(E->getRHS(), RHS, Info))
880 return false;
881
882 switch (E->getOpcode()) {
883 default: return false;
884 case BinaryOperator::Mul:
885 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
886 return true;
887 case BinaryOperator::Add:
888 Result.add(RHS, APFloat::rmNearestTiesToEven);
889 return true;
890 case BinaryOperator::Sub:
891 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
892 return true;
893 case BinaryOperator::Div:
894 Result.divide(RHS, APFloat::rmNearestTiesToEven);
895 return true;
896 case BinaryOperator::Rem:
897 Result.mod(RHS, APFloat::rmNearestTiesToEven);
898 return true;
899 }
900}
901
902bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
903 Result = E->getValue();
904 return true;
905}
906
Eli Friedman7888b932008-11-12 09:44:48 +0000907bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
908 Expr* SubExpr = E->getSubExpr();
909 const llvm::fltSemantics& destSemantics =
910 Info.Ctx.getFloatTypeSemantics(E->getType());
911 if (SubExpr->getType()->isIntegralType()) {
912 APSInt IntResult;
913 if (!EvaluateInteger(E, IntResult, Info))
914 return false;
915 Result = APFloat(destSemantics, 1);
916 Result.convertFromAPInt(IntResult, IntResult.isSigned(),
917 APFloat::rmNearestTiesToEven);
918 return true;
919 }
920 if (SubExpr->getType()->isRealFloatingType()) {
921 if (!Visit(SubExpr))
922 return false;
923 bool ignored;
924 Result.convert(destSemantics, APFloat::rmNearestTiesToEven, &ignored);
925 return true;
926 }
927
928 return false;
929}
930
931bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
932 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
933 return true;
934}
935
Eli Friedman2f445492008-08-22 00:06:13 +0000936//===----------------------------------------------------------------------===//
Chris Lattnera823ccf2008-07-11 18:11:29 +0000937// Top level TryEvaluate.
938//===----------------------------------------------------------------------===//
939
Chris Lattner87293782008-10-06 05:28:25 +0000940/// tryEvaluate - Return true if this is a constant which we can fold using
941/// any crazy technique (that has nothing to do with language standards) that
942/// we want to. If this function returns true, it returns the folded constant
943/// in Result.
Chris Lattnera42f09a2008-07-11 19:10:17 +0000944bool Expr::tryEvaluate(APValue &Result, ASTContext &Ctx) const {
Chris Lattner422373c2008-07-11 22:52:41 +0000945 EvalInfo Info(Ctx);
Anders Carlssonc0328012008-07-08 05:49:43 +0000946 if (getType()->isIntegerType()) {
Eli Friedman2f445492008-08-22 00:06:13 +0000947 llvm::APSInt sInt(32);
Chris Lattner422373c2008-07-11 22:52:41 +0000948 if (EvaluateInteger(this, sInt, Info)) {
Anders Carlssonc0328012008-07-08 05:49:43 +0000949 Result = APValue(sInt);
950 return true;
951 }
Eli Friedman2f445492008-08-22 00:06:13 +0000952 } else if (getType()->isPointerType()) {
953 if (EvaluatePointer(this, Result, Info)) {
954 return true;
955 }
956 } else if (getType()->isRealFloatingType()) {
957 llvm::APFloat f(0.0);
958 if (EvaluateFloat(this, f, Info)) {
959 Result = APValue(f);
960 return true;
961 }
962 }
Anders Carlsson47968a92008-08-10 17:03:01 +0000963
Anders Carlssonc7436af2008-07-03 04:20:39 +0000964 return false;
965}
Chris Lattner2d9a3f62008-10-06 06:49:02 +0000966
967/// isEvaluatable - Call tryEvaluate to see if this expression can be constant
968/// folded, but discard the result.
969bool Expr::isEvaluatable(ASTContext &Ctx) const {
970 APValue V;
971 return tryEvaluate(V, Ctx);
972}