blob: 30ef6f3aec8d79fca20ed7e8a293520ca7c2f1e4 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-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"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
45struct EvalInfo {
46 ASTContext &Ctx;
Mike Stump11289f42009-09-09 15:08:12 +000047
Anders Carlssonbd1df8e2008-11-30 16:38:33 +000048 /// EvalResult - Contains information about the evaluation.
49 Expr::EvalResult &EvalResult;
Anders Carlsson58620012008-11-30 18:26:25 +000050
Eli Friedman7d45c482009-09-13 10:17:44 +000051 /// AnyLValue - Stack based LValue results are not discarded.
52 bool AnyLValue;
53
54 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult,
55 bool anylvalue = false)
56 : Ctx(ctx), EvalResult(evalresult), AnyLValue(anylvalue) {}
Chris Lattnercdf34e72008-07-11 22:52:41 +000057};
58
59
Eli Friedman9a156e52008-11-12 09:44:48 +000060static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +000061static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
62static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +000063static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
64 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +000065static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +000066static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +000067
68//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +000069// Misc utilities
70//===----------------------------------------------------------------------===//
71
Eli Friedman334046a2009-06-14 02:17:33 +000072static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
73 // FIXME: Is this accurate for all kinds of bases? If not, what would
74 // the check look like?
Ken Dyck02990832010-01-15 12:37:54 +000075 Result = Value.getLValueBase() || !Value.getLValueOffset().isZero();
Eli Friedman334046a2009-06-14 02:17:33 +000076 return true;
77}
78
John McCall1be1c632010-01-05 23:42:56 +000079static bool HandleConversionToBool(const Expr* E, bool& Result,
80 EvalInfo &Info) {
Eli Friedman9a156e52008-11-12 09:44:48 +000081 if (E->getType()->isIntegralType()) {
82 APSInt IntResult;
83 if (!EvaluateInteger(E, IntResult, Info))
84 return false;
85 Result = IntResult != 0;
86 return true;
87 } else if (E->getType()->isRealFloatingType()) {
88 APFloat FloatResult(0.0);
89 if (!EvaluateFloat(E, FloatResult, Info))
90 return false;
91 Result = !FloatResult.isZero();
92 return true;
Eli Friedman64004332009-03-23 04:38:34 +000093 } else if (E->getType()->hasPointerRepresentation()) {
Eli Friedman9a156e52008-11-12 09:44:48 +000094 APValue PointerResult;
95 if (!EvaluatePointer(E, PointerResult, Info))
96 return false;
Eli Friedman334046a2009-06-14 02:17:33 +000097 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +000098 } else if (E->getType()->isAnyComplexType()) {
99 APValue ComplexResult;
100 if (!EvaluateComplex(E, ComplexResult, Info))
101 return false;
102 if (ComplexResult.isComplexFloat()) {
103 Result = !ComplexResult.getComplexFloatReal().isZero() ||
104 !ComplexResult.getComplexFloatImag().isZero();
105 } else {
106 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
107 ComplexResult.getComplexIntImag().getBoolValue();
108 }
109 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000110 }
111
112 return false;
113}
114
Mike Stump11289f42009-09-09 15:08:12 +0000115static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000116 APFloat &Value, ASTContext &Ctx) {
117 unsigned DestWidth = Ctx.getIntWidth(DestType);
118 // Determine whether we are converting to unsigned or signed.
119 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump11289f42009-09-09 15:08:12 +0000120
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000121 // FIXME: Warning for overflow.
122 uint64_t Space[4];
123 bool ignored;
124 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
125 llvm::APFloat::rmTowardZero, &ignored);
126 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
127}
128
Mike Stump11289f42009-09-09 15:08:12 +0000129static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000130 APFloat &Value, ASTContext &Ctx) {
131 bool ignored;
132 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000133 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000134 APFloat::rmNearestTiesToEven, &ignored);
135 return Result;
136}
137
Mike Stump11289f42009-09-09 15:08:12 +0000138static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000139 APSInt &Value, ASTContext &Ctx) {
140 unsigned DestWidth = Ctx.getIntWidth(DestType);
141 APSInt Result = Value;
142 // Figure out if this is a truncate, extend or noop cast.
143 // If the input is signed, do a sign extend, noop, or truncate.
144 Result.extOrTrunc(DestWidth);
145 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
146 return Result;
147}
148
Mike Stump11289f42009-09-09 15:08:12 +0000149static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000150 APSInt &Value, ASTContext &Ctx) {
151
152 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
153 Result.convertFromAPInt(Value, Value.isSigned(),
154 APFloat::rmNearestTiesToEven);
155 return Result;
156}
157
Mike Stump876387b2009-10-27 22:09:17 +0000158namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000159class HasSideEffect
Mike Stump876387b2009-10-27 22:09:17 +0000160 : public StmtVisitor<HasSideEffect, bool> {
161 EvalInfo &Info;
162public:
163
164 HasSideEffect(EvalInfo &info) : Info(info) {}
165
166 // Unhandled nodes conservatively default to having side effects.
167 bool VisitStmt(Stmt *S) {
168 return true;
169 }
170
171 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
172 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000173 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000174 return true;
175 return false;
176 }
177 // We don't want to evaluate BlockExprs multiple times, as they generate
178 // a ton of code.
179 bool VisitBlockExpr(BlockExpr *E) { return true; }
180 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
181 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
182 { return Visit(E->getInitializer()); }
183 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
184 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
185 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
186 bool VisitStringLiteral(StringLiteral *E) { return false; }
187 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
188 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
189 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000190 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stump876387b2009-10-27 22:09:17 +0000191 bool VisitChooseExpr(ChooseExpr *E)
192 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
193 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
194 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stumpf3eb5ec2009-10-29 23:34:20 +0000195 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stumpfa502902009-10-29 20:48:09 +0000196 bool VisitBinaryOperator(BinaryOperator *E)
197 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stump876387b2009-10-27 22:09:17 +0000198 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
199 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
200 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
201 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
202 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000203 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000204 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000205 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000206 }
207 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000208
209 // Has side effects if any element does.
210 bool VisitInitListExpr(InitListExpr *E) {
211 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
212 if (Visit(E->getInit(i))) return true;
213 return false;
214 }
Mike Stump876387b2009-10-27 22:09:17 +0000215};
216
Mike Stump876387b2009-10-27 22:09:17 +0000217} // end anonymous namespace
218
Eli Friedman9a156e52008-11-12 09:44:48 +0000219//===----------------------------------------------------------------------===//
220// LValue Evaluation
221//===----------------------------------------------------------------------===//
222namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000223class LValueExprEvaluator
Eli Friedman9a156e52008-11-12 09:44:48 +0000224 : public StmtVisitor<LValueExprEvaluator, APValue> {
225 EvalInfo &Info;
226public:
Mike Stump11289f42009-09-09 15:08:12 +0000227
Eli Friedman9a156e52008-11-12 09:44:48 +0000228 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
229
230 APValue VisitStmt(Stmt *S) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000231 return APValue();
232 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000233
Eli Friedman9a156e52008-11-12 09:44:48 +0000234 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssona42ee442008-11-24 04:41:22 +0000235 APValue VisitDeclRefExpr(DeclRefExpr *E);
Ken Dyck02990832010-01-15 12:37:54 +0000236 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E); }
Eli Friedman9a156e52008-11-12 09:44:48 +0000237 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
238 APValue VisitMemberExpr(MemberExpr *E);
Ken Dyck02990832010-01-15 12:37:54 +0000239 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E); }
240 APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E); }
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000241 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000242 APValue VisitUnaryDeref(UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000243 APValue VisitUnaryExtension(const UnaryOperator *E)
244 { return Visit(E->getSubExpr()); }
245 APValue VisitChooseExpr(const ChooseExpr *E)
246 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlssonde55f642009-10-03 16:30:22 +0000247
248 APValue VisitCastExpr(CastExpr *E) {
249 switch (E->getCastKind()) {
250 default:
251 return APValue();
252
253 case CastExpr::CK_NoOp:
254 return Visit(E->getSubExpr());
255 }
256 }
Eli Friedman449fe542009-03-23 04:56:01 +0000257 // FIXME: Missing: __real__, __imag__
Eli Friedman9a156e52008-11-12 09:44:48 +0000258};
259} // end anonymous namespace
260
261static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
262 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
263 return Result.isLValue();
264}
265
Mike Stump11289f42009-09-09 15:08:12 +0000266APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000267 if (isa<FunctionDecl>(E->getDecl())) {
Ken Dyck02990832010-01-15 12:37:54 +0000268 return APValue(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000269 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman7d45c482009-09-13 10:17:44 +0000270 if (!Info.AnyLValue && !VD->hasGlobalStorage())
Eli Friedman9ab03192009-08-29 19:09:59 +0000271 return APValue();
Eli Friedman751aa72b72009-05-27 06:04:58 +0000272 if (!VD->getType()->isReferenceType())
Ken Dyck02990832010-01-15 12:37:54 +0000273 return APValue(E);
Eli Friedman9ab03192009-08-29 19:09:59 +0000274 // FIXME: Check whether VD might be overridden!
Sebastian Redl5ca79842010-02-01 20:16:42 +0000275 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregor0840cc02009-11-01 20:32:48 +0000276 return Visit(const_cast<Expr *>(Init));
Eli Friedman751aa72b72009-05-27 06:04:58 +0000277 }
278
279 return APValue();
Anders Carlssona42ee442008-11-24 04:41:22 +0000280}
281
Eli Friedman9a156e52008-11-12 09:44:48 +0000282APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Eli Friedman7d45c482009-09-13 10:17:44 +0000283 if (!Info.AnyLValue && !E->isFileScope())
284 return APValue();
Ken Dyck02990832010-01-15 12:37:54 +0000285 return APValue(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000286}
287
288APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
289 APValue result;
290 QualType Ty;
291 if (E->isArrow()) {
292 if (!EvaluatePointer(E->getBase(), result, Info))
293 return APValue();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000294 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000295 } else {
296 result = Visit(E->getBase());
297 if (result.isUninit())
298 return APValue();
299 Ty = E->getBase()->getType();
300 }
301
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000302 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000303 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000304
305 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
306 if (!FD) // FIXME: deal with other kinds of member expressions
307 return APValue();
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000308
309 if (FD->getType()->isReferenceType())
310 return APValue();
311
Eli Friedman9a156e52008-11-12 09:44:48 +0000312 // FIXME: This is linear time.
Douglas Gregor91f84212008-12-11 16:49:14 +0000313 unsigned i = 0;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000314 for (RecordDecl::field_iterator Field = RD->field_begin(),
315 FieldEnd = RD->field_end();
Douglas Gregor91f84212008-12-11 16:49:14 +0000316 Field != FieldEnd; (void)++Field, ++i) {
317 if (*Field == FD)
Eli Friedman9a156e52008-11-12 09:44:48 +0000318 break;
319 }
320
321 result.setLValue(result.getLValueBase(),
Ken Dyck02990832010-01-15 12:37:54 +0000322 result.getLValueOffset() +
323 CharUnits::fromQuantity(RL.getFieldOffset(i) / 8));
Eli Friedman9a156e52008-11-12 09:44:48 +0000324
325 return result;
326}
327
Mike Stump11289f42009-09-09 15:08:12 +0000328APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000329 APValue Result;
Mike Stump11289f42009-09-09 15:08:12 +0000330
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000331 if (!EvaluatePointer(E->getBase(), Result, Info))
332 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000333
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000334 APSInt Index;
335 if (!EvaluateInteger(E->getIdx(), Index, Info))
336 return APValue();
337
Ken Dyck40775002010-01-11 17:06:35 +0000338 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000339
Ken Dyck40775002010-01-11 17:06:35 +0000340 CharUnits Offset = Index.getSExtValue() * ElementSize;
Mike Stump11289f42009-09-09 15:08:12 +0000341 Result.setLValue(Result.getLValueBase(),
Ken Dyck02990832010-01-15 12:37:54 +0000342 Result.getLValueOffset() + Offset);
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000343 return Result;
344}
Eli Friedman9a156e52008-11-12 09:44:48 +0000345
Mike Stump11289f42009-09-09 15:08:12 +0000346APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
Eli Friedman0b8337c2009-02-20 01:57:15 +0000347 APValue Result;
348 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
349 return APValue();
350 return Result;
351}
352
Eli Friedman9a156e52008-11-12 09:44:48 +0000353//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000354// Pointer Evaluation
355//===----------------------------------------------------------------------===//
356
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000357namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000358class PointerExprEvaluator
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000359 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattnercdf34e72008-07-11 22:52:41 +0000360 EvalInfo &Info;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000361public:
Mike Stump11289f42009-09-09 15:08:12 +0000362
Chris Lattnercdf34e72008-07-11 22:52:41 +0000363 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000364
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000365 APValue VisitStmt(Stmt *S) {
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000366 return APValue();
367 }
368
369 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
370
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000371 APValue VisitBinaryOperator(const BinaryOperator *E);
Eli Friedman847a2bc2009-12-27 05:43:15 +0000372 APValue VisitCastExpr(CastExpr* E);
Eli Friedmanc2b50172009-02-22 11:46:18 +0000373 APValue VisitUnaryExtension(const UnaryOperator *E)
374 { return Visit(E->getSubExpr()); }
375 APValue VisitUnaryAddrOf(const UnaryOperator *E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000376 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
Ken Dyck02990832010-01-15 12:37:54 +0000377 { return APValue(E); }
Eli Friedman529a99b2009-01-25 01:21:06 +0000378 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
Ken Dyck02990832010-01-15 12:37:54 +0000379 { return APValue(E); }
Eli Friedmanc69d4542009-01-25 01:54:01 +0000380 APValue VisitCallExpr(CallExpr *E);
Mike Stumpa6703322009-02-19 22:01:56 +0000381 APValue VisitBlockExpr(BlockExpr *E) {
382 if (!E->hasBlockDeclRefExprs())
Ken Dyck02990832010-01-15 12:37:54 +0000383 return APValue(E);
Mike Stumpa6703322009-02-19 22:01:56 +0000384 return APValue();
385 }
Eli Friedman3ae59112009-02-23 04:23:56 +0000386 APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
Ken Dyck02990832010-01-15 12:37:54 +0000387 { return APValue((Expr*)0); }
Eli Friedman9a156e52008-11-12 09:44:48 +0000388 APValue VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000389 APValue VisitChooseExpr(ChooseExpr *E)
Sebastian Redl576fd422009-05-10 18:38:11 +0000390 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
391 APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
Ken Dyck02990832010-01-15 12:37:54 +0000392 { return APValue((Expr*)0); }
Eli Friedman449fe542009-03-23 04:56:01 +0000393 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000394};
Chris Lattner05706e882008-07-11 18:11:29 +0000395} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000396
Chris Lattnercdf34e72008-07-11 22:52:41 +0000397static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000398 assert(E->getType()->hasPointerRepresentation());
Chris Lattnercdf34e72008-07-11 22:52:41 +0000399 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattner05706e882008-07-11 18:11:29 +0000400 return Result.isLValue();
401}
402
403APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
404 if (E->getOpcode() != BinaryOperator::Add &&
405 E->getOpcode() != BinaryOperator::Sub)
406 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000407
Chris Lattner05706e882008-07-11 18:11:29 +0000408 const Expr *PExp = E->getLHS();
409 const Expr *IExp = E->getRHS();
410 if (IExp->getType()->isPointerType())
411 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattner05706e882008-07-11 18:11:29 +0000413 APValue ResultLValue;
Chris Lattnercdf34e72008-07-11 22:52:41 +0000414 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattner05706e882008-07-11 18:11:29 +0000415 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000416
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000417 llvm::APSInt AdditionalOffset;
Chris Lattnercdf34e72008-07-11 22:52:41 +0000418 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattner05706e882008-07-11 18:11:29 +0000419 return APValue();
420
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000421 // Compute the new offset in the appropriate width.
422
423 QualType PointeeType =
424 PExp->getType()->getAs<PointerType>()->getPointeeType();
425 llvm::APSInt SizeOfPointee(AdditionalOffset);
Mike Stump11289f42009-09-09 15:08:12 +0000426
Anders Carlssonef56fba2009-02-19 04:55:58 +0000427 // Explicitly handle GNU void* and function pointer arithmetic extensions.
428 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000429 SizeOfPointee = 1;
Anders Carlssonef56fba2009-02-19 04:55:58 +0000430 else
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000431 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType).getQuantity();
Eli Friedman9a156e52008-11-12 09:44:48 +0000432
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000433 llvm::APSInt Offset(AdditionalOffset);
434 Offset = ResultLValue.getLValueOffset().getQuantity();
Chris Lattner05706e882008-07-11 18:11:29 +0000435 if (E->getOpcode() == BinaryOperator::Add)
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000436 Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000437 else
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000438 Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000439
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000440 // Sign extend prior to converting back to a char unit.
441 if (Offset.getBitWidth() < 64)
442 Offset.extend(64);
443 return APValue(ResultLValue.getLValueBase(),
444 CharUnits::fromQuantity(Offset.getLimitedValue()));
Chris Lattner05706e882008-07-11 18:11:29 +0000445}
Eli Friedman9a156e52008-11-12 09:44:48 +0000446
Eli Friedmanc2b50172009-02-22 11:46:18 +0000447APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
448 APValue result;
449 if (EvaluateLValue(E->getSubExpr(), result, Info))
450 return result;
Eli Friedman9a156e52008-11-12 09:44:48 +0000451 return APValue();
452}
Mike Stump11289f42009-09-09 15:08:12 +0000453
Chris Lattner05706e882008-07-11 18:11:29 +0000454
Eli Friedman847a2bc2009-12-27 05:43:15 +0000455APValue PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
456 Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000457
Eli Friedman847a2bc2009-12-27 05:43:15 +0000458 switch (E->getCastKind()) {
459 default:
460 break;
461
462 case CastExpr::CK_Unknown: {
463 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
464
465 // Check for pointer->pointer cast
466 if (SubExpr->getType()->isPointerType() ||
467 SubExpr->getType()->isObjCObjectPointerType() ||
468 SubExpr->getType()->isNullPtrType() ||
469 SubExpr->getType()->isBlockPointerType())
470 return Visit(SubExpr);
471
472 if (SubExpr->getType()->isIntegralType()) {
473 APValue Result;
474 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
475 break;
476
477 if (Result.isInt()) {
478 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Ken Dyck02990832010-01-15 12:37:54 +0000479 return APValue(0,
480 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
Eli Friedman847a2bc2009-12-27 05:43:15 +0000481 }
482
483 // Cast is of an lvalue, no need to change value.
Chris Lattner05706e882008-07-11 18:11:29 +0000484 return Result;
Eli Friedman847a2bc2009-12-27 05:43:15 +0000485 }
486 break;
Chris Lattner05706e882008-07-11 18:11:29 +0000487 }
Mike Stump11289f42009-09-09 15:08:12 +0000488
Eli Friedman847a2bc2009-12-27 05:43:15 +0000489 case CastExpr::CK_NoOp:
490 case CastExpr::CK_BitCast:
491 case CastExpr::CK_AnyPointerToObjCPointerCast:
492 case CastExpr::CK_AnyPointerToBlockPointerCast:
493 return Visit(SubExpr);
494
495 case CastExpr::CK_IntegralToPointer: {
Daniel Dunbarce399542009-02-20 18:22:23 +0000496 APValue Result;
497 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000498 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000499
500 if (Result.isInt()) {
501 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Ken Dyck02990832010-01-15 12:37:54 +0000502 return APValue(0,
503 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
Chris Lattner05706e882008-07-11 18:11:29 +0000504 }
Mike Stump11289f42009-09-09 15:08:12 +0000505
Daniel Dunbarce399542009-02-20 18:22:23 +0000506 // Cast is of an lvalue, no need to change value.
507 return Result;
Chris Lattner05706e882008-07-11 18:11:29 +0000508 }
Eli Friedman847a2bc2009-12-27 05:43:15 +0000509 case CastExpr::CK_ArrayToPointerDecay:
510 case CastExpr::CK_FunctionToPointerDecay: {
Eli Friedman9a156e52008-11-12 09:44:48 +0000511 APValue Result;
512 if (EvaluateLValue(SubExpr, Result, Info))
513 return Result;
Eli Friedman847a2bc2009-12-27 05:43:15 +0000514 break;
515 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000516 }
517
Chris Lattner05706e882008-07-11 18:11:29 +0000518 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000519}
Chris Lattner05706e882008-07-11 18:11:29 +0000520
Eli Friedmanc69d4542009-01-25 01:54:01 +0000521APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000522 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000523 Builtin::BI__builtin___CFStringMakeConstantString ||
524 E->isBuiltinCall(Info.Ctx) ==
525 Builtin::BI__builtin___NSStringMakeConstantString)
Ken Dyck02990832010-01-15 12:37:54 +0000526 return APValue(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000527 return APValue();
528}
529
Eli Friedman9a156e52008-11-12 09:44:48 +0000530APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
531 bool BoolResult;
532 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
533 return APValue();
534
535 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
536
537 APValue Result;
538 if (EvaluatePointer(EvalExpr, Result, Info))
539 return Result;
540 return APValue();
541}
Chris Lattner05706e882008-07-11 18:11:29 +0000542
543//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000544// Vector Evaluation
545//===----------------------------------------------------------------------===//
546
547namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000548 class VectorExprEvaluator
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000549 : public StmtVisitor<VectorExprEvaluator, APValue> {
550 EvalInfo &Info;
Eli Friedman3ae59112009-02-23 04:23:56 +0000551 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000552 public:
Mike Stump11289f42009-09-09 15:08:12 +0000553
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000554 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000555
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000556 APValue VisitStmt(Stmt *S) {
557 return APValue();
558 }
Mike Stump11289f42009-09-09 15:08:12 +0000559
Eli Friedman3ae59112009-02-23 04:23:56 +0000560 APValue VisitParenExpr(ParenExpr *E)
561 { return Visit(E->getSubExpr()); }
562 APValue VisitUnaryExtension(const UnaryOperator *E)
563 { return Visit(E->getSubExpr()); }
564 APValue VisitUnaryPlus(const UnaryOperator *E)
565 { return Visit(E->getSubExpr()); }
566 APValue VisitUnaryReal(const UnaryOperator *E)
567 { return Visit(E->getSubExpr()); }
568 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
569 { return GetZeroVector(E->getType()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000570 APValue VisitCastExpr(const CastExpr* E);
571 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
572 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000573 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +0000574 APValue VisitChooseExpr(const ChooseExpr *E)
575 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman3ae59112009-02-23 04:23:56 +0000576 APValue VisitUnaryImag(const UnaryOperator *E);
577 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000578 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000579 // shufflevector, ExtVectorElementExpr
580 // (Note that these require implementing conversions
581 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000582 };
583} // end anonymous namespace
584
585static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
586 if (!E->getType()->isVectorType())
587 return false;
588 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
589 return !Result.isUninit();
590}
591
592APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000593 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000594 QualType EltTy = VTy->getElementType();
595 unsigned NElts = VTy->getNumElements();
596 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000597
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000598 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000599 QualType SETy = SE->getType();
600 APValue Result = APValue();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000601
Nate Begeman2ffd3842009-06-26 18:22:18 +0000602 // Check for vector->vector bitcast and scalar->vector splat.
603 if (SETy->isVectorType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000604 return this->Visit(const_cast<Expr*>(SE));
Nate Begeman2ffd3842009-06-26 18:22:18 +0000605 } else if (SETy->isIntegerType()) {
606 APSInt IntResult;
Daniel Dunbardf4a58e2009-07-01 20:37:45 +0000607 if (!EvaluateInteger(SE, IntResult, Info))
608 return APValue();
609 Result = APValue(IntResult);
Nate Begeman2ffd3842009-06-26 18:22:18 +0000610 } else if (SETy->isRealFloatingType()) {
611 APFloat F(0.0);
Daniel Dunbardf4a58e2009-07-01 20:37:45 +0000612 if (!EvaluateFloat(SE, F, Info))
613 return APValue();
614 Result = APValue(F);
615 } else
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000616 return APValue();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000617
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000618 // For casts of a scalar to ExtVector, convert the scalar to the element type
619 // and splat it to all elements.
620 if (E->getType()->isExtVectorType()) {
621 if (EltTy->isIntegerType() && Result.isInt())
622 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
623 Info.Ctx));
624 else if (EltTy->isIntegerType())
625 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
626 Info.Ctx));
627 else if (EltTy->isRealFloatingType() && Result.isInt())
628 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
629 Info.Ctx));
630 else if (EltTy->isRealFloatingType())
631 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
632 Info.Ctx));
633 else
634 return APValue();
635
636 // Splat and create vector APValue.
637 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
638 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000639 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000640
641 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
642 // to the vector. To construct the APValue vector initializer, bitcast the
643 // initializing value to an APInt, and shift out the bits pertaining to each
644 // element.
645 APSInt Init;
646 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump11289f42009-09-09 15:08:12 +0000647
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000648 llvm::SmallVector<APValue, 4> Elts;
649 for (unsigned i = 0; i != NElts; ++i) {
650 APSInt Tmp = Init;
651 Tmp.extOrTrunc(EltWidth);
Mike Stump11289f42009-09-09 15:08:12 +0000652
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000653 if (EltTy->isIntegerType())
654 Elts.push_back(APValue(Tmp));
655 else if (EltTy->isRealFloatingType())
656 Elts.push_back(APValue(APFloat(Tmp)));
657 else
658 return APValue();
659
660 Init >>= EltWidth;
661 }
662 return APValue(&Elts[0], Elts.size());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000663}
664
Mike Stump11289f42009-09-09 15:08:12 +0000665APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000666VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
667 return this->Visit(const_cast<Expr*>(E->getInitializer()));
668}
669
Mike Stump11289f42009-09-09 15:08:12 +0000670APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000671VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000672 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000673 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000674 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000675
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000676 QualType EltTy = VT->getElementType();
677 llvm::SmallVector<APValue, 4> Elements;
678
Eli Friedman3ae59112009-02-23 04:23:56 +0000679 for (unsigned i = 0; i < NumElements; i++) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000680 if (EltTy->isIntegerType()) {
681 llvm::APSInt sInt(32);
Eli Friedman3ae59112009-02-23 04:23:56 +0000682 if (i < NumInits) {
683 if (!EvaluateInteger(E->getInit(i), sInt, Info))
684 return APValue();
685 } else {
686 sInt = Info.Ctx.MakeIntValue(0, EltTy);
687 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000688 Elements.push_back(APValue(sInt));
689 } else {
690 llvm::APFloat f(0.0);
Eli Friedman3ae59112009-02-23 04:23:56 +0000691 if (i < NumInits) {
692 if (!EvaluateFloat(E->getInit(i), f, Info))
693 return APValue();
694 } else {
695 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
696 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000697 Elements.push_back(APValue(f));
698 }
699 }
700 return APValue(&Elements[0], Elements.size());
701}
702
Mike Stump11289f42009-09-09 15:08:12 +0000703APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000704VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000705 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000706 QualType EltTy = VT->getElementType();
707 APValue ZeroElement;
708 if (EltTy->isIntegerType())
709 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
710 else
711 ZeroElement =
712 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
713
714 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
715 return APValue(&Elements[0], Elements.size());
716}
717
718APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
719 bool BoolResult;
720 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
721 return APValue();
722
723 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
724
725 APValue Result;
726 if (EvaluateVector(EvalExpr, Result, Info))
727 return Result;
728 return APValue();
729}
730
Eli Friedman3ae59112009-02-23 04:23:56 +0000731APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
732 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
733 Info.EvalResult.HasSideEffects = true;
734 return GetZeroVector(E->getType());
735}
736
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000737//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000738// Integer Evaluation
739//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000740
741namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000742class IntExprEvaluator
Chris Lattnere13042c2008-07-11 19:10:17 +0000743 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattnercdf34e72008-07-11 22:52:41 +0000744 EvalInfo &Info;
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000745 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000746public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000747 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattnercdf34e72008-07-11 22:52:41 +0000748 : Info(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000749
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000750 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbar79e042a2009-02-21 18:14:20 +0000751 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000752 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000753 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000754 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000755 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000756 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000757 return true;
758 }
759
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000760 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbar79e042a2009-02-21 18:14:20 +0000761 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000762 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000763 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000764 Result = APValue(APSInt(I));
765 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000766 return true;
767 }
768
769 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbar79e042a2009-02-21 18:14:20 +0000770 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000771 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000772 return true;
773 }
774
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000775 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000776 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +0000777 if (Info.EvalResult.Diag == 0) {
778 Info.EvalResult.DiagLoc = L;
779 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000780 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000781 }
Chris Lattner99415702008-07-12 00:14:42 +0000782 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +0000783 }
Mike Stump11289f42009-09-09 15:08:12 +0000784
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000785 //===--------------------------------------------------------------------===//
786 // Visitor Methods
787 //===--------------------------------------------------------------------===//
Mike Stump11289f42009-09-09 15:08:12 +0000788
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000789 bool VisitStmt(Stmt *) {
790 assert(0 && "This should be called on integers, stmts are not integers");
791 return false;
792 }
Mike Stump11289f42009-09-09 15:08:12 +0000793
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000794 bool VisitExpr(Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +0000795 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000796 }
Mike Stump11289f42009-09-09 15:08:12 +0000797
Chris Lattnere13042c2008-07-11 19:10:17 +0000798 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000799
Chris Lattner7174bf32008-07-12 00:38:25 +0000800 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000801 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000802 }
803 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000804 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000805 }
806 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbard7be95d2008-10-24 08:07:57 +0000807 // Per gcc docs "this built-in function ignores top level
808 // qualifiers". We need to use the canonical version to properly
809 // be able to strip CRV qualifiers from the type.
810 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
811 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump11289f42009-09-09 15:08:12 +0000812 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000813 T1.getUnqualifiedType()),
814 E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000815 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +0000816
817 bool CheckReferencedDecl(const Expr *E, const Decl *D);
818 bool VisitDeclRefExpr(const DeclRefExpr *E) {
819 return CheckReferencedDecl(E, E->getDecl());
820 }
821 bool VisitMemberExpr(const MemberExpr *E) {
822 if (CheckReferencedDecl(E, E->getMemberDecl())) {
823 // Conservatively assume a MemberExpr will have side-effects
824 Info.EvalResult.HasSideEffects = true;
825 return true;
826 }
827 return false;
828 }
829
Eli Friedmand5c93992010-02-13 00:10:10 +0000830 bool VisitCallExpr(CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +0000831 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +0000832 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +0000833 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopes42042612008-11-16 19:28:31 +0000834 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +0000835
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000836 bool VisitCastExpr(CastExpr* E);
Sebastian Redl6f282892008-11-11 17:56:53 +0000837 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
838
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000839 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000840 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000841 }
Mike Stump11289f42009-09-09 15:08:12 +0000842
Anders Carlsson39def3a2008-12-21 22:39:40 +0000843 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000844 return Success(0, E);
Anders Carlsson39def3a2008-12-21 22:39:40 +0000845 }
Mike Stump11289f42009-09-09 15:08:12 +0000846
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000847 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000848 return Success(0, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000849 }
850
Eli Friedman4e7a2412009-02-27 04:45:43 +0000851 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
852 return Success(0, E);
853 }
854
Sebastian Redlbaad4e72009-01-05 20:52:13 +0000855 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Douglas Gregor79f83ed2009-07-23 23:49:00 +0000856 return Success(E->EvaluateTrait(Info.Ctx), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +0000857 }
858
Eli Friedman449fe542009-03-23 04:56:01 +0000859 bool VisitChooseExpr(const ChooseExpr *E) {
860 return Visit(E->getChosenSubExpr(Info.Ctx));
861 }
862
Eli Friedmana1c7b6c2009-02-28 03:59:05 +0000863 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +0000864 bool VisitUnaryImag(const UnaryOperator *E);
865
Chris Lattnerf8d7f722008-07-11 21:24:13 +0000866private:
Ken Dyck160146e2010-01-27 17:10:57 +0000867 CharUnits GetAlignOfExpr(const Expr *E);
868 CharUnits GetAlignOfType(QualType T);
Eli Friedman4e7a2412009-02-27 04:45:43 +0000869 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +0000870};
Chris Lattner05706e882008-07-11 18:11:29 +0000871} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000872
Daniel Dunbarce399542009-02-20 18:22:23 +0000873static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000874 assert(E->getType()->isIntegralType());
Daniel Dunbarce399542009-02-20 18:22:23 +0000875 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
876}
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000877
Daniel Dunbarce399542009-02-20 18:22:23 +0000878static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000879 assert(E->getType()->isIntegralType());
880
Daniel Dunbarce399542009-02-20 18:22:23 +0000881 APValue Val;
882 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
883 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000884 Result = Val.getInt();
885 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000886}
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000887
Eli Friedmanfb8a93f2009-11-24 05:28:59 +0000888bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +0000889 // Enums are integer constant exprs.
Eli Friedmanee275c82009-12-10 22:29:29 +0000890 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
891 return Success(ECD->getInitVal(), E);
Sebastian Redlc9ab3d42009-02-08 15:51:17 +0000892
893 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +0000894 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +0000895 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
896 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +0000897
898 if (isa<ParmVarDecl>(D))
899 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
900
Eli Friedmanfb8a93f2009-11-24 05:28:59 +0000901 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +0000902 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +0000903 if (APValue *V = VD->getEvaluatedValue()) {
904 if (V->isInt())
905 return Success(V->getInt(), E);
906 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
907 }
908
909 if (VD->isEvaluatingValue())
910 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
911
912 VD->setEvaluatingValue();
913
Douglas Gregor31cf12c2009-05-26 18:54:04 +0000914 if (Visit(const_cast<Expr*>(Init))) {
915 // Cache the evaluated value in the variable declaration.
Eli Friedman1d6fb162009-12-03 20:31:57 +0000916 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +0000917 return true;
918 }
919
Eli Friedman1d6fb162009-12-03 20:31:57 +0000920 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +0000921 return false;
922 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +0000923 }
924 }
925
Chris Lattner7174bf32008-07-12 00:38:25 +0000926 // Otherwise, random variable references are not constants.
Anders Carlssonb33d6c82008-11-30 18:37:00 +0000927 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner7174bf32008-07-12 00:38:25 +0000928}
929
Chris Lattner86ee2862008-10-06 06:40:35 +0000930/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
931/// as GCC.
932static int EvaluateBuiltinClassifyType(const CallExpr *E) {
933 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000934 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +0000935 enum gcc_type_class {
936 no_type_class = -1,
937 void_type_class, integer_type_class, char_type_class,
938 enumeral_type_class, boolean_type_class,
939 pointer_type_class, reference_type_class, offset_type_class,
940 real_type_class, complex_type_class,
941 function_type_class, method_type_class,
942 record_type_class, union_type_class,
943 array_type_class, string_type_class,
944 lang_type_class
945 };
Mike Stump11289f42009-09-09 15:08:12 +0000946
947 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +0000948 // ideal, however it is what gcc does.
949 if (E->getNumArgs() == 0)
950 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +0000951
Chris Lattner86ee2862008-10-06 06:40:35 +0000952 QualType ArgTy = E->getArg(0)->getType();
953 if (ArgTy->isVoidType())
954 return void_type_class;
955 else if (ArgTy->isEnumeralType())
956 return enumeral_type_class;
957 else if (ArgTy->isBooleanType())
958 return boolean_type_class;
959 else if (ArgTy->isCharType())
960 return string_type_class; // gcc doesn't appear to use char_type_class
961 else if (ArgTy->isIntegerType())
962 return integer_type_class;
963 else if (ArgTy->isPointerType())
964 return pointer_type_class;
965 else if (ArgTy->isReferenceType())
966 return reference_type_class;
967 else if (ArgTy->isRealType())
968 return real_type_class;
969 else if (ArgTy->isComplexType())
970 return complex_type_class;
971 else if (ArgTy->isFunctionType())
972 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +0000973 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +0000974 return record_type_class;
975 else if (ArgTy->isUnionType())
976 return union_type_class;
977 else if (ArgTy->isArrayType())
978 return array_type_class;
979 else if (ArgTy->isUnionType())
980 return union_type_class;
981 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
982 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
983 return -1;
984}
985
Eli Friedmand5c93992010-02-13 00:10:10 +0000986bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +0000987 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +0000988 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +0000989 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump722cedf2009-10-26 18:35:08 +0000990
991 case Builtin::BI__builtin_object_size: {
Mike Stump722cedf2009-10-26 18:35:08 +0000992 const Expr *Arg = E->getArg(0)->IgnoreParens();
993 Expr::EvalResult Base;
Eric Christopher99469702010-01-19 22:58:35 +0000994
995 // TODO: Perhaps we should let LLVM lower this?
Mike Stump5183a142009-10-26 23:05:19 +0000996 if (Arg->EvaluateAsAny(Base, Info.Ctx)
Mike Stump722cedf2009-10-26 18:35:08 +0000997 && Base.Val.getKind() == APValue::LValue
998 && !Base.HasSideEffects)
999 if (const Expr *LVBase = Base.Val.getLValueBase())
1000 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) {
1001 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Mike Stump5179f302009-10-28 21:22:24 +00001002 if (!VD->getType()->isIncompleteType()
1003 && VD->getType()->isObjectType()
1004 && !VD->getType()->isVariablyModifiedType()
1005 && !VD->getType()->isDependentType()) {
Ken Dyck40775002010-01-11 17:06:35 +00001006 CharUnits Size = Info.Ctx.getTypeSizeInChars(VD->getType());
Ken Dyck02990832010-01-15 12:37:54 +00001007 CharUnits Offset = Base.Val.getLValueOffset();
Ken Dyck40775002010-01-11 17:06:35 +00001008 if (!Offset.isNegative() && Offset <= Size)
1009 Size -= Offset;
Mike Stump5179f302009-10-28 21:22:24 +00001010 else
Ken Dyck40775002010-01-11 17:06:35 +00001011 Size = CharUnits::Zero();
1012 return Success(Size.getQuantity(), E);
Mike Stump5179f302009-10-28 21:22:24 +00001013 }
Mike Stump722cedf2009-10-26 18:35:08 +00001014 }
1015 }
1016
Eric Christopher99469702010-01-19 22:58:35 +00001017 // If evaluating the argument has side-effects we can't determine
1018 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001019 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer0128f662010-01-03 18:18:37 +00001020 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001021 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001022 return Success(0, E);
1023 }
Mike Stump876387b2009-10-27 22:09:17 +00001024
Mike Stump722cedf2009-10-26 18:35:08 +00001025 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1026 }
1027
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001028 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001029 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001030
Anders Carlsson4c76e932008-11-24 04:21:33 +00001031 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001032 // __builtin_constant_p always has one operand: it returns true if that
1033 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001034 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001035
1036 case Builtin::BI__builtin_eh_return_data_regno: {
1037 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1038 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1039 return Success(Operand, E);
1040 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001041
1042 case Builtin::BI__builtin_expect:
1043 return Visit(E->getArg(0));
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001044 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001045}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001046
Chris Lattnere13042c2008-07-11 19:10:17 +00001047bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001048 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001049 if (!Visit(E->getRHS()))
1050 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001051
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001052 // If we can't evaluate the LHS, it might have side effects;
1053 // conservatively mark it.
1054 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1055 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001056
Anders Carlsson564730a2008-12-01 02:07:06 +00001057 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001058 }
1059
1060 if (E->isLogicalOp()) {
1061 // These need to be handled specially because the operands aren't
1062 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001063 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001064
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001065 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001066 // We were able to evaluate the LHS, see if we can get away with not
1067 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001068 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001069 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001070
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001071 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001072 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001073 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001074 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001075 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001076 }
1077 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001078 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001079 // We can't evaluate the LHS; however, sometimes the result
1080 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Mike Stump11289f42009-09-09 15:08:12 +00001081 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001082 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001083 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001084 // must have had side effects.
1085 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001086
1087 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001088 }
1089 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001090 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001091
Eli Friedman5a332ea2008-11-13 06:09:17 +00001092 return false;
1093 }
1094
Anders Carlssonacc79812008-11-16 07:17:21 +00001095 QualType LHSTy = E->getLHS()->getType();
1096 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001097
1098 if (LHSTy->isAnyComplexType()) {
1099 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
1100 APValue LHS, RHS;
1101
1102 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1103 return false;
1104
1105 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1106 return false;
1107
1108 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001109 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001110 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001111 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001112 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1113
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001114 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001115 return Success((CR_r == APFloat::cmpEqual &&
1116 CR_i == APFloat::cmpEqual), E);
1117 else {
1118 assert(E->getOpcode() == BinaryOperator::NE &&
1119 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001120 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001121 CR_r == APFloat::cmpLessThan ||
1122 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001123 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001124 CR_i == APFloat::cmpLessThan ||
1125 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001126 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001127 } else {
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001128 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001129 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1130 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1131 else {
1132 assert(E->getOpcode() == BinaryOperator::NE &&
1133 "Invalid compex comparison.");
1134 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1135 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1136 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001137 }
1138 }
Mike Stump11289f42009-09-09 15:08:12 +00001139
Anders Carlssonacc79812008-11-16 07:17:21 +00001140 if (LHSTy->isRealFloatingType() &&
1141 RHSTy->isRealFloatingType()) {
1142 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001143
Anders Carlssonacc79812008-11-16 07:17:21 +00001144 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1145 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001146
Anders Carlssonacc79812008-11-16 07:17:21 +00001147 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1148 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001149
Anders Carlssonacc79812008-11-16 07:17:21 +00001150 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001151
Anders Carlssonacc79812008-11-16 07:17:21 +00001152 switch (E->getOpcode()) {
1153 default:
1154 assert(0 && "Invalid binary operator!");
1155 case BinaryOperator::LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001156 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001157 case BinaryOperator::GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001158 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001159 case BinaryOperator::LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001160 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001161 case BinaryOperator::GE:
Mike Stump11289f42009-09-09 15:08:12 +00001162 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001163 E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001164 case BinaryOperator::EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001165 return Success(CR == APFloat::cmpEqual, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001166 case BinaryOperator::NE:
Mike Stump11289f42009-09-09 15:08:12 +00001167 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001168 || CR == APFloat::cmpLessThan
1169 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001170 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001171 }
Mike Stump11289f42009-09-09 15:08:12 +00001172
Eli Friedmana38da572009-04-28 19:17:36 +00001173 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1174 if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001175 APValue LHSValue;
1176 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1177 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001178
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001179 APValue RHSValue;
1180 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1181 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001182
Eli Friedman334046a2009-06-14 02:17:33 +00001183 // Reject any bases from the normal codepath; we special-case comparisons
1184 // to null.
1185 if (LHSValue.getLValueBase()) {
1186 if (!E->isEqualityOp())
1187 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001188 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001189 return false;
1190 bool bres;
1191 if (!EvalPointerValueAsBool(LHSValue, bres))
1192 return false;
1193 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1194 } else if (RHSValue.getLValueBase()) {
1195 if (!E->isEqualityOp())
1196 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001197 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001198 return false;
1199 bool bres;
1200 if (!EvalPointerValueAsBool(RHSValue, bres))
1201 return false;
1202 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1203 }
Eli Friedman64004332009-03-23 04:38:34 +00001204
Eli Friedmana38da572009-04-28 19:17:36 +00001205 if (E->getOpcode() == BinaryOperator::Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001206 QualType Type = E->getLHS()->getType();
1207 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001208
Ken Dyck02990832010-01-15 12:37:54 +00001209 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001210 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001211 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001212
Ken Dyck02990832010-01-15 12:37:54 +00001213 CharUnits Diff = LHSValue.getLValueOffset() -
1214 RHSValue.getLValueOffset();
1215 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001216 }
1217 bool Result;
1218 if (E->getOpcode() == BinaryOperator::EQ) {
1219 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001220 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001221 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1222 }
1223 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001224 }
1225 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001226 if (!LHSTy->isIntegralType() ||
1227 !RHSTy->isIntegralType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001228 // We can't continue from here for non-integral types, and they
1229 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001230 return false;
1231 }
1232
Anders Carlsson9c181652008-07-08 14:35:21 +00001233 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001234 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001235 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001236
Eli Friedman94c25c62009-03-24 01:14:50 +00001237 APValue RHSVal;
1238 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001239 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001240
1241 // Handle cases like (unsigned long)&a + 4.
1242 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001243 CharUnits Offset = Result.getLValueOffset();
1244 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1245 RHSVal.getInt().getZExtValue());
Eli Friedman94c25c62009-03-24 01:14:50 +00001246 if (E->getOpcode() == BinaryOperator::Add)
Ken Dyck02990832010-01-15 12:37:54 +00001247 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001248 else
Ken Dyck02990832010-01-15 12:37:54 +00001249 Offset -= AdditionalOffset;
1250 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001251 return true;
1252 }
1253
1254 // Handle cases like 4 + (unsigned long)&a
1255 if (E->getOpcode() == BinaryOperator::Add &&
1256 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001257 CharUnits Offset = RHSVal.getLValueOffset();
1258 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1259 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001260 return true;
1261 }
1262
1263 // All the following cases expect both operands to be an integer
1264 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001265 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001266
Eli Friedman94c25c62009-03-24 01:14:50 +00001267 APSInt& RHS = RHSVal.getInt();
1268
Anders Carlsson9c181652008-07-08 14:35:21 +00001269 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001270 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001271 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001272 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1273 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1274 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1275 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1276 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1277 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001278 case BinaryOperator::Div:
Chris Lattner99415702008-07-12 00:14:42 +00001279 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001280 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001281 return Success(Result.getInt() / RHS, E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001282 case BinaryOperator::Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001283 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001284 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001285 return Success(Result.getInt() % RHS, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001286 case BinaryOperator::Shl: {
Chris Lattner99415702008-07-12 00:14:42 +00001287 // FIXME: Warn about out of range shift amounts!
Mike Stump11289f42009-09-09 15:08:12 +00001288 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001289 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1290 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001291 }
1292 case BinaryOperator::Shr: {
Mike Stump11289f42009-09-09 15:08:12 +00001293 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001294 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1295 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001296 }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001298 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1299 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1300 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1301 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1302 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1303 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001304 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001305}
1306
Nuno Lopes42042612008-11-16 19:28:31 +00001307bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopes527b5a62008-11-16 22:06:39 +00001308 bool Cond;
1309 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopes42042612008-11-16 19:28:31 +00001310 return false;
1311
Nuno Lopes527b5a62008-11-16 22:06:39 +00001312 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopes42042612008-11-16 19:28:31 +00001313}
1314
Ken Dyck160146e2010-01-27 17:10:57 +00001315CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001316 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1317 // the result is the size of the referenced type."
1318 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1319 // result shall be the alignment of the referenced type."
1320 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1321 T = Ref->getPointeeType();
1322
Chris Lattner24aeeab2009-01-24 21:09:06 +00001323 // Get information about the alignment.
1324 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregoref462e62009-04-30 17:32:17 +00001325
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001326 // __alignof is defined to return the preferred alignment.
Ken Dyck160146e2010-01-27 17:10:57 +00001327 return CharUnits::fromQuantity(
1328 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001329}
1330
Ken Dyck160146e2010-01-27 17:10:57 +00001331CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001332 E = E->IgnoreParens();
1333
1334 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001335 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001336 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001337 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1338 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001339
Chris Lattner68061312009-01-24 21:53:27 +00001340 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001341 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1342 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001343
Chris Lattner24aeeab2009-01-24 21:09:06 +00001344 return GetAlignOfType(E->getType());
1345}
1346
1347
Sebastian Redl6f282892008-11-11 17:56:53 +00001348/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1349/// expression's type.
1350bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001351 // Handle alignof separately.
1352 if (!E->isSizeOf()) {
1353 if (E->isArgumentType())
Ken Dyck160146e2010-01-27 17:10:57 +00001354 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001355 else
Ken Dyck160146e2010-01-27 17:10:57 +00001356 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001357 }
Eli Friedman64004332009-03-23 04:38:34 +00001358
Sebastian Redl6f282892008-11-11 17:56:53 +00001359 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001360 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1361 // the result is the size of the referenced type."
1362 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1363 // result shall be the alignment of the referenced type."
1364 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1365 SrcTy = Ref->getPointeeType();
Sebastian Redl6f282892008-11-11 17:56:53 +00001366
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001367 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1368 // extension.
1369 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1370 return Success(1, E);
Eli Friedman64004332009-03-23 04:38:34 +00001371
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001372 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattner24aeeab2009-01-24 21:09:06 +00001373 if (!SrcTy->isConstantSizeType())
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001374 return false;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001375
Chris Lattner24aeeab2009-01-24 21:09:06 +00001376 // Get information about the size.
Ken Dyck40775002010-01-11 17:06:35 +00001377 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001378}
1379
Douglas Gregor882211c2010-04-28 22:16:22 +00001380bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1381 CharUnits Result;
1382 unsigned n = E->getNumComponents();
1383 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1384 if (n == 0)
1385 return false;
1386 QualType CurrentType = E->getTypeSourceInfo()->getType();
1387 for (unsigned i = 0; i != n; ++i) {
1388 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1389 switch (ON.getKind()) {
1390 case OffsetOfExpr::OffsetOfNode::Array: {
1391 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1392 APSInt IdxResult;
1393 if (!EvaluateInteger(Idx, IdxResult, Info))
1394 return false;
1395 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1396 if (!AT)
1397 return false;
1398 CurrentType = AT->getElementType();
1399 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1400 Result += IdxResult.getSExtValue() * ElementSize;
1401 break;
1402 }
1403
1404 case OffsetOfExpr::OffsetOfNode::Field: {
1405 FieldDecl *MemberDecl = ON.getField();
1406 const RecordType *RT = CurrentType->getAs<RecordType>();
1407 if (!RT)
1408 return false;
1409 RecordDecl *RD = RT->getDecl();
1410 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1411 unsigned i = 0;
1412 // FIXME: It would be nice if we didn't have to loop here!
1413 for (RecordDecl::field_iterator Field = RD->field_begin(),
1414 FieldEnd = RD->field_end();
1415 Field != FieldEnd; (void)++Field, ++i) {
1416 if (*Field == MemberDecl)
1417 break;
1418 }
Douglas Gregord1702062010-04-29 00:18:15 +00001419 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1420 Result += CharUnits::fromQuantity(
1421 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor882211c2010-04-28 22:16:22 +00001422 CurrentType = MemberDecl->getType().getNonReferenceType();
1423 break;
1424 }
1425
1426 case OffsetOfExpr::OffsetOfNode::Identifier:
1427 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001428 return false;
1429
1430 case OffsetOfExpr::OffsetOfNode::Base: {
1431 CXXBaseSpecifier *BaseSpec = ON.getBase();
1432 if (BaseSpec->isVirtual())
1433 return false;
1434
1435 // Find the layout of the class whose base we are looking into.
1436 const RecordType *RT = CurrentType->getAs<RecordType>();
1437 if (!RT)
1438 return false;
1439 RecordDecl *RD = RT->getDecl();
1440 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1441
1442 // Find the base class itself.
1443 CurrentType = BaseSpec->getType();
1444 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1445 if (!BaseRT)
1446 return false;
1447
1448 // Add the offset to the base.
1449 Result += CharUnits::fromQuantity(
1450 RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1451 / Info.Ctx.getCharWidth());
1452 break;
1453 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001454 }
1455 }
1456 return Success(Result.getQuantity(), E);
1457}
1458
Chris Lattnere13042c2008-07-11 19:10:17 +00001459bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001460 // Special case unary operators that do not need their subexpression
1461 // evaluated. offsetof/sizeof/alignof are all special.
Eli Friedman988a16b2009-02-27 06:44:11 +00001462 if (E->isOffsetOfOp()) {
1463 // The AST for offsetof is defined in such a way that we can just
1464 // directly Evaluate it as an l-value.
1465 APValue LV;
1466 if (!EvaluateLValue(E->getSubExpr(), LV, Info))
Douglas Gregor882211c2010-04-28 22:16:22 +00001467 return false;
Eli Friedman988a16b2009-02-27 06:44:11 +00001468 if (LV.getLValueBase())
Douglas Gregor882211c2010-04-28 22:16:22 +00001469 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001470 return Success(LV.getLValueOffset().getQuantity(), E);
Eli Friedman988a16b2009-02-27 06:44:11 +00001471 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001472
Eli Friedman5a332ea2008-11-13 06:09:17 +00001473 if (E->getOpcode() == UnaryOperator::LNot) {
1474 // LNot's operand isn't necessarily an integer, so we handle it specially.
1475 bool bres;
1476 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1477 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001478 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001479 }
1480
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001481 // Only handle integral operations...
1482 if (!E->getSubExpr()->getType()->isIntegralType())
1483 return false;
1484
Chris Lattnercdf34e72008-07-11 22:52:41 +00001485 // Get the operand value into 'Result'.
1486 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001487 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001488
Chris Lattnerf09ad162008-07-11 22:15:16 +00001489 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001490 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001491 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1492 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001493 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001494 case UnaryOperator::Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001495 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1496 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001497 return true;
Chris Lattnerf09ad162008-07-11 22:15:16 +00001498 case UnaryOperator::Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001499 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001500 return true;
Chris Lattnerf09ad162008-07-11 22:15:16 +00001501 case UnaryOperator::Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001502 if (!Result.isInt()) return false;
1503 return Success(-Result.getInt(), E);
Chris Lattnerf09ad162008-07-11 22:15:16 +00001504 case UnaryOperator::Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001505 if (!Result.isInt()) return false;
1506 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001507 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001508}
Mike Stump11289f42009-09-09 15:08:12 +00001509
Chris Lattner477c4be2008-07-12 01:15:53 +00001510/// HandleCast - This is used to evaluate implicit or explicit casts where the
1511/// result type is integer.
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001512bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001513 Expr *SubExpr = E->getSubExpr();
1514 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001515 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001516
Eli Friedman9a156e52008-11-12 09:44:48 +00001517 if (DestType->isBooleanType()) {
1518 bool BoolResult;
1519 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1520 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001521 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001522 }
1523
Anders Carlsson9c181652008-07-08 14:35:21 +00001524 // Handle simple integer->integer casts.
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001525 if (SrcType->isIntegralType()) {
Chris Lattner477c4be2008-07-12 01:15:53 +00001526 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001527 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001528
Eli Friedman742421e2009-02-20 01:15:07 +00001529 if (!Result.isInt()) {
1530 // Only allow casts of lvalues if they are lossless.
1531 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1532 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001533
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001534 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001535 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001536 }
Mike Stump11289f42009-09-09 15:08:12 +00001537
Chris Lattner477c4be2008-07-12 01:15:53 +00001538 // FIXME: Clean this up!
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001539 if (SrcType->isPointerType()) {
Anders Carlsson9c181652008-07-08 14:35:21 +00001540 APValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001541 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001542 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001543
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001544 if (LV.getLValueBase()) {
1545 // Only allow based lvalue casts if they are lossless.
1546 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1547 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001548
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001549 Result = LV;
1550 return true;
1551 }
1552
Ken Dyck02990832010-01-15 12:37:54 +00001553 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1554 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001555 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001556 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001557
Eli Friedman742421e2009-02-20 01:15:07 +00001558 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1559 // This handles double-conversion cases, where there's both
1560 // an l-value promotion and an implicit conversion to int.
1561 APValue LV;
1562 if (!EvaluateLValue(SubExpr, LV, Info))
1563 return false;
1564
1565 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1566 return false;
1567
1568 Result = LV;
1569 return true;
1570 }
1571
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001572 if (SrcType->isAnyComplexType()) {
1573 APValue C;
1574 if (!EvaluateComplex(SubExpr, C, Info))
1575 return false;
1576 if (C.isComplexFloat())
1577 return Success(HandleFloatToIntCast(DestType, SrcType,
1578 C.getComplexFloatReal(), Info.Ctx),
1579 E);
1580 else
1581 return Success(HandleIntToIntCast(DestType, SrcType,
1582 C.getComplexIntReal(), Info.Ctx), E);
1583 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001584 // FIXME: Handle vectors
1585
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001586 if (!SrcType->isRealFloatingType())
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001587 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001588
Eli Friedman24c01542008-08-22 00:06:13 +00001589 APFloat F(0.0);
1590 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001591 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump11289f42009-09-09 15:08:12 +00001592
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001593 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001594}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001595
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001596bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1597 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1598 APValue LV;
1599 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1600 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1601 return Success(LV.getComplexIntReal(), E);
1602 }
1603
1604 return Visit(E->getSubExpr());
1605}
1606
Eli Friedman4e7a2412009-02-27 04:45:43 +00001607bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001608 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
1609 APValue LV;
1610 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1611 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1612 return Success(LV.getComplexIntImag(), E);
1613 }
1614
Eli Friedman4e7a2412009-02-27 04:45:43 +00001615 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1616 Info.EvalResult.HasSideEffects = true;
1617 return Success(0, E);
1618}
1619
Chris Lattner05706e882008-07-11 18:11:29 +00001620//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001621// Float Evaluation
1622//===----------------------------------------------------------------------===//
1623
1624namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001625class FloatExprEvaluator
Eli Friedman24c01542008-08-22 00:06:13 +00001626 : public StmtVisitor<FloatExprEvaluator, bool> {
1627 EvalInfo &Info;
1628 APFloat &Result;
1629public:
1630 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1631 : Info(info), Result(result) {}
1632
1633 bool VisitStmt(Stmt *S) {
1634 return false;
1635 }
1636
1637 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001638 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001639
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001640 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001641 bool VisitBinaryOperator(const BinaryOperator *E);
1642 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001643 bool VisitCastExpr(CastExpr *E);
1644 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedmanf3da3342009-12-04 02:12:53 +00001645 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001646
Eli Friedman449fe542009-03-23 04:56:01 +00001647 bool VisitChooseExpr(const ChooseExpr *E)
1648 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1649 bool VisitUnaryExtension(const UnaryOperator *E)
1650 { return Visit(E->getSubExpr()); }
1651
1652 // FIXME: Missing: __real__/__imag__, array subscript of vector,
Eli Friedmanf3da3342009-12-04 02:12:53 +00001653 // member of vector, ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001654};
1655} // end anonymous namespace
1656
1657static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001658 assert(E->getType()->isRealFloatingType());
Eli Friedman24c01542008-08-22 00:06:13 +00001659 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1660}
1661
John McCall16291492010-02-28 13:00:19 +00001662static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1663 QualType ResultTy,
1664 const Expr *Arg,
1665 bool SNaN,
1666 llvm::APFloat &Result) {
1667 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1668 if (!S) return false;
1669
1670 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1671
1672 llvm::APInt fill;
1673
1674 // Treat empty strings as if they were zero.
1675 if (S->getString().empty())
1676 fill = llvm::APInt(32, 0);
1677 else if (S->getString().getAsInteger(0, fill))
1678 return false;
1679
1680 if (SNaN)
1681 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1682 else
1683 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1684 return true;
1685}
1686
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001687bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001688 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner37346e02008-10-06 05:53:16 +00001689 default: return false;
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001690 case Builtin::BI__builtin_huge_val:
1691 case Builtin::BI__builtin_huge_valf:
1692 case Builtin::BI__builtin_huge_vall:
1693 case Builtin::BI__builtin_inf:
1694 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00001695 case Builtin::BI__builtin_infl: {
1696 const llvm::fltSemantics &Sem =
1697 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00001698 Result = llvm::APFloat::getInf(Sem);
1699 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00001700 }
Mike Stump11289f42009-09-09 15:08:12 +00001701
John McCall16291492010-02-28 13:00:19 +00001702 case Builtin::BI__builtin_nans:
1703 case Builtin::BI__builtin_nansf:
1704 case Builtin::BI__builtin_nansl:
1705 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1706 true, Result);
1707
Chris Lattner0b7282e2008-10-06 06:31:58 +00001708 case Builtin::BI__builtin_nan:
1709 case Builtin::BI__builtin_nanf:
1710 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00001711 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00001712 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00001713 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1714 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001715
1716 case Builtin::BI__builtin_fabs:
1717 case Builtin::BI__builtin_fabsf:
1718 case Builtin::BI__builtin_fabsl:
1719 if (!EvaluateFloat(E->getArg(0), Result, Info))
1720 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001721
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001722 if (Result.isNegative())
1723 Result.changeSign();
1724 return true;
1725
Mike Stump11289f42009-09-09 15:08:12 +00001726 case Builtin::BI__builtin_copysign:
1727 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001728 case Builtin::BI__builtin_copysignl: {
1729 APFloat RHS(0.);
1730 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1731 !EvaluateFloat(E->getArg(1), RHS, Info))
1732 return false;
1733 Result.copySign(RHS);
1734 return true;
1735 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001736 }
1737}
1738
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001739bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopes0e33c682008-11-19 17:44:31 +00001740 if (E->getOpcode() == UnaryOperator::Deref)
1741 return false;
1742
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001743 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1744 return false;
1745
1746 switch (E->getOpcode()) {
1747 default: return false;
Mike Stump11289f42009-09-09 15:08:12 +00001748 case UnaryOperator::Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001749 return true;
1750 case UnaryOperator::Minus:
1751 Result.changeSign();
1752 return true;
1753 }
1754}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001755
Eli Friedman24c01542008-08-22 00:06:13 +00001756bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman141fbf32009-11-16 04:25:37 +00001757 if (E->getOpcode() == BinaryOperator::Comma) {
1758 if (!EvaluateFloat(E->getRHS(), Result, Info))
1759 return false;
1760
1761 // If we can't evaluate the LHS, it might have side effects;
1762 // conservatively mark it.
1763 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1764 Info.EvalResult.HasSideEffects = true;
1765
1766 return true;
1767 }
1768
Eli Friedman24c01542008-08-22 00:06:13 +00001769 // FIXME: Diagnostics? I really don't understand how the warnings
1770 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001771 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00001772 if (!EvaluateFloat(E->getLHS(), Result, Info))
1773 return false;
1774 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1775 return false;
1776
1777 switch (E->getOpcode()) {
1778 default: return false;
1779 case BinaryOperator::Mul:
1780 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1781 return true;
1782 case BinaryOperator::Add:
1783 Result.add(RHS, APFloat::rmNearestTiesToEven);
1784 return true;
1785 case BinaryOperator::Sub:
1786 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1787 return true;
1788 case BinaryOperator::Div:
1789 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1790 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00001791 }
1792}
1793
1794bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1795 Result = E->getValue();
1796 return true;
1797}
1798
Eli Friedman9a156e52008-11-12 09:44:48 +00001799bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1800 Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00001801
Eli Friedman9a156e52008-11-12 09:44:48 +00001802 if (SubExpr->getType()->isIntegralType()) {
1803 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001804 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00001805 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001806 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001807 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00001808 return true;
1809 }
1810 if (SubExpr->getType()->isRealFloatingType()) {
1811 if (!Visit(SubExpr))
1812 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001813 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1814 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00001815 return true;
1816 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001817 // FIXME: Handle complex types
Eli Friedman9a156e52008-11-12 09:44:48 +00001818
1819 return false;
1820}
1821
1822bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1823 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1824 return true;
1825}
1826
Eli Friedmanf3da3342009-12-04 02:12:53 +00001827bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1828 bool Cond;
1829 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1830 return false;
1831
1832 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1833}
1834
Eli Friedman24c01542008-08-22 00:06:13 +00001835//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001836// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00001837//===----------------------------------------------------------------------===//
1838
1839namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001840class ComplexExprEvaluator
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001841 : public StmtVisitor<ComplexExprEvaluator, APValue> {
Anders Carlsson537969c2008-11-16 20:27:53 +00001842 EvalInfo &Info;
Mike Stump11289f42009-09-09 15:08:12 +00001843
Anders Carlsson537969c2008-11-16 20:27:53 +00001844public:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001845 ComplexExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump11289f42009-09-09 15:08:12 +00001846
Anders Carlsson537969c2008-11-16 20:27:53 +00001847 //===--------------------------------------------------------------------===//
1848 // Visitor Methods
1849 //===--------------------------------------------------------------------===//
1850
1851 APValue VisitStmt(Stmt *S) {
Anders Carlsson537969c2008-11-16 20:27:53 +00001852 return APValue();
1853 }
Mike Stump11289f42009-09-09 15:08:12 +00001854
Anders Carlsson537969c2008-11-16 20:27:53 +00001855 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
1856
1857 APValue VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001858 Expr* SubExpr = E->getSubExpr();
1859
1860 if (SubExpr->getType()->isRealFloatingType()) {
1861 APFloat Result(0.0);
1862
1863 if (!EvaluateFloat(SubExpr, Result, Info))
1864 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +00001865
1866 return APValue(APFloat(Result.getSemantics(), APFloat::fcZero, false),
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001867 Result);
1868 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001869 assert(SubExpr->getType()->isIntegerType() &&
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001870 "Unexpected imaginary literal.");
1871
1872 llvm::APSInt Result;
1873 if (!EvaluateInteger(SubExpr, Result, Info))
1874 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +00001875
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001876 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1877 Zero = 0;
1878 return APValue(Zero, Result);
1879 }
Anders Carlsson537969c2008-11-16 20:27:53 +00001880 }
1881
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001882 APValue VisitCastExpr(CastExpr *E) {
1883 Expr* SubExpr = E->getSubExpr();
John McCall9dd450b2009-09-21 23:43:11 +00001884 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001885 QualType SubType = SubExpr->getType();
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001886
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001887 if (SubType->isRealFloatingType()) {
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001888 APFloat Result(0.0);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001889
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001890 if (!EvaluateFloat(SubExpr, Result, Info))
1891 return APValue();
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001892
1893 if (EltType->isRealFloatingType()) {
1894 Result = HandleFloatToFloatCast(EltType, SubType, Result, Info.Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001895 return APValue(Result,
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001896 APFloat(Result.getSemantics(), APFloat::fcZero, false));
1897 } else {
1898 llvm::APSInt IResult;
1899 IResult = HandleFloatToIntCast(EltType, SubType, Result, Info.Ctx);
1900 llvm::APSInt Zero(IResult.getBitWidth(), !IResult.isSigned());
1901 Zero = 0;
1902 return APValue(IResult, Zero);
1903 }
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001904 } else if (SubType->isIntegerType()) {
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001905 APSInt Result;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001906
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001907 if (!EvaluateInteger(SubExpr, Result, Info))
1908 return APValue();
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001909
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001910 if (EltType->isRealFloatingType()) {
1911 APFloat FResult =
1912 HandleIntToFloatCast(EltType, SubType, Result, Info.Ctx);
Mike Stump11289f42009-09-09 15:08:12 +00001913 return APValue(FResult,
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001914 APFloat(FResult.getSemantics(), APFloat::fcZero, false));
1915 } else {
1916 Result = HandleIntToIntCast(EltType, SubType, Result, Info.Ctx);
1917 llvm::APSInt Zero(Result.getBitWidth(), !Result.isSigned());
1918 Zero = 0;
1919 return APValue(Result, Zero);
1920 }
John McCall9dd450b2009-09-21 23:43:11 +00001921 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001922 APValue Src;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001923
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001924 if (!EvaluateComplex(SubExpr, Src, Info))
1925 return APValue();
1926
1927 QualType SrcType = CT->getElementType();
1928
1929 if (Src.isComplexFloat()) {
1930 if (EltType->isRealFloatingType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001931 return APValue(HandleFloatToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001932 Src.getComplexFloatReal(),
1933 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001934 HandleFloatToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001935 Src.getComplexFloatImag(),
1936 Info.Ctx));
1937 } else {
1938 return APValue(HandleFloatToIntCast(EltType, SrcType,
1939 Src.getComplexFloatReal(),
1940 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001941 HandleFloatToIntCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001942 Src.getComplexFloatImag(),
Mike Stump11289f42009-09-09 15:08:12 +00001943 Info.Ctx));
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001944 }
1945 } else {
1946 assert(Src.isComplexInt() && "Invalid evaluate result.");
1947 if (EltType->isRealFloatingType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001948 return APValue(HandleIntToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001949 Src.getComplexIntReal(),
1950 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001951 HandleIntToFloatCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001952 Src.getComplexIntImag(),
1953 Info.Ctx));
1954 } else {
1955 return APValue(HandleIntToIntCast(EltType, SrcType,
1956 Src.getComplexIntReal(),
1957 Info.Ctx),
Mike Stump11289f42009-09-09 15:08:12 +00001958 HandleIntToIntCast(EltType, SrcType,
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001959 Src.getComplexIntImag(),
Mike Stump11289f42009-09-09 15:08:12 +00001960 Info.Ctx));
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001961 }
1962 }
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001963 }
1964
1965 // FIXME: Handle more casts.
1966 return APValue();
1967 }
Mike Stump11289f42009-09-09 15:08:12 +00001968
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001969 APValue VisitBinaryOperator(const BinaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001970 APValue VisitChooseExpr(const ChooseExpr *E)
1971 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1972 APValue VisitUnaryExtension(const UnaryOperator *E)
1973 { return Visit(E->getSubExpr()); }
1974 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001975 // conditional ?:, comma
Anders Carlsson537969c2008-11-16 20:27:53 +00001976};
1977} // end anonymous namespace
1978
Mike Stump11289f42009-09-09 15:08:12 +00001979static bool EvaluateComplex(const Expr *E, APValue &Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001980 assert(E->getType()->isAnyComplexType());
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001981 Result = ComplexExprEvaluator(Info).Visit(const_cast<Expr*>(E));
1982 assert((!Result.isComplexFloat() ||
Mike Stump11289f42009-09-09 15:08:12 +00001983 (&Result.getComplexFloatReal().getSemantics() ==
1984 &Result.getComplexFloatImag().getSemantics())) &&
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001985 "Invalid complex evaluation.");
1986 return Result.isComplexFloat() || Result.isComplexInt();
Anders Carlsson537969c2008-11-16 20:27:53 +00001987}
1988
Mike Stump11289f42009-09-09 15:08:12 +00001989APValue ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001990 APValue Result, RHS;
Mike Stump11289f42009-09-09 15:08:12 +00001991
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001992 if (!EvaluateComplex(E->getLHS(), Result, Info))
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001993 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +00001994
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001995 if (!EvaluateComplex(E->getRHS(), RHS, Info))
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00001996 return APValue();
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00001997
Daniel Dunbar0aa26062009-01-29 01:32:56 +00001998 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
1999 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002000 switch (E->getOpcode()) {
2001 default: return APValue();
2002 case BinaryOperator::Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002003 if (Result.isComplexFloat()) {
2004 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2005 APFloat::rmNearestTiesToEven);
2006 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2007 APFloat::rmNearestTiesToEven);
2008 } else {
2009 Result.getComplexIntReal() += RHS.getComplexIntReal();
2010 Result.getComplexIntImag() += RHS.getComplexIntImag();
2011 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002012 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002013 case BinaryOperator::Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002014 if (Result.isComplexFloat()) {
2015 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2016 APFloat::rmNearestTiesToEven);
2017 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2018 APFloat::rmNearestTiesToEven);
2019 } else {
2020 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2021 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2022 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002023 break;
2024 case BinaryOperator::Mul:
2025 if (Result.isComplexFloat()) {
2026 APValue LHS = Result;
2027 APFloat &LHS_r = LHS.getComplexFloatReal();
2028 APFloat &LHS_i = LHS.getComplexFloatImag();
2029 APFloat &RHS_r = RHS.getComplexFloatReal();
2030 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002031
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002032 APFloat Tmp = LHS_r;
2033 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2034 Result.getComplexFloatReal() = Tmp;
2035 Tmp = LHS_i;
2036 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2037 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2038
2039 Tmp = LHS_r;
2040 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2041 Result.getComplexFloatImag() = Tmp;
2042 Tmp = LHS_i;
2043 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2044 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2045 } else {
2046 APValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002047 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002048 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2049 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002050 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002051 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2052 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2053 }
2054 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002055 }
2056
2057 return Result;
2058}
2059
Anders Carlsson537969c2008-11-16 20:27:53 +00002060//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002061// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002062//===----------------------------------------------------------------------===//
2063
Chris Lattner67d7b922008-11-16 21:24:15 +00002064/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002065/// any crazy technique (that has nothing to do with language standards) that
2066/// we want to. If this function returns true, it returns the folded constant
2067/// in Result.
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002068bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2069 EvalInfo Info(Ctx, Result);
Anders Carlssonbd1df8e2008-11-30 16:38:33 +00002070
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002071 if (getType()->isVectorType()) {
2072 if (!EvaluateVector(this, Result.Val, Info))
2073 return false;
2074 } else if (getType()->isIntegerType()) {
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002075 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002076 return false;
Daniel Dunbar76ba41c2009-02-26 20:52:22 +00002077 } else if (getType()->hasPointerRepresentation()) {
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002078 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002079 return false;
Eli Friedman24c01542008-08-22 00:06:13 +00002080 } else if (getType()->isRealFloatingType()) {
2081 llvm::APFloat f(0.0);
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002082 if (!EvaluateFloat(this, f, Info))
2083 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002084
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002085 Result.Val = APValue(f);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002086 } else if (getType()->isAnyComplexType()) {
2087 if (!EvaluateComplex(this, Result.Val, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002088 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002089 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002090 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002091
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002092 return true;
2093}
2094
Mike Stump5183a142009-10-26 23:05:19 +00002095bool Expr::EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const {
2096 EvalInfo Info(Ctx, Result, true);
2097
2098 if (getType()->isVectorType()) {
2099 if (!EvaluateVector(this, Result.Val, Info))
2100 return false;
2101 } else if (getType()->isIntegerType()) {
2102 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
2103 return false;
2104 } else if (getType()->hasPointerRepresentation()) {
2105 if (!EvaluatePointer(this, Result.Val, Info))
2106 return false;
2107 } else if (getType()->isRealFloatingType()) {
2108 llvm::APFloat f(0.0);
2109 if (!EvaluateFloat(this, f, Info))
2110 return false;
2111
2112 Result.Val = APValue(f);
2113 } else if (getType()->isAnyComplexType()) {
2114 if (!EvaluateComplex(this, Result.Val, Info))
2115 return false;
2116 } else
2117 return false;
2118
2119 return true;
2120}
2121
John McCall1be1c632010-01-05 23:42:56 +00002122bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2123 EvalResult Scratch;
2124 EvalInfo Info(Ctx, Scratch);
2125
2126 return HandleConversionToBool(this, Result, Info);
2127}
2128
Anders Carlsson43168122009-04-10 04:54:13 +00002129bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2130 EvalInfo Info(Ctx, Result);
2131
2132 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2133}
2134
Eli Friedman7d45c482009-09-13 10:17:44 +00002135bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2136 EvalInfo Info(Ctx, Result, true);
2137
2138 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2139}
2140
Chris Lattner67d7b922008-11-16 21:24:15 +00002141/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002142/// folded, but discard the result.
2143bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002144 EvalResult Result;
2145 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002146}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002147
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002148bool Expr::HasSideEffects(ASTContext &Ctx) const {
2149 Expr::EvalResult Result;
2150 EvalInfo Info(Ctx, Result);
2151 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2152}
2153
Anders Carlsson59689ed2008-11-22 21:04:56 +00002154APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002155 EvalResult EvalResult;
2156 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbar435bbe02009-01-15 18:32:35 +00002157 Result = Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002158 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002159 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002160
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002161 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002162}
John McCall864e3962010-05-07 05:32:02 +00002163
2164/// isIntegerConstantExpr - this recursive routine will test if an expression is
2165/// an integer constant expression.
2166
2167/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2168/// comma, etc
2169///
2170/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2171/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2172/// cast+dereference.
2173
2174// CheckICE - This function does the fundamental ICE checking: the returned
2175// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2176// Note that to reduce code duplication, this helper does no evaluation
2177// itself; the caller checks whether the expression is evaluatable, and
2178// in the rare cases where CheckICE actually cares about the evaluated
2179// value, it calls into Evalute.
2180//
2181// Meanings of Val:
2182// 0: This expression is an ICE if it can be evaluated by Evaluate.
2183// 1: This expression is not an ICE, but if it isn't evaluated, it's
2184// a legal subexpression for an ICE. This return value is used to handle
2185// the comma operator in C99 mode.
2186// 2: This expression is not an ICE, and is not a legal subexpression for one.
2187
2188struct ICEDiag {
2189 unsigned Val;
2190 SourceLocation Loc;
2191
2192 public:
2193 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2194 ICEDiag() : Val(0) {}
2195};
2196
2197ICEDiag NoDiag() { return ICEDiag(); }
2198
2199static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2200 Expr::EvalResult EVResult;
2201 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2202 !EVResult.Val.isInt()) {
2203 return ICEDiag(2, E->getLocStart());
2204 }
2205 return NoDiag();
2206}
2207
2208static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2209 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2210 if (!E->getType()->isIntegralType()) {
2211 return ICEDiag(2, E->getLocStart());
2212 }
2213
2214 switch (E->getStmtClass()) {
2215#define STMT(Node, Base) case Expr::Node##Class:
2216#define EXPR(Node, Base)
2217#include "clang/AST/StmtNodes.inc"
2218 case Expr::PredefinedExprClass:
2219 case Expr::FloatingLiteralClass:
2220 case Expr::ImaginaryLiteralClass:
2221 case Expr::StringLiteralClass:
2222 case Expr::ArraySubscriptExprClass:
2223 case Expr::MemberExprClass:
2224 case Expr::CompoundAssignOperatorClass:
2225 case Expr::CompoundLiteralExprClass:
2226 case Expr::ExtVectorElementExprClass:
2227 case Expr::InitListExprClass:
2228 case Expr::DesignatedInitExprClass:
2229 case Expr::ImplicitValueInitExprClass:
2230 case Expr::ParenListExprClass:
2231 case Expr::VAArgExprClass:
2232 case Expr::AddrLabelExprClass:
2233 case Expr::StmtExprClass:
2234 case Expr::CXXMemberCallExprClass:
2235 case Expr::CXXDynamicCastExprClass:
2236 case Expr::CXXTypeidExprClass:
2237 case Expr::CXXNullPtrLiteralExprClass:
2238 case Expr::CXXThisExprClass:
2239 case Expr::CXXThrowExprClass:
2240 case Expr::CXXNewExprClass:
2241 case Expr::CXXDeleteExprClass:
2242 case Expr::CXXPseudoDestructorExprClass:
2243 case Expr::UnresolvedLookupExprClass:
2244 case Expr::DependentScopeDeclRefExprClass:
2245 case Expr::CXXConstructExprClass:
2246 case Expr::CXXBindTemporaryExprClass:
2247 case Expr::CXXBindReferenceExprClass:
2248 case Expr::CXXExprWithTemporariesClass:
2249 case Expr::CXXTemporaryObjectExprClass:
2250 case Expr::CXXUnresolvedConstructExprClass:
2251 case Expr::CXXDependentScopeMemberExprClass:
2252 case Expr::UnresolvedMemberExprClass:
2253 case Expr::ObjCStringLiteralClass:
2254 case Expr::ObjCEncodeExprClass:
2255 case Expr::ObjCMessageExprClass:
2256 case Expr::ObjCSelectorExprClass:
2257 case Expr::ObjCProtocolExprClass:
2258 case Expr::ObjCIvarRefExprClass:
2259 case Expr::ObjCPropertyRefExprClass:
2260 case Expr::ObjCImplicitSetterGetterRefExprClass:
2261 case Expr::ObjCSuperExprClass:
2262 case Expr::ObjCIsaExprClass:
2263 case Expr::ShuffleVectorExprClass:
2264 case Expr::BlockExprClass:
2265 case Expr::BlockDeclRefExprClass:
2266 case Expr::NoStmtClass:
2267 return ICEDiag(2, E->getLocStart());
2268
2269 case Expr::GNUNullExprClass:
2270 // GCC considers the GNU __null value to be an integral constant expression.
2271 return NoDiag();
2272
2273 case Expr::ParenExprClass:
2274 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2275 case Expr::IntegerLiteralClass:
2276 case Expr::CharacterLiteralClass:
2277 case Expr::CXXBoolLiteralExprClass:
2278 case Expr::CXXZeroInitValueExprClass:
2279 case Expr::TypesCompatibleExprClass:
2280 case Expr::UnaryTypeTraitExprClass:
2281 return NoDiag();
2282 case Expr::CallExprClass:
2283 case Expr::CXXOperatorCallExprClass: {
2284 const CallExpr *CE = cast<CallExpr>(E);
2285 if (CE->isBuiltinCall(Ctx))
2286 return CheckEvalInICE(E, Ctx);
2287 return ICEDiag(2, E->getLocStart());
2288 }
2289 case Expr::DeclRefExprClass:
2290 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2291 return NoDiag();
2292 if (Ctx.getLangOptions().CPlusPlus &&
2293 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2294 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2295
2296 // Parameter variables are never constants. Without this check,
2297 // getAnyInitializer() can find a default argument, which leads
2298 // to chaos.
2299 if (isa<ParmVarDecl>(D))
2300 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2301
2302 // C++ 7.1.5.1p2
2303 // A variable of non-volatile const-qualified integral or enumeration
2304 // type initialized by an ICE can be used in ICEs.
2305 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2306 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2307 if (Quals.hasVolatile() || !Quals.hasConst())
2308 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2309
2310 // Look for a declaration of this variable that has an initializer.
2311 const VarDecl *ID = 0;
2312 const Expr *Init = Dcl->getAnyInitializer(ID);
2313 if (Init) {
2314 if (ID->isInitKnownICE()) {
2315 // We have already checked whether this subexpression is an
2316 // integral constant expression.
2317 if (ID->isInitICE())
2318 return NoDiag();
2319 else
2320 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2321 }
2322
2323 // It's an ICE whether or not the definition we found is
2324 // out-of-line. See DR 721 and the discussion in Clang PR
2325 // 6206 for details.
2326
2327 if (Dcl->isCheckingICE()) {
2328 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2329 }
2330
2331 Dcl->setCheckingICE();
2332 ICEDiag Result = CheckICE(Init, Ctx);
2333 // Cache the result of the ICE test.
2334 Dcl->setInitKnownICE(Result.Val == 0);
2335 return Result;
2336 }
2337 }
2338 }
2339 return ICEDiag(2, E->getLocStart());
2340 case Expr::UnaryOperatorClass: {
2341 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2342 switch (Exp->getOpcode()) {
2343 case UnaryOperator::PostInc:
2344 case UnaryOperator::PostDec:
2345 case UnaryOperator::PreInc:
2346 case UnaryOperator::PreDec:
2347 case UnaryOperator::AddrOf:
2348 case UnaryOperator::Deref:
2349 return ICEDiag(2, E->getLocStart());
2350 case UnaryOperator::Extension:
2351 case UnaryOperator::LNot:
2352 case UnaryOperator::Plus:
2353 case UnaryOperator::Minus:
2354 case UnaryOperator::Not:
2355 case UnaryOperator::Real:
2356 case UnaryOperator::Imag:
2357 return CheckICE(Exp->getSubExpr(), Ctx);
2358 case UnaryOperator::OffsetOf:
2359 break;
2360 }
2361
2362 // OffsetOf falls through here.
2363 }
2364 case Expr::OffsetOfExprClass: {
2365 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2366 // Evaluate matches the proposed gcc behavior for cases like
2367 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2368 // compliance: we should warn earlier for offsetof expressions with
2369 // array subscripts that aren't ICEs, and if the array subscripts
2370 // are ICEs, the value of the offsetof must be an integer constant.
2371 return CheckEvalInICE(E, Ctx);
2372 }
2373 case Expr::SizeOfAlignOfExprClass: {
2374 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2375 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2376 return ICEDiag(2, E->getLocStart());
2377 return NoDiag();
2378 }
2379 case Expr::BinaryOperatorClass: {
2380 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2381 switch (Exp->getOpcode()) {
2382 case BinaryOperator::PtrMemD:
2383 case BinaryOperator::PtrMemI:
2384 case BinaryOperator::Assign:
2385 case BinaryOperator::MulAssign:
2386 case BinaryOperator::DivAssign:
2387 case BinaryOperator::RemAssign:
2388 case BinaryOperator::AddAssign:
2389 case BinaryOperator::SubAssign:
2390 case BinaryOperator::ShlAssign:
2391 case BinaryOperator::ShrAssign:
2392 case BinaryOperator::AndAssign:
2393 case BinaryOperator::XorAssign:
2394 case BinaryOperator::OrAssign:
2395 return ICEDiag(2, E->getLocStart());
2396
2397 case BinaryOperator::Mul:
2398 case BinaryOperator::Div:
2399 case BinaryOperator::Rem:
2400 case BinaryOperator::Add:
2401 case BinaryOperator::Sub:
2402 case BinaryOperator::Shl:
2403 case BinaryOperator::Shr:
2404 case BinaryOperator::LT:
2405 case BinaryOperator::GT:
2406 case BinaryOperator::LE:
2407 case BinaryOperator::GE:
2408 case BinaryOperator::EQ:
2409 case BinaryOperator::NE:
2410 case BinaryOperator::And:
2411 case BinaryOperator::Xor:
2412 case BinaryOperator::Or:
2413 case BinaryOperator::Comma: {
2414 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2415 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2416 if (Exp->getOpcode() == BinaryOperator::Div ||
2417 Exp->getOpcode() == BinaryOperator::Rem) {
2418 // Evaluate gives an error for undefined Div/Rem, so make sure
2419 // we don't evaluate one.
2420 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2421 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2422 if (REval == 0)
2423 return ICEDiag(1, E->getLocStart());
2424 if (REval.isSigned() && REval.isAllOnesValue()) {
2425 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2426 if (LEval.isMinSignedValue())
2427 return ICEDiag(1, E->getLocStart());
2428 }
2429 }
2430 }
2431 if (Exp->getOpcode() == BinaryOperator::Comma) {
2432 if (Ctx.getLangOptions().C99) {
2433 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2434 // if it isn't evaluated.
2435 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2436 return ICEDiag(1, E->getLocStart());
2437 } else {
2438 // In both C89 and C++, commas in ICEs are illegal.
2439 return ICEDiag(2, E->getLocStart());
2440 }
2441 }
2442 if (LHSResult.Val >= RHSResult.Val)
2443 return LHSResult;
2444 return RHSResult;
2445 }
2446 case BinaryOperator::LAnd:
2447 case BinaryOperator::LOr: {
2448 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2449 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2450 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2451 // Rare case where the RHS has a comma "side-effect"; we need
2452 // to actually check the condition to see whether the side
2453 // with the comma is evaluated.
2454 if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
2455 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2456 return RHSResult;
2457 return NoDiag();
2458 }
2459
2460 if (LHSResult.Val >= RHSResult.Val)
2461 return LHSResult;
2462 return RHSResult;
2463 }
2464 }
2465 }
2466 case Expr::ImplicitCastExprClass:
2467 case Expr::CStyleCastExprClass:
2468 case Expr::CXXFunctionalCastExprClass:
2469 case Expr::CXXStaticCastExprClass:
2470 case Expr::CXXReinterpretCastExprClass:
2471 case Expr::CXXConstCastExprClass: {
2472 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2473 if (SubExpr->getType()->isIntegralType())
2474 return CheckICE(SubExpr, Ctx);
2475 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2476 return NoDiag();
2477 return ICEDiag(2, E->getLocStart());
2478 }
2479 case Expr::ConditionalOperatorClass: {
2480 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2481 // If the condition (ignoring parens) is a __builtin_constant_p call,
2482 // then only the true side is actually considered in an integer constant
2483 // expression, and it is fully evaluated. This is an important GNU
2484 // extension. See GCC PR38377 for discussion.
2485 if (const CallExpr *CallCE
2486 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2487 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2488 Expr::EvalResult EVResult;
2489 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2490 !EVResult.Val.isInt()) {
2491 return ICEDiag(2, E->getLocStart());
2492 }
2493 return NoDiag();
2494 }
2495 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2496 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2497 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2498 if (CondResult.Val == 2)
2499 return CondResult;
2500 if (TrueResult.Val == 2)
2501 return TrueResult;
2502 if (FalseResult.Val == 2)
2503 return FalseResult;
2504 if (CondResult.Val == 1)
2505 return CondResult;
2506 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2507 return NoDiag();
2508 // Rare case where the diagnostics depend on which side is evaluated
2509 // Note that if we get here, CondResult is 0, and at least one of
2510 // TrueResult and FalseResult is non-zero.
2511 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2512 return FalseResult;
2513 }
2514 return TrueResult;
2515 }
2516 case Expr::CXXDefaultArgExprClass:
2517 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2518 case Expr::ChooseExprClass: {
2519 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2520 }
2521 }
2522
2523 // Silence a GCC warning
2524 return ICEDiag(2, E->getLocStart());
2525}
2526
2527bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2528 SourceLocation *Loc, bool isEvaluated) const {
2529 ICEDiag d = CheckICE(this, Ctx);
2530 if (d.Val != 0) {
2531 if (Loc) *Loc = d.Loc;
2532 return false;
2533 }
2534 EvalResult EvalResult;
2535 if (!Evaluate(EvalResult, Ctx))
2536 llvm_unreachable("ICE cannot be evaluated!");
2537 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2538 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2539 Result = EvalResult.Val.getInt();
2540 return true;
2541}