blob: cea1455d0d8f3fea0e83a1ead428f694772b0e6d [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-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 Stump1eb44332009-09-09 15:08:12 +000047
Anders Carlsson54da0492008-11-30 16:38:33 +000048 /// EvalResult - Contains information about the evaluation.
49 Expr::EvalResult &EvalResult;
Anders Carlssonf0c1e4b2008-11-30 18:26:25 +000050
Eli Friedmanb2f295c2009-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 Lattner87eae5e2008-07-11 22:52:41 +000057};
58
John McCallf4cf1a12010-05-07 17:22:02 +000059namespace {
60 struct ComplexValue {
61 private:
62 bool IsInt;
63
64 public:
65 APSInt IntReal, IntImag;
66 APFloat FloatReal, FloatImag;
67
68 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
69
70 void makeComplexFloat() { IsInt = false; }
71 bool isComplexFloat() const { return !IsInt; }
72 APFloat &getComplexFloatReal() { return FloatReal; }
73 APFloat &getComplexFloatImag() { return FloatImag; }
74
75 void makeComplexInt() { IsInt = true; }
76 bool isComplexInt() const { return IsInt; }
77 APSInt &getComplexIntReal() { return IntReal; }
78 APSInt &getComplexIntImag() { return IntImag; }
79
80 void moveInto(APValue &v) {
81 if (isComplexFloat())
82 v = APValue(FloatReal, FloatImag);
83 else
84 v = APValue(IntReal, IntImag);
85 }
86 };
87}
Chris Lattner87eae5e2008-07-11 22:52:41 +000088
Eli Friedman4efaa272008-11-12 09:44:48 +000089static bool EvaluateLValue(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +000090static bool EvaluatePointer(const Expr *E, APValue &Result, EvalInfo &Info);
91static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +000092static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
93 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000094static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +000095static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +000096
97//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +000098// Misc utilities
99//===----------------------------------------------------------------------===//
100
Eli Friedman5bc86102009-06-14 02:17:33 +0000101static bool EvalPointerValueAsBool(APValue& Value, bool& Result) {
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000102 const Expr* Base = Value.getLValueBase();
103
104 Result = Base || !Value.getLValueOffset().isZero();
105
106 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
107 if (!DeclRef)
108 return true;
109
110 const ValueDecl* Decl = DeclRef->getDecl();
111 if (Decl->hasAttr<WeakAttr>() ||
112 Decl->hasAttr<WeakRefAttr>() ||
113 Decl->hasAttr<WeakImportAttr>())
114 return false;
115
Eli Friedman5bc86102009-06-14 02:17:33 +0000116 return true;
117}
118
John McCallcd7a4452010-01-05 23:42:56 +0000119static bool HandleConversionToBool(const Expr* E, bool& Result,
120 EvalInfo &Info) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000121 if (E->getType()->isIntegralType()) {
122 APSInt IntResult;
123 if (!EvaluateInteger(E, IntResult, Info))
124 return false;
125 Result = IntResult != 0;
126 return true;
127 } else if (E->getType()->isRealFloatingType()) {
128 APFloat FloatResult(0.0);
129 if (!EvaluateFloat(E, FloatResult, Info))
130 return false;
131 Result = !FloatResult.isZero();
132 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000133 } else if (E->getType()->hasPointerRepresentation()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000134 APValue PointerResult;
135 if (!EvaluatePointer(E, PointerResult, Info))
136 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000137 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000138 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000139 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000140 if (!EvaluateComplex(E, ComplexResult, Info))
141 return false;
142 if (ComplexResult.isComplexFloat()) {
143 Result = !ComplexResult.getComplexFloatReal().isZero() ||
144 !ComplexResult.getComplexFloatImag().isZero();
145 } else {
146 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
147 ComplexResult.getComplexIntImag().getBoolValue();
148 }
149 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000150 }
151
152 return false;
153}
154
Mike Stump1eb44332009-09-09 15:08:12 +0000155static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000156 APFloat &Value, ASTContext &Ctx) {
157 unsigned DestWidth = Ctx.getIntWidth(DestType);
158 // Determine whether we are converting to unsigned or signed.
159 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000160
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000161 // FIXME: Warning for overflow.
162 uint64_t Space[4];
163 bool ignored;
164 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
165 llvm::APFloat::rmTowardZero, &ignored);
166 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
167}
168
Mike Stump1eb44332009-09-09 15:08:12 +0000169static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000170 APFloat &Value, ASTContext &Ctx) {
171 bool ignored;
172 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000173 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000174 APFloat::rmNearestTiesToEven, &ignored);
175 return Result;
176}
177
Mike Stump1eb44332009-09-09 15:08:12 +0000178static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000179 APSInt &Value, ASTContext &Ctx) {
180 unsigned DestWidth = Ctx.getIntWidth(DestType);
181 APSInt Result = Value;
182 // Figure out if this is a truncate, extend or noop cast.
183 // If the input is signed, do a sign extend, noop, or truncate.
184 Result.extOrTrunc(DestWidth);
185 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
186 return Result;
187}
188
Mike Stump1eb44332009-09-09 15:08:12 +0000189static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000190 APSInt &Value, ASTContext &Ctx) {
191
192 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
193 Result.convertFromAPInt(Value, Value.isSigned(),
194 APFloat::rmNearestTiesToEven);
195 return Result;
196}
197
Mike Stumpc4c90452009-10-27 22:09:17 +0000198namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000199class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000200 : public StmtVisitor<HasSideEffect, bool> {
201 EvalInfo &Info;
202public:
203
204 HasSideEffect(EvalInfo &info) : Info(info) {}
205
206 // Unhandled nodes conservatively default to having side effects.
207 bool VisitStmt(Stmt *S) {
208 return true;
209 }
210
211 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
212 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000213 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000214 return true;
215 return false;
216 }
217 // We don't want to evaluate BlockExprs multiple times, as they generate
218 // a ton of code.
219 bool VisitBlockExpr(BlockExpr *E) { return true; }
220 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
221 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
222 { return Visit(E->getInitializer()); }
223 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
224 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
225 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
226 bool VisitStringLiteral(StringLiteral *E) { return false; }
227 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
228 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
229 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000230 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000231 bool VisitChooseExpr(ChooseExpr *E)
232 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
233 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
234 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000235 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000236 bool VisitBinaryOperator(BinaryOperator *E)
237 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000238 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
239 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
240 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
241 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
242 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000243 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000244 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000245 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000246 }
247 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000248
249 // Has side effects if any element does.
250 bool VisitInitListExpr(InitListExpr *E) {
251 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
252 if (Visit(E->getInit(i))) return true;
253 return false;
254 }
Mike Stumpc4c90452009-10-27 22:09:17 +0000255};
256
Mike Stumpc4c90452009-10-27 22:09:17 +0000257} // end anonymous namespace
258
Eli Friedman4efaa272008-11-12 09:44:48 +0000259//===----------------------------------------------------------------------===//
260// LValue Evaluation
261//===----------------------------------------------------------------------===//
262namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000263class LValueExprEvaluator
Eli Friedman4efaa272008-11-12 09:44:48 +0000264 : public StmtVisitor<LValueExprEvaluator, APValue> {
265 EvalInfo &Info;
266public:
Mike Stump1eb44332009-09-09 15:08:12 +0000267
Eli Friedman4efaa272008-11-12 09:44:48 +0000268 LValueExprEvaluator(EvalInfo &info) : Info(info) {}
269
270 APValue VisitStmt(Stmt *S) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000271 return APValue();
272 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000273
Eli Friedman4efaa272008-11-12 09:44:48 +0000274 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson35873c42008-11-24 04:41:22 +0000275 APValue VisitDeclRefExpr(DeclRefExpr *E);
Ken Dycka7305832010-01-15 12:37:54 +0000276 APValue VisitPredefinedExpr(PredefinedExpr *E) { return APValue(E); }
Eli Friedman4efaa272008-11-12 09:44:48 +0000277 APValue VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
278 APValue VisitMemberExpr(MemberExpr *E);
Ken Dycka7305832010-01-15 12:37:54 +0000279 APValue VisitStringLiteral(StringLiteral *E) { return APValue(E); }
280 APValue VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return APValue(E); }
Anders Carlsson3068d112008-11-16 19:01:22 +0000281 APValue VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmane8761c82009-02-20 01:57:15 +0000282 APValue VisitUnaryDeref(UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000283 APValue VisitUnaryExtension(const UnaryOperator *E)
284 { return Visit(E->getSubExpr()); }
285 APValue VisitChooseExpr(const ChooseExpr *E)
286 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000287
288 APValue VisitCastExpr(CastExpr *E) {
289 switch (E->getCastKind()) {
290 default:
291 return APValue();
292
293 case CastExpr::CK_NoOp:
294 return Visit(E->getSubExpr());
295 }
296 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000297 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000298};
299} // end anonymous namespace
300
301static bool EvaluateLValue(const Expr* E, APValue& Result, EvalInfo &Info) {
302 Result = LValueExprEvaluator(Info).Visit(const_cast<Expr*>(E));
303 return Result.isLValue();
304}
305
Mike Stump1eb44332009-09-09 15:08:12 +0000306APValue LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000307 if (isa<FunctionDecl>(E->getDecl())) {
Ken Dycka7305832010-01-15 12:37:54 +0000308 return APValue(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000309 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedmanb2f295c2009-09-13 10:17:44 +0000310 if (!Info.AnyLValue && !VD->hasGlobalStorage())
Eli Friedmand933a012009-08-29 19:09:59 +0000311 return APValue();
Eli Friedman50c39ea2009-05-27 06:04:58 +0000312 if (!VD->getType()->isReferenceType())
Ken Dycka7305832010-01-15 12:37:54 +0000313 return APValue(E);
Eli Friedmand933a012009-08-29 19:09:59 +0000314 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000315 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000316 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000317 }
318
319 return APValue();
Anders Carlsson35873c42008-11-24 04:41:22 +0000320}
321
Eli Friedman4efaa272008-11-12 09:44:48 +0000322APValue LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Eli Friedmanb2f295c2009-09-13 10:17:44 +0000323 if (!Info.AnyLValue && !E->isFileScope())
324 return APValue();
Ken Dycka7305832010-01-15 12:37:54 +0000325 return APValue(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000326}
327
328APValue LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
329 APValue result;
330 QualType Ty;
331 if (E->isArrow()) {
332 if (!EvaluatePointer(E->getBase(), result, Info))
333 return APValue();
Ted Kremenek6217b802009-07-29 21:53:49 +0000334 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000335 } else {
336 result = Visit(E->getBase());
337 if (result.isUninit())
338 return APValue();
339 Ty = E->getBase()->getType();
340 }
341
Ted Kremenek6217b802009-07-29 21:53:49 +0000342 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000343 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000344
345 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
346 if (!FD) // FIXME: deal with other kinds of member expressions
347 return APValue();
Eli Friedman2be58612009-05-30 21:09:44 +0000348
349 if (FD->getType()->isReferenceType())
350 return APValue();
351
Eli Friedman4efaa272008-11-12 09:44:48 +0000352 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000353 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000354 for (RecordDecl::field_iterator Field = RD->field_begin(),
355 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000356 Field != FieldEnd; (void)++Field, ++i) {
357 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000358 break;
359 }
360
361 result.setLValue(result.getLValueBase(),
Ken Dycka7305832010-01-15 12:37:54 +0000362 result.getLValueOffset() +
363 CharUnits::fromQuantity(RL.getFieldOffset(i) / 8));
Eli Friedman4efaa272008-11-12 09:44:48 +0000364
365 return result;
366}
367
Mike Stump1eb44332009-09-09 15:08:12 +0000368APValue LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000369 APValue Result;
Mike Stump1eb44332009-09-09 15:08:12 +0000370
Anders Carlsson3068d112008-11-16 19:01:22 +0000371 if (!EvaluatePointer(E->getBase(), Result, Info))
372 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Anders Carlsson3068d112008-11-16 19:01:22 +0000374 APSInt Index;
375 if (!EvaluateInteger(E->getIdx(), Index, Info))
376 return APValue();
377
Ken Dyck199c3d62010-01-11 17:06:35 +0000378 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
Anders Carlsson3068d112008-11-16 19:01:22 +0000379
Ken Dyck199c3d62010-01-11 17:06:35 +0000380 CharUnits Offset = Index.getSExtValue() * ElementSize;
Mike Stump1eb44332009-09-09 15:08:12 +0000381 Result.setLValue(Result.getLValueBase(),
Ken Dycka7305832010-01-15 12:37:54 +0000382 Result.getLValueOffset() + Offset);
Anders Carlsson3068d112008-11-16 19:01:22 +0000383 return Result;
384}
Eli Friedman4efaa272008-11-12 09:44:48 +0000385
Mike Stump1eb44332009-09-09 15:08:12 +0000386APValue LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
Eli Friedmane8761c82009-02-20 01:57:15 +0000387 APValue Result;
388 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
389 return APValue();
390 return Result;
391}
392
Eli Friedman4efaa272008-11-12 09:44:48 +0000393//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000394// Pointer Evaluation
395//===----------------------------------------------------------------------===//
396
Anders Carlssonc754aa62008-07-08 05:13:58 +0000397namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000398class PointerExprEvaluator
Anders Carlsson2bad1682008-07-08 14:30:00 +0000399 : public StmtVisitor<PointerExprEvaluator, APValue> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000400 EvalInfo &Info;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000401public:
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Chris Lattner87eae5e2008-07-11 22:52:41 +0000403 PointerExprEvaluator(EvalInfo &info) : Info(info) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000404
Anders Carlsson2bad1682008-07-08 14:30:00 +0000405 APValue VisitStmt(Stmt *S) {
Anders Carlsson2bad1682008-07-08 14:30:00 +0000406 return APValue();
407 }
408
409 APValue VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
410
Anders Carlsson650c92f2008-07-08 15:34:11 +0000411 APValue VisitBinaryOperator(const BinaryOperator *E);
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000412 APValue VisitCastExpr(CastExpr* E);
Eli Friedman2217c872009-02-22 11:46:18 +0000413 APValue VisitUnaryExtension(const UnaryOperator *E)
414 { return Visit(E->getSubExpr()); }
415 APValue VisitUnaryAddrOf(const UnaryOperator *E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000416 APValue VisitObjCStringLiteral(ObjCStringLiteral *E)
Ken Dycka7305832010-01-15 12:37:54 +0000417 { return APValue(E); }
Eli Friedmanf0115892009-01-25 01:21:06 +0000418 APValue VisitAddrLabelExpr(AddrLabelExpr *E)
Ken Dycka7305832010-01-15 12:37:54 +0000419 { return APValue(E); }
Eli Friedman3941b182009-01-25 01:54:01 +0000420 APValue VisitCallExpr(CallExpr *E);
Mike Stumpb83d2872009-02-19 22:01:56 +0000421 APValue VisitBlockExpr(BlockExpr *E) {
422 if (!E->hasBlockDeclRefExprs())
Ken Dycka7305832010-01-15 12:37:54 +0000423 return APValue(E);
Mike Stumpb83d2872009-02-19 22:01:56 +0000424 return APValue();
425 }
Eli Friedman91110ee2009-02-23 04:23:56 +0000426 APValue VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
Ken Dycka7305832010-01-15 12:37:54 +0000427 { return APValue((Expr*)0); }
Eli Friedman4efaa272008-11-12 09:44:48 +0000428 APValue VisitConditionalOperator(ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000429 APValue VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000430 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
431 APValue VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
Ken Dycka7305832010-01-15 12:37:54 +0000432 { return APValue((Expr*)0); }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000433 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000434};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000435} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000436
Chris Lattner87eae5e2008-07-11 22:52:41 +0000437static bool EvaluatePointer(const Expr* E, APValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000438 assert(E->getType()->hasPointerRepresentation());
Chris Lattner87eae5e2008-07-11 22:52:41 +0000439 Result = PointerExprEvaluator(Info).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000440 return Result.isLValue();
441}
442
443APValue PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
444 if (E->getOpcode() != BinaryOperator::Add &&
445 E->getOpcode() != BinaryOperator::Sub)
446 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000448 const Expr *PExp = E->getLHS();
449 const Expr *IExp = E->getRHS();
450 if (IExp->getType()->isPointerType())
451 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000453 APValue ResultLValue;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000454 if (!EvaluatePointer(PExp, ResultLValue, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000455 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000457 llvm::APSInt AdditionalOffset;
Chris Lattner87eae5e2008-07-11 22:52:41 +0000458 if (!EvaluateInteger(IExp, AdditionalOffset, Info))
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000459 return APValue();
460
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000461 // Compute the new offset in the appropriate width.
462
463 QualType PointeeType =
464 PExp->getType()->getAs<PointerType>()->getPointeeType();
465 llvm::APSInt SizeOfPointee(AdditionalOffset);
Mike Stump1eb44332009-09-09 15:08:12 +0000466
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000467 // Explicitly handle GNU void* and function pointer arithmetic extensions.
468 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000469 SizeOfPointee = 1;
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000470 else
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000471 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType).getQuantity();
Eli Friedman4efaa272008-11-12 09:44:48 +0000472
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000473 llvm::APSInt Offset(AdditionalOffset);
474 Offset = ResultLValue.getLValueOffset().getQuantity();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000475 if (E->getOpcode() == BinaryOperator::Add)
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000476 Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000477 else
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000478 Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000479
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000480 // Sign extend prior to converting back to a char unit.
481 if (Offset.getBitWidth() < 64)
482 Offset.extend(64);
483 return APValue(ResultLValue.getLValueBase(),
484 CharUnits::fromQuantity(Offset.getLimitedValue()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000485}
Eli Friedman4efaa272008-11-12 09:44:48 +0000486
Eli Friedman2217c872009-02-22 11:46:18 +0000487APValue PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
488 APValue result;
489 if (EvaluateLValue(E->getSubExpr(), result, Info))
490 return result;
Eli Friedman4efaa272008-11-12 09:44:48 +0000491 return APValue();
492}
Mike Stump1eb44332009-09-09 15:08:12 +0000493
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000494
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000495APValue PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
496 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000497
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000498 switch (E->getCastKind()) {
499 default:
500 break;
501
502 case CastExpr::CK_Unknown: {
503 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
504
505 // Check for pointer->pointer cast
506 if (SubExpr->getType()->isPointerType() ||
507 SubExpr->getType()->isObjCObjectPointerType() ||
508 SubExpr->getType()->isNullPtrType() ||
509 SubExpr->getType()->isBlockPointerType())
510 return Visit(SubExpr);
511
512 if (SubExpr->getType()->isIntegralType()) {
513 APValue Result;
514 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
515 break;
516
517 if (Result.isInt()) {
518 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Ken Dycka7305832010-01-15 12:37:54 +0000519 return APValue(0,
520 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000521 }
522
523 // Cast is of an lvalue, no need to change value.
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000524 return Result;
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000525 }
526 break;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000529 case CastExpr::CK_NoOp:
530 case CastExpr::CK_BitCast:
531 case CastExpr::CK_AnyPointerToObjCPointerCast:
532 case CastExpr::CK_AnyPointerToBlockPointerCast:
533 return Visit(SubExpr);
534
535 case CastExpr::CK_IntegralToPointer: {
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000536 APValue Result;
537 if (!EvaluateIntegerOrLValue(SubExpr, Result, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000538 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000539
540 if (Result.isInt()) {
541 Result.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
Ken Dycka7305832010-01-15 12:37:54 +0000542 return APValue(0,
543 CharUnits::fromQuantity(Result.getInt().getZExtValue()));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000544 }
Mike Stump1eb44332009-09-09 15:08:12 +0000545
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000546 // Cast is of an lvalue, no need to change value.
547 return Result;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000548 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000549 case CastExpr::CK_ArrayToPointerDecay:
550 case CastExpr::CK_FunctionToPointerDecay: {
Eli Friedman4efaa272008-11-12 09:44:48 +0000551 APValue Result;
552 if (EvaluateLValue(SubExpr, Result, Info))
553 return Result;
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000554 break;
555 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000556 }
557
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000558 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000559}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000560
Eli Friedman3941b182009-01-25 01:54:01 +0000561APValue PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000562 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000563 Builtin::BI__builtin___CFStringMakeConstantString ||
564 E->isBuiltinCall(Info.Ctx) ==
565 Builtin::BI__builtin___NSStringMakeConstantString)
Ken Dycka7305832010-01-15 12:37:54 +0000566 return APValue(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000567 return APValue();
568}
569
Eli Friedman4efaa272008-11-12 09:44:48 +0000570APValue PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
571 bool BoolResult;
572 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
573 return APValue();
574
575 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
576
577 APValue Result;
578 if (EvaluatePointer(EvalExpr, Result, Info))
579 return Result;
580 return APValue();
581}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000582
583//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000584// Vector Evaluation
585//===----------------------------------------------------------------------===//
586
587namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000588 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000589 : public StmtVisitor<VectorExprEvaluator, APValue> {
590 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000591 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000592 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Nate Begeman59b5da62009-01-18 03:20:47 +0000594 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000595
Nate Begeman59b5da62009-01-18 03:20:47 +0000596 APValue VisitStmt(Stmt *S) {
597 return APValue();
598 }
Mike Stump1eb44332009-09-09 15:08:12 +0000599
Eli Friedman91110ee2009-02-23 04:23:56 +0000600 APValue VisitParenExpr(ParenExpr *E)
601 { return Visit(E->getSubExpr()); }
602 APValue VisitUnaryExtension(const UnaryOperator *E)
603 { return Visit(E->getSubExpr()); }
604 APValue VisitUnaryPlus(const UnaryOperator *E)
605 { return Visit(E->getSubExpr()); }
606 APValue VisitUnaryReal(const UnaryOperator *E)
607 { return Visit(E->getSubExpr()); }
608 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
609 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000610 APValue VisitCastExpr(const CastExpr* E);
611 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
612 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000613 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000614 APValue VisitChooseExpr(const ChooseExpr *E)
615 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000616 APValue VisitUnaryImag(const UnaryOperator *E);
617 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000618 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000619 // shufflevector, ExtVectorElementExpr
620 // (Note that these require implementing conversions
621 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000622 };
623} // end anonymous namespace
624
625static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
626 if (!E->getType()->isVectorType())
627 return false;
628 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
629 return !Result.isUninit();
630}
631
632APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000633 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000634 QualType EltTy = VTy->getElementType();
635 unsigned NElts = VTy->getNumElements();
636 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Nate Begeman59b5da62009-01-18 03:20:47 +0000638 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000639 QualType SETy = SE->getType();
640 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000641
Nate Begemane8c9e922009-06-26 18:22:18 +0000642 // Check for vector->vector bitcast and scalar->vector splat.
643 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000644 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000645 } else if (SETy->isIntegerType()) {
646 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000647 if (!EvaluateInteger(SE, IntResult, Info))
648 return APValue();
649 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000650 } else if (SETy->isRealFloatingType()) {
651 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000652 if (!EvaluateFloat(SE, F, Info))
653 return APValue();
654 Result = APValue(F);
655 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000656 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000657
Nate Begemanc0b8b192009-07-01 07:50:47 +0000658 // For casts of a scalar to ExtVector, convert the scalar to the element type
659 // and splat it to all elements.
660 if (E->getType()->isExtVectorType()) {
661 if (EltTy->isIntegerType() && Result.isInt())
662 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
663 Info.Ctx));
664 else if (EltTy->isIntegerType())
665 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
666 Info.Ctx));
667 else if (EltTy->isRealFloatingType() && Result.isInt())
668 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
669 Info.Ctx));
670 else if (EltTy->isRealFloatingType())
671 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
672 Info.Ctx));
673 else
674 return APValue();
675
676 // Splat and create vector APValue.
677 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
678 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000679 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000680
681 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
682 // to the vector. To construct the APValue vector initializer, bitcast the
683 // initializing value to an APInt, and shift out the bits pertaining to each
684 // element.
685 APSInt Init;
686 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Nate Begemanc0b8b192009-07-01 07:50:47 +0000688 llvm::SmallVector<APValue, 4> Elts;
689 for (unsigned i = 0; i != NElts; ++i) {
690 APSInt Tmp = Init;
691 Tmp.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000692
Nate Begemanc0b8b192009-07-01 07:50:47 +0000693 if (EltTy->isIntegerType())
694 Elts.push_back(APValue(Tmp));
695 else if (EltTy->isRealFloatingType())
696 Elts.push_back(APValue(APFloat(Tmp)));
697 else
698 return APValue();
699
700 Init >>= EltWidth;
701 }
702 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000703}
704
Mike Stump1eb44332009-09-09 15:08:12 +0000705APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000706VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
707 return this->Visit(const_cast<Expr*>(E->getInitializer()));
708}
709
Mike Stump1eb44332009-09-09 15:08:12 +0000710APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000711VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000712 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000713 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000714 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000715
Nate Begeman59b5da62009-01-18 03:20:47 +0000716 QualType EltTy = VT->getElementType();
717 llvm::SmallVector<APValue, 4> Elements;
718
Eli Friedman91110ee2009-02-23 04:23:56 +0000719 for (unsigned i = 0; i < NumElements; i++) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000720 if (EltTy->isIntegerType()) {
721 llvm::APSInt sInt(32);
Eli Friedman91110ee2009-02-23 04:23:56 +0000722 if (i < NumInits) {
723 if (!EvaluateInteger(E->getInit(i), sInt, Info))
724 return APValue();
725 } else {
726 sInt = Info.Ctx.MakeIntValue(0, EltTy);
727 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000728 Elements.push_back(APValue(sInt));
729 } else {
730 llvm::APFloat f(0.0);
Eli Friedman91110ee2009-02-23 04:23:56 +0000731 if (i < NumInits) {
732 if (!EvaluateFloat(E->getInit(i), f, Info))
733 return APValue();
734 } else {
735 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
736 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000737 Elements.push_back(APValue(f));
738 }
739 }
740 return APValue(&Elements[0], Elements.size());
741}
742
Mike Stump1eb44332009-09-09 15:08:12 +0000743APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000744VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000745 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000746 QualType EltTy = VT->getElementType();
747 APValue ZeroElement;
748 if (EltTy->isIntegerType())
749 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
750 else
751 ZeroElement =
752 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
753
754 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
755 return APValue(&Elements[0], Elements.size());
756}
757
758APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
759 bool BoolResult;
760 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
761 return APValue();
762
763 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
764
765 APValue Result;
766 if (EvaluateVector(EvalExpr, Result, Info))
767 return Result;
768 return APValue();
769}
770
Eli Friedman91110ee2009-02-23 04:23:56 +0000771APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
772 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
773 Info.EvalResult.HasSideEffects = true;
774 return GetZeroVector(E->getType());
775}
776
Nate Begeman59b5da62009-01-18 03:20:47 +0000777//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000778// Integer Evaluation
779//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000780
781namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000782class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000783 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000784 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000785 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000786public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000787 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000788 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000789
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000790 bool Success(const llvm::APSInt &SI, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000791 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000792 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000793 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000794 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000795 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000796 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000797 return true;
798 }
799
Daniel Dunbar131eb432009-02-19 09:06:44 +0000800 bool Success(const llvm::APInt &I, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000801 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000802 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000803 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000804 Result = APValue(APSInt(I));
805 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000806 return true;
807 }
808
809 bool Success(uint64_t Value, const Expr *E) {
Daniel Dunbar4fff4812009-02-21 18:14:20 +0000810 assert(E->getType()->isIntegralType() && "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000811 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000812 return true;
813 }
814
Anders Carlsson82206e22008-11-30 18:14:57 +0000815 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000816 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000817 if (Info.EvalResult.Diag == 0) {
818 Info.EvalResult.DiagLoc = L;
819 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000820 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000821 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000822 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000823 }
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Anders Carlssonc754aa62008-07-08 05:13:58 +0000825 //===--------------------------------------------------------------------===//
826 // Visitor Methods
827 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000828
Chris Lattner32fea9d2008-11-12 07:43:42 +0000829 bool VisitStmt(Stmt *) {
830 assert(0 && "This should be called on integers, stmts are not integers");
831 return false;
832 }
Mike Stump1eb44332009-09-09 15:08:12 +0000833
Chris Lattner32fea9d2008-11-12 07:43:42 +0000834 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000835 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000836 }
Mike Stump1eb44332009-09-09 15:08:12 +0000837
Chris Lattnerb542afe2008-07-11 19:10:17 +0000838 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000839
Chris Lattner4c4867e2008-07-12 00:38:25 +0000840 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000841 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000842 }
843 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000844 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000845 }
846 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarac620de2008-10-24 08:07:57 +0000847 // Per gcc docs "this built-in function ignores top level
848 // qualifiers". We need to use the canonical version to properly
849 // be able to strip CRV qualifiers from the type.
850 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
851 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump1eb44332009-09-09 15:08:12 +0000852 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar131eb432009-02-19 09:06:44 +0000853 T1.getUnqualifiedType()),
854 E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000855 }
Eli Friedman04309752009-11-24 05:28:59 +0000856
857 bool CheckReferencedDecl(const Expr *E, const Decl *D);
858 bool VisitDeclRefExpr(const DeclRefExpr *E) {
859 return CheckReferencedDecl(E, E->getDecl());
860 }
861 bool VisitMemberExpr(const MemberExpr *E) {
862 if (CheckReferencedDecl(E, E->getMemberDecl())) {
863 // Conservatively assume a MemberExpr will have side-effects
864 Info.EvalResult.HasSideEffects = true;
865 return true;
866 }
867 return false;
868 }
869
Eli Friedmanc4a26382010-02-13 00:10:10 +0000870 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000871 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000872 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000873 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000874 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000875
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000876 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000877 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
878
Anders Carlsson3068d112008-11-16 19:01:22 +0000879 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000880 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000881 }
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Anders Carlsson3f704562008-12-21 22:39:40 +0000883 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000884 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000885 }
Mike Stump1eb44332009-09-09 15:08:12 +0000886
Anders Carlsson3068d112008-11-16 19:01:22 +0000887 bool VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000888 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000889 }
890
Eli Friedman664a1042009-02-27 04:45:43 +0000891 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
892 return Success(0, E);
893 }
894
Sebastian Redl64b45f72009-01-05 20:52:13 +0000895 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +0000896 return Success(E->EvaluateTrait(Info.Ctx), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000897 }
898
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000899 bool VisitChooseExpr(const ChooseExpr *E) {
900 return Visit(E->getChosenSubExpr(Info.Ctx));
901 }
902
Eli Friedman722c7172009-02-28 03:59:05 +0000903 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000904 bool VisitUnaryImag(const UnaryOperator *E);
905
Chris Lattnerfcee0012008-07-11 21:24:13 +0000906private:
Ken Dyck8b752f12010-01-27 17:10:57 +0000907 CharUnits GetAlignOfExpr(const Expr *E);
908 CharUnits GetAlignOfType(QualType T);
Eli Friedman664a1042009-02-27 04:45:43 +0000909 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000910};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000911} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000912
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000913static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000914 assert(E->getType()->isIntegralType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000915 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
916}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000917
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000918static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000919 assert(E->getType()->isIntegralType());
920
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000921 APValue Val;
922 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
923 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000924 Result = Val.getInt();
925 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +0000926}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000927
Eli Friedman04309752009-11-24 05:28:59 +0000928bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000929 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +0000930 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
931 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000932
933 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +0000934 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000935 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
936 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +0000937
938 if (isa<ParmVarDecl>(D))
939 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
940
Eli Friedman04309752009-11-24 05:28:59 +0000941 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000942 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +0000943 if (APValue *V = VD->getEvaluatedValue()) {
944 if (V->isInt())
945 return Success(V->getInt(), E);
946 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
947 }
948
949 if (VD->isEvaluatingValue())
950 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
951
952 VD->setEvaluatingValue();
953
Douglas Gregor78d15832009-05-26 18:54:04 +0000954 if (Visit(const_cast<Expr*>(Init))) {
955 // Cache the evaluated value in the variable declaration.
Eli Friedmanc0131182009-12-03 20:31:57 +0000956 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +0000957 return true;
958 }
959
Eli Friedmanc0131182009-12-03 20:31:57 +0000960 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +0000961 return false;
962 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000963 }
964 }
965
Chris Lattner4c4867e2008-07-12 00:38:25 +0000966 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000967 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000968}
969
Chris Lattnera4d55d82008-10-06 06:40:35 +0000970/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
971/// as GCC.
972static int EvaluateBuiltinClassifyType(const CallExpr *E) {
973 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +0000974 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +0000975 enum gcc_type_class {
976 no_type_class = -1,
977 void_type_class, integer_type_class, char_type_class,
978 enumeral_type_class, boolean_type_class,
979 pointer_type_class, reference_type_class, offset_type_class,
980 real_type_class, complex_type_class,
981 function_type_class, method_type_class,
982 record_type_class, union_type_class,
983 array_type_class, string_type_class,
984 lang_type_class
985 };
Mike Stump1eb44332009-09-09 15:08:12 +0000986
987 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +0000988 // ideal, however it is what gcc does.
989 if (E->getNumArgs() == 0)
990 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattnera4d55d82008-10-06 06:40:35 +0000992 QualType ArgTy = E->getArg(0)->getType();
993 if (ArgTy->isVoidType())
994 return void_type_class;
995 else if (ArgTy->isEnumeralType())
996 return enumeral_type_class;
997 else if (ArgTy->isBooleanType())
998 return boolean_type_class;
999 else if (ArgTy->isCharType())
1000 return string_type_class; // gcc doesn't appear to use char_type_class
1001 else if (ArgTy->isIntegerType())
1002 return integer_type_class;
1003 else if (ArgTy->isPointerType())
1004 return pointer_type_class;
1005 else if (ArgTy->isReferenceType())
1006 return reference_type_class;
1007 else if (ArgTy->isRealType())
1008 return real_type_class;
1009 else if (ArgTy->isComplexType())
1010 return complex_type_class;
1011 else if (ArgTy->isFunctionType())
1012 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001013 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001014 return record_type_class;
1015 else if (ArgTy->isUnionType())
1016 return union_type_class;
1017 else if (ArgTy->isArrayType())
1018 return array_type_class;
1019 else if (ArgTy->isUnionType())
1020 return union_type_class;
1021 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1022 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1023 return -1;
1024}
1025
Eli Friedmanc4a26382010-02-13 00:10:10 +00001026bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001027 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001028 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001029 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001030
1031 case Builtin::BI__builtin_object_size: {
Mike Stump64eda9e2009-10-26 18:35:08 +00001032 const Expr *Arg = E->getArg(0)->IgnoreParens();
1033 Expr::EvalResult Base;
Eric Christopherb2aaf512010-01-19 22:58:35 +00001034
1035 // TODO: Perhaps we should let LLVM lower this?
Mike Stump660e6f72009-10-26 23:05:19 +00001036 if (Arg->EvaluateAsAny(Base, Info.Ctx)
Mike Stump64eda9e2009-10-26 18:35:08 +00001037 && Base.Val.getKind() == APValue::LValue
1038 && !Base.HasSideEffects)
1039 if (const Expr *LVBase = Base.Val.getLValueBase())
1040 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(LVBase)) {
1041 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
Mike Stump460d1382009-10-28 21:22:24 +00001042 if (!VD->getType()->isIncompleteType()
1043 && VD->getType()->isObjectType()
1044 && !VD->getType()->isVariablyModifiedType()
1045 && !VD->getType()->isDependentType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001046 CharUnits Size = Info.Ctx.getTypeSizeInChars(VD->getType());
Ken Dycka7305832010-01-15 12:37:54 +00001047 CharUnits Offset = Base.Val.getLValueOffset();
Ken Dyck199c3d62010-01-11 17:06:35 +00001048 if (!Offset.isNegative() && Offset <= Size)
1049 Size -= Offset;
Mike Stump460d1382009-10-28 21:22:24 +00001050 else
Ken Dyck199c3d62010-01-11 17:06:35 +00001051 Size = CharUnits::Zero();
1052 return Success(Size.getQuantity(), E);
Mike Stump460d1382009-10-28 21:22:24 +00001053 }
Mike Stump64eda9e2009-10-26 18:35:08 +00001054 }
1055 }
1056
Eric Christopherb2aaf512010-01-19 22:58:35 +00001057 // If evaluating the argument has side-effects we can't determine
1058 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001059 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001060 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001061 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001062 return Success(0, E);
1063 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001064
Mike Stump64eda9e2009-10-26 18:35:08 +00001065 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1066 }
1067
Chris Lattner019f4e82008-10-06 05:28:25 +00001068 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001069 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001070
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001071 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001072 // __builtin_constant_p always has one operand: it returns true if that
1073 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001074 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001075
1076 case Builtin::BI__builtin_eh_return_data_regno: {
1077 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1078 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1079 return Success(Operand, E);
1080 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001081
1082 case Builtin::BI__builtin_expect:
1083 return Visit(E->getArg(0));
Chris Lattner019f4e82008-10-06 05:28:25 +00001084 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001085}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001086
Chris Lattnerb542afe2008-07-11 19:10:17 +00001087bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001088 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001089 if (!Visit(E->getRHS()))
1090 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001091
Eli Friedman33ef1452009-02-26 10:19:36 +00001092 // If we can't evaluate the LHS, it might have side effects;
1093 // conservatively mark it.
1094 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1095 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001096
Anders Carlsson027f62e2008-12-01 02:07:06 +00001097 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001098 }
1099
1100 if (E->isLogicalOp()) {
1101 // These need to be handled specially because the operands aren't
1102 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001103 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001104
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001105 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001106 // We were able to evaluate the LHS, see if we can get away with not
1107 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Eli Friedman33ef1452009-02-26 10:19:36 +00001108 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001109 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001110
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001111 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001112 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001113 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001114 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001115 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001116 }
1117 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001118 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001119 // We can't evaluate the LHS; however, sometimes the result
1120 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Mike Stump1eb44332009-09-09 15:08:12 +00001121 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001122 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001123 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001124 // must have had side effects.
1125 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001126
1127 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001128 }
1129 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001130 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001131
Eli Friedmana6afa762008-11-13 06:09:17 +00001132 return false;
1133 }
1134
Anders Carlsson286f85e2008-11-16 07:17:21 +00001135 QualType LHSTy = E->getLHS()->getType();
1136 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001137
1138 if (LHSTy->isAnyComplexType()) {
1139 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001140 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001141
1142 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1143 return false;
1144
1145 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1146 return false;
1147
1148 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001149 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001150 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001151 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001152 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1153
Daniel Dunbar4087e242009-01-29 06:43:41 +00001154 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001155 return Success((CR_r == APFloat::cmpEqual &&
1156 CR_i == APFloat::cmpEqual), E);
1157 else {
1158 assert(E->getOpcode() == BinaryOperator::NE &&
1159 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001160 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001161 CR_r == APFloat::cmpLessThan ||
1162 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001163 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001164 CR_i == APFloat::cmpLessThan ||
1165 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001166 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001167 } else {
Daniel Dunbar4087e242009-01-29 06:43:41 +00001168 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001169 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1170 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1171 else {
1172 assert(E->getOpcode() == BinaryOperator::NE &&
1173 "Invalid compex comparison.");
1174 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1175 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1176 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001177 }
1178 }
Mike Stump1eb44332009-09-09 15:08:12 +00001179
Anders Carlsson286f85e2008-11-16 07:17:21 +00001180 if (LHSTy->isRealFloatingType() &&
1181 RHSTy->isRealFloatingType()) {
1182 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Anders Carlsson286f85e2008-11-16 07:17:21 +00001184 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1185 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001186
Anders Carlsson286f85e2008-11-16 07:17:21 +00001187 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1188 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001189
Anders Carlsson286f85e2008-11-16 07:17:21 +00001190 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001191
Anders Carlsson286f85e2008-11-16 07:17:21 +00001192 switch (E->getOpcode()) {
1193 default:
1194 assert(0 && "Invalid binary operator!");
1195 case BinaryOperator::LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001196 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001197 case BinaryOperator::GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001198 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001199 case BinaryOperator::LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001200 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001201 case BinaryOperator::GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001202 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001203 E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001204 case BinaryOperator::EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001205 return Success(CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001206 case BinaryOperator::NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001207 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001208 || CR == APFloat::cmpLessThan
1209 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001210 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001211 }
Mike Stump1eb44332009-09-09 15:08:12 +00001212
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001213 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1214 if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
Anders Carlsson3068d112008-11-16 19:01:22 +00001215 APValue LHSValue;
1216 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1217 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001218
Anders Carlsson3068d112008-11-16 19:01:22 +00001219 APValue RHSValue;
1220 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1221 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001222
Eli Friedman5bc86102009-06-14 02:17:33 +00001223 // Reject any bases from the normal codepath; we special-case comparisons
1224 // to null.
1225 if (LHSValue.getLValueBase()) {
1226 if (!E->isEqualityOp())
1227 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001228 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001229 return false;
1230 bool bres;
1231 if (!EvalPointerValueAsBool(LHSValue, bres))
1232 return false;
1233 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1234 } else if (RHSValue.getLValueBase()) {
1235 if (!E->isEqualityOp())
1236 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001237 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001238 return false;
1239 bool bres;
1240 if (!EvalPointerValueAsBool(RHSValue, bres))
1241 return false;
1242 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1243 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001244
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001245 if (E->getOpcode() == BinaryOperator::Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001246 QualType Type = E->getLHS()->getType();
1247 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001248
Ken Dycka7305832010-01-15 12:37:54 +00001249 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001250 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001251 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001252
Ken Dycka7305832010-01-15 12:37:54 +00001253 CharUnits Diff = LHSValue.getLValueOffset() -
1254 RHSValue.getLValueOffset();
1255 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001256 }
1257 bool Result;
1258 if (E->getOpcode() == BinaryOperator::EQ) {
1259 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001260 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001261 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1262 }
1263 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001264 }
1265 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001266 if (!LHSTy->isIntegralType() ||
1267 !RHSTy->isIntegralType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001268 // We can't continue from here for non-integral types, and they
1269 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001270 return false;
1271 }
1272
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001273 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001274 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001275 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001276
Eli Friedman42edd0d2009-03-24 01:14:50 +00001277 APValue RHSVal;
1278 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001279 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001280
1281 // Handle cases like (unsigned long)&a + 4.
1282 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001283 CharUnits Offset = Result.getLValueOffset();
1284 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1285 RHSVal.getInt().getZExtValue());
Eli Friedman42edd0d2009-03-24 01:14:50 +00001286 if (E->getOpcode() == BinaryOperator::Add)
Ken Dycka7305832010-01-15 12:37:54 +00001287 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001288 else
Ken Dycka7305832010-01-15 12:37:54 +00001289 Offset -= AdditionalOffset;
1290 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001291 return true;
1292 }
1293
1294 // Handle cases like 4 + (unsigned long)&a
1295 if (E->getOpcode() == BinaryOperator::Add &&
1296 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001297 CharUnits Offset = RHSVal.getLValueOffset();
1298 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1299 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001300 return true;
1301 }
1302
1303 // All the following cases expect both operands to be an integer
1304 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001305 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001306
Eli Friedman42edd0d2009-03-24 01:14:50 +00001307 APSInt& RHS = RHSVal.getInt();
1308
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001309 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001310 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001311 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001312 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1313 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1314 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1315 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1316 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1317 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001318 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001319 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001320 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001321 return Success(Result.getInt() / RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001322 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001323 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001324 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001325 return Success(Result.getInt() % RHS, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001326 case BinaryOperator::Shl: {
Chris Lattner54176fd2008-07-12 00:14:42 +00001327 // FIXME: Warn about out of range shift amounts!
Mike Stump1eb44332009-09-09 15:08:12 +00001328 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001329 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1330 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001331 }
1332 case BinaryOperator::Shr: {
Mike Stump1eb44332009-09-09 15:08:12 +00001333 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001334 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1335 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001336 }
Mike Stump1eb44332009-09-09 15:08:12 +00001337
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001338 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1339 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1340 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1341 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1342 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1343 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001344 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001345}
1346
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001347bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001348 bool Cond;
1349 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001350 return false;
1351
Nuno Lopesa25bd552008-11-16 22:06:39 +00001352 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001353}
1354
Ken Dyck8b752f12010-01-27 17:10:57 +00001355CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001356 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1357 // the result is the size of the referenced type."
1358 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1359 // result shall be the alignment of the referenced type."
1360 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1361 T = Ref->getPointeeType();
1362
Chris Lattnere9feb472009-01-24 21:09:06 +00001363 // Get information about the alignment.
1364 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001365
Eli Friedman2be58612009-05-30 21:09:44 +00001366 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001367 return CharUnits::fromQuantity(
1368 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001369}
1370
Ken Dyck8b752f12010-01-27 17:10:57 +00001371CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001372 E = E->IgnoreParens();
1373
1374 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001375 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001376 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001377 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1378 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001379
Chris Lattneraf707ab2009-01-24 21:53:27 +00001380 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001381 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1382 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001383
Chris Lattnere9feb472009-01-24 21:09:06 +00001384 return GetAlignOfType(E->getType());
1385}
1386
1387
Sebastian Redl05189992008-11-11 17:56:53 +00001388/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1389/// expression's type.
1390bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001391 // Handle alignof separately.
1392 if (!E->isSizeOf()) {
1393 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001394 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001395 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001396 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001397 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001398
Sebastian Redl05189992008-11-11 17:56:53 +00001399 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001400 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1401 // the result is the size of the referenced type."
1402 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1403 // result shall be the alignment of the referenced type."
1404 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1405 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001406
Daniel Dunbar131eb432009-02-19 09:06:44 +00001407 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1408 // extension.
1409 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1410 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001411
Chris Lattnerfcee0012008-07-11 21:24:13 +00001412 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001413 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001414 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001415
Chris Lattnere9feb472009-01-24 21:09:06 +00001416 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001417 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001418}
1419
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001420bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1421 CharUnits Result;
1422 unsigned n = E->getNumComponents();
1423 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1424 if (n == 0)
1425 return false;
1426 QualType CurrentType = E->getTypeSourceInfo()->getType();
1427 for (unsigned i = 0; i != n; ++i) {
1428 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1429 switch (ON.getKind()) {
1430 case OffsetOfExpr::OffsetOfNode::Array: {
1431 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1432 APSInt IdxResult;
1433 if (!EvaluateInteger(Idx, IdxResult, Info))
1434 return false;
1435 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1436 if (!AT)
1437 return false;
1438 CurrentType = AT->getElementType();
1439 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1440 Result += IdxResult.getSExtValue() * ElementSize;
1441 break;
1442 }
1443
1444 case OffsetOfExpr::OffsetOfNode::Field: {
1445 FieldDecl *MemberDecl = ON.getField();
1446 const RecordType *RT = CurrentType->getAs<RecordType>();
1447 if (!RT)
1448 return false;
1449 RecordDecl *RD = RT->getDecl();
1450 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1451 unsigned i = 0;
1452 // FIXME: It would be nice if we didn't have to loop here!
1453 for (RecordDecl::field_iterator Field = RD->field_begin(),
1454 FieldEnd = RD->field_end();
1455 Field != FieldEnd; (void)++Field, ++i) {
1456 if (*Field == MemberDecl)
1457 break;
1458 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001459 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1460 Result += CharUnits::fromQuantity(
1461 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001462 CurrentType = MemberDecl->getType().getNonReferenceType();
1463 break;
1464 }
1465
1466 case OffsetOfExpr::OffsetOfNode::Identifier:
1467 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001468 return false;
1469
1470 case OffsetOfExpr::OffsetOfNode::Base: {
1471 CXXBaseSpecifier *BaseSpec = ON.getBase();
1472 if (BaseSpec->isVirtual())
1473 return false;
1474
1475 // Find the layout of the class whose base we are looking into.
1476 const RecordType *RT = CurrentType->getAs<RecordType>();
1477 if (!RT)
1478 return false;
1479 RecordDecl *RD = RT->getDecl();
1480 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1481
1482 // Find the base class itself.
1483 CurrentType = BaseSpec->getType();
1484 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1485 if (!BaseRT)
1486 return false;
1487
1488 // Add the offset to the base.
1489 Result += CharUnits::fromQuantity(
1490 RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1491 / Info.Ctx.getCharWidth());
1492 break;
1493 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001494 }
1495 }
1496 return Success(Result.getQuantity(), E);
1497}
1498
Chris Lattnerb542afe2008-07-11 19:10:17 +00001499bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001500 // Special case unary operators that do not need their subexpression
1501 // evaluated. offsetof/sizeof/alignof are all special.
Eli Friedman35183ac2009-02-27 06:44:11 +00001502 if (E->isOffsetOfOp()) {
1503 // The AST for offsetof is defined in such a way that we can just
1504 // directly Evaluate it as an l-value.
1505 APValue LV;
1506 if (!EvaluateLValue(E->getSubExpr(), LV, Info))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001507 return false;
Eli Friedman35183ac2009-02-27 06:44:11 +00001508 if (LV.getLValueBase())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001509 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001510 return Success(LV.getLValueOffset().getQuantity(), E);
Eli Friedman35183ac2009-02-27 06:44:11 +00001511 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001512
Eli Friedmana6afa762008-11-13 06:09:17 +00001513 if (E->getOpcode() == UnaryOperator::LNot) {
1514 // LNot's operand isn't necessarily an integer, so we handle it specially.
1515 bool bres;
1516 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1517 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001518 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001519 }
1520
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001521 // Only handle integral operations...
1522 if (!E->getSubExpr()->getType()->isIntegralType())
1523 return false;
1524
Chris Lattner87eae5e2008-07-11 22:52:41 +00001525 // Get the operand value into 'Result'.
1526 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001527 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001528
Chris Lattner75a48812008-07-11 22:15:16 +00001529 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001530 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001531 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1532 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001533 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001534 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001535 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1536 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001537 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001538 case UnaryOperator::Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001539 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001540 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001541 case UnaryOperator::Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001542 if (!Result.isInt()) return false;
1543 return Success(-Result.getInt(), E);
Chris Lattner75a48812008-07-11 22:15:16 +00001544 case UnaryOperator::Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001545 if (!Result.isInt()) return false;
1546 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001547 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001548}
Mike Stump1eb44332009-09-09 15:08:12 +00001549
Chris Lattner732b2232008-07-12 01:15:53 +00001550/// HandleCast - This is used to evaluate implicit or explicit casts where the
1551/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001552bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001553 Expr *SubExpr = E->getSubExpr();
1554 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001555 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001556
Eli Friedman4efaa272008-11-12 09:44:48 +00001557 if (DestType->isBooleanType()) {
1558 bool BoolResult;
1559 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1560 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001561 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001562 }
1563
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001564 // Handle simple integer->integer casts.
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001565 if (SrcType->isIntegralType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001566 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001567 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001568
Eli Friedmanbe265702009-02-20 01:15:07 +00001569 if (!Result.isInt()) {
1570 // Only allow casts of lvalues if they are lossless.
1571 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1572 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001573
Daniel Dunbardd211642009-02-19 22:24:01 +00001574 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001575 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
Chris Lattner732b2232008-07-12 01:15:53 +00001578 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001579 if (SrcType->isPointerType()) {
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001580 APValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001581 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001582 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001583
Daniel Dunbardd211642009-02-19 22:24:01 +00001584 if (LV.getLValueBase()) {
1585 // Only allow based lvalue casts if they are lossless.
1586 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1587 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001588
Daniel Dunbardd211642009-02-19 22:24:01 +00001589 Result = LV;
1590 return true;
1591 }
1592
Ken Dycka7305832010-01-15 12:37:54 +00001593 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1594 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001595 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001596 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001597
Eli Friedmanbe265702009-02-20 01:15:07 +00001598 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1599 // This handles double-conversion cases, where there's both
1600 // an l-value promotion and an implicit conversion to int.
1601 APValue LV;
1602 if (!EvaluateLValue(SubExpr, LV, Info))
1603 return false;
1604
1605 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1606 return false;
1607
1608 Result = LV;
1609 return true;
1610 }
1611
Eli Friedman1725f682009-04-22 19:23:09 +00001612 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001613 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001614 if (!EvaluateComplex(SubExpr, C, Info))
1615 return false;
1616 if (C.isComplexFloat())
1617 return Success(HandleFloatToIntCast(DestType, SrcType,
1618 C.getComplexFloatReal(), Info.Ctx),
1619 E);
1620 else
1621 return Success(HandleIntToIntCast(DestType, SrcType,
1622 C.getComplexIntReal(), Info.Ctx), E);
1623 }
Eli Friedman2217c872009-02-22 11:46:18 +00001624 // FIXME: Handle vectors
1625
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001626 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001627 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001628
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001629 APFloat F(0.0);
1630 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001631 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001632
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001633 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001634}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001635
Eli Friedman722c7172009-02-28 03:59:05 +00001636bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1637 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001638 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001639 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1640 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1641 return Success(LV.getComplexIntReal(), E);
1642 }
1643
1644 return Visit(E->getSubExpr());
1645}
1646
Eli Friedman664a1042009-02-27 04:45:43 +00001647bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001648 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001649 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001650 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1651 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1652 return Success(LV.getComplexIntImag(), E);
1653 }
1654
Eli Friedman664a1042009-02-27 04:45:43 +00001655 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1656 Info.EvalResult.HasSideEffects = true;
1657 return Success(0, E);
1658}
1659
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001660//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001661// Float Evaluation
1662//===----------------------------------------------------------------------===//
1663
1664namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001665class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001666 : public StmtVisitor<FloatExprEvaluator, bool> {
1667 EvalInfo &Info;
1668 APFloat &Result;
1669public:
1670 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1671 : Info(info), Result(result) {}
1672
1673 bool VisitStmt(Stmt *S) {
1674 return false;
1675 }
1676
1677 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001678 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001679
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001680 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001681 bool VisitBinaryOperator(const BinaryOperator *E);
1682 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001683 bool VisitCastExpr(CastExpr *E);
1684 bool VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001685 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001686
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001687 bool VisitChooseExpr(const ChooseExpr *E)
1688 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1689 bool VisitUnaryExtension(const UnaryOperator *E)
1690 { return Visit(E->getSubExpr()); }
1691
1692 // FIXME: Missing: __real__/__imag__, array subscript of vector,
Eli Friedman67f85fc2009-12-04 02:12:53 +00001693 // member of vector, ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001694};
1695} // end anonymous namespace
1696
1697static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001698 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001699 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1700}
1701
John McCalldb7b72a2010-02-28 13:00:19 +00001702static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1703 QualType ResultTy,
1704 const Expr *Arg,
1705 bool SNaN,
1706 llvm::APFloat &Result) {
1707 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1708 if (!S) return false;
1709
1710 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1711
1712 llvm::APInt fill;
1713
1714 // Treat empty strings as if they were zero.
1715 if (S->getString().empty())
1716 fill = llvm::APInt(32, 0);
1717 else if (S->getString().getAsInteger(0, fill))
1718 return false;
1719
1720 if (SNaN)
1721 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1722 else
1723 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1724 return true;
1725}
1726
Chris Lattner019f4e82008-10-06 05:28:25 +00001727bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001728 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001729 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001730 case Builtin::BI__builtin_huge_val:
1731 case Builtin::BI__builtin_huge_valf:
1732 case Builtin::BI__builtin_huge_vall:
1733 case Builtin::BI__builtin_inf:
1734 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001735 case Builtin::BI__builtin_infl: {
1736 const llvm::fltSemantics &Sem =
1737 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001738 Result = llvm::APFloat::getInf(Sem);
1739 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001740 }
Mike Stump1eb44332009-09-09 15:08:12 +00001741
John McCalldb7b72a2010-02-28 13:00:19 +00001742 case Builtin::BI__builtin_nans:
1743 case Builtin::BI__builtin_nansf:
1744 case Builtin::BI__builtin_nansl:
1745 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1746 true, Result);
1747
Chris Lattner9e621712008-10-06 06:31:58 +00001748 case Builtin::BI__builtin_nan:
1749 case Builtin::BI__builtin_nanf:
1750 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001751 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001752 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001753 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1754 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001755
1756 case Builtin::BI__builtin_fabs:
1757 case Builtin::BI__builtin_fabsf:
1758 case Builtin::BI__builtin_fabsl:
1759 if (!EvaluateFloat(E->getArg(0), Result, Info))
1760 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001761
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001762 if (Result.isNegative())
1763 Result.changeSign();
1764 return true;
1765
Mike Stump1eb44332009-09-09 15:08:12 +00001766 case Builtin::BI__builtin_copysign:
1767 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001768 case Builtin::BI__builtin_copysignl: {
1769 APFloat RHS(0.);
1770 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1771 !EvaluateFloat(E->getArg(1), RHS, Info))
1772 return false;
1773 Result.copySign(RHS);
1774 return true;
1775 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001776 }
1777}
1778
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001779bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001780 if (E->getOpcode() == UnaryOperator::Deref)
1781 return false;
1782
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001783 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1784 return false;
1785
1786 switch (E->getOpcode()) {
1787 default: return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001788 case UnaryOperator::Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001789 return true;
1790 case UnaryOperator::Minus:
1791 Result.changeSign();
1792 return true;
1793 }
1794}
Chris Lattner019f4e82008-10-06 05:28:25 +00001795
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001796bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman7f92f032009-11-16 04:25:37 +00001797 if (E->getOpcode() == BinaryOperator::Comma) {
1798 if (!EvaluateFloat(E->getRHS(), Result, Info))
1799 return false;
1800
1801 // If we can't evaluate the LHS, it might have side effects;
1802 // conservatively mark it.
1803 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1804 Info.EvalResult.HasSideEffects = true;
1805
1806 return true;
1807 }
1808
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001809 // FIXME: Diagnostics? I really don't understand how the warnings
1810 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001811 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001812 if (!EvaluateFloat(E->getLHS(), Result, Info))
1813 return false;
1814 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1815 return false;
1816
1817 switch (E->getOpcode()) {
1818 default: return false;
1819 case BinaryOperator::Mul:
1820 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1821 return true;
1822 case BinaryOperator::Add:
1823 Result.add(RHS, APFloat::rmNearestTiesToEven);
1824 return true;
1825 case BinaryOperator::Sub:
1826 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1827 return true;
1828 case BinaryOperator::Div:
1829 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1830 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001831 }
1832}
1833
1834bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1835 Result = E->getValue();
1836 return true;
1837}
1838
Eli Friedman4efaa272008-11-12 09:44:48 +00001839bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1840 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Eli Friedman4efaa272008-11-12 09:44:48 +00001842 if (SubExpr->getType()->isIntegralType()) {
1843 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001844 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00001845 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001846 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001847 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001848 return true;
1849 }
1850 if (SubExpr->getType()->isRealFloatingType()) {
1851 if (!Visit(SubExpr))
1852 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001853 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1854 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001855 return true;
1856 }
Eli Friedman2217c872009-02-22 11:46:18 +00001857 // FIXME: Handle complex types
Eli Friedman4efaa272008-11-12 09:44:48 +00001858
1859 return false;
1860}
1861
1862bool FloatExprEvaluator::VisitCXXZeroInitValueExpr(CXXZeroInitValueExpr *E) {
1863 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1864 return true;
1865}
1866
Eli Friedman67f85fc2009-12-04 02:12:53 +00001867bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1868 bool Cond;
1869 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1870 return false;
1871
1872 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1873}
1874
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001875//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001876// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001877//===----------------------------------------------------------------------===//
1878
1879namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001880class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00001881 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001882 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00001883 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001885public:
John McCallf4cf1a12010-05-07 17:22:02 +00001886 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
1887 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001889 //===--------------------------------------------------------------------===//
1890 // Visitor Methods
1891 //===--------------------------------------------------------------------===//
1892
John McCallf4cf1a12010-05-07 17:22:02 +00001893 bool VisitStmt(Stmt *S) {
1894 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001895 }
Mike Stump1eb44332009-09-09 15:08:12 +00001896
John McCallf4cf1a12010-05-07 17:22:02 +00001897 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001898
John McCallf4cf1a12010-05-07 17:22:02 +00001899 bool VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001900 Expr* SubExpr = E->getSubExpr();
1901
1902 if (SubExpr->getType()->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001903 Result.makeComplexFloat();
1904 APFloat &Imag = Result.FloatImag;
1905 if (!EvaluateFloat(SubExpr, Imag, Info))
1906 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001907
John McCallf4cf1a12010-05-07 17:22:02 +00001908 Result.FloatReal = APFloat(Imag.getSemantics());
1909 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001910 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001911 assert(SubExpr->getType()->isIntegerType() &&
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001912 "Unexpected imaginary literal.");
1913
John McCallf4cf1a12010-05-07 17:22:02 +00001914 Result.makeComplexInt();
1915 APSInt &Imag = Result.IntImag;
1916 if (!EvaluateInteger(SubExpr, Imag, Info))
1917 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001918
John McCallf4cf1a12010-05-07 17:22:02 +00001919 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
1920 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001921 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001922 }
1923
John McCallf4cf1a12010-05-07 17:22:02 +00001924 bool VisitCastExpr(CastExpr *E) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001925 Expr* SubExpr = E->getSubExpr();
John McCall183700f2009-09-21 23:43:11 +00001926 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001927 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00001928
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001929 if (SubType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001930 APFloat &Real = Result.FloatReal;
1931 if (!EvaluateFloat(SubExpr, Real, Info))
1932 return false;
Eli Friedman1725f682009-04-22 19:23:09 +00001933
1934 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001935 Result.makeComplexFloat();
1936 Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
1937 Result.FloatImag = APFloat(Real.getSemantics());
1938 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001939 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001940 Result.makeComplexInt();
1941 Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
1942 Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
1943 !Result.IntReal.isSigned());
1944 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001945 }
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001946 } else if (SubType->isIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001947 APSInt &Real = Result.IntReal;
1948 if (!EvaluateInteger(SubExpr, Real, Info))
1949 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001950
Eli Friedman1725f682009-04-22 19:23:09 +00001951 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001952 Result.makeComplexFloat();
1953 Result.FloatReal
1954 = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
1955 Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
1956 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001957 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001958 Result.makeComplexInt();
1959 Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
1960 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
1961 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00001962 }
John McCall183700f2009-09-21 23:43:11 +00001963 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001964 if (!Visit(SubExpr))
1965 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001966
1967 QualType SrcType = CT->getElementType();
1968
John McCallf4cf1a12010-05-07 17:22:02 +00001969 if (Result.isComplexFloat()) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001970 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001971 Result.makeComplexFloat();
1972 Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
1973 Result.FloatReal,
1974 Info.Ctx);
1975 Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
1976 Result.FloatImag,
1977 Info.Ctx);
1978 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001979 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001980 Result.makeComplexInt();
1981 Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
1982 Result.FloatReal,
1983 Info.Ctx);
1984 Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
1985 Result.FloatImag,
1986 Info.Ctx);
1987 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001988 }
1989 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00001990 assert(Result.isComplexInt() && "Invalid evaluate result.");
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001991 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001992 Result.makeComplexFloat();
1993 Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
1994 Result.IntReal,
1995 Info.Ctx);
1996 Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
1997 Result.IntImag,
1998 Info.Ctx);
1999 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002000 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002001 Result.makeComplexInt();
2002 Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2003 Result.IntReal,
2004 Info.Ctx);
2005 Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2006 Result.IntImag,
2007 Info.Ctx);
2008 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002009 }
2010 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002011 }
2012
2013 // FIXME: Handle more casts.
John McCallf4cf1a12010-05-07 17:22:02 +00002014 return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002015 }
Mike Stump1eb44332009-09-09 15:08:12 +00002016
John McCallf4cf1a12010-05-07 17:22:02 +00002017 bool VisitBinaryOperator(const BinaryOperator *E);
2018 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002019 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002020 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002021 { return Visit(E->getSubExpr()); }
2022 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedman2217c872009-02-22 11:46:18 +00002023 // conditional ?:, comma
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002024};
2025} // end anonymous namespace
2026
John McCallf4cf1a12010-05-07 17:22:02 +00002027static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2028 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002029 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002030 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002031}
2032
John McCallf4cf1a12010-05-07 17:22:02 +00002033bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2034 if (!Visit(E->getLHS()))
2035 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002036
John McCallf4cf1a12010-05-07 17:22:02 +00002037 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002038 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002039 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002040
Daniel Dunbar3f279872009-01-29 01:32:56 +00002041 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2042 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002043 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002044 default: return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002045 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002046 if (Result.isComplexFloat()) {
2047 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2048 APFloat::rmNearestTiesToEven);
2049 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2050 APFloat::rmNearestTiesToEven);
2051 } else {
2052 Result.getComplexIntReal() += RHS.getComplexIntReal();
2053 Result.getComplexIntImag() += RHS.getComplexIntImag();
2054 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002055 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002056 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002057 if (Result.isComplexFloat()) {
2058 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2059 APFloat::rmNearestTiesToEven);
2060 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2061 APFloat::rmNearestTiesToEven);
2062 } else {
2063 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2064 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2065 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002066 break;
2067 case BinaryOperator::Mul:
2068 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002069 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002070 APFloat &LHS_r = LHS.getComplexFloatReal();
2071 APFloat &LHS_i = LHS.getComplexFloatImag();
2072 APFloat &RHS_r = RHS.getComplexFloatReal();
2073 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002074
Daniel Dunbar3f279872009-01-29 01:32:56 +00002075 APFloat Tmp = LHS_r;
2076 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2077 Result.getComplexFloatReal() = Tmp;
2078 Tmp = LHS_i;
2079 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2080 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2081
2082 Tmp = LHS_r;
2083 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2084 Result.getComplexFloatImag() = Tmp;
2085 Tmp = LHS_i;
2086 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2087 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2088 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002089 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002090 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002091 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2092 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002093 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002094 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2095 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2096 }
2097 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002098 }
2099
John McCallf4cf1a12010-05-07 17:22:02 +00002100 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002101}
2102
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002103//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002104// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002105//===----------------------------------------------------------------------===//
2106
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002107/// Evaluate - Return true if this is a constant which we can fold using
Chris Lattner019f4e82008-10-06 05:28:25 +00002108/// any crazy technique (that has nothing to do with language standards) that
2109/// we want to. If this function returns true, it returns the folded constant
2110/// in Result.
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002111bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2112 EvalInfo Info(Ctx, Result);
Anders Carlsson54da0492008-11-30 16:38:33 +00002113
Nate Begeman59b5da62009-01-18 03:20:47 +00002114 if (getType()->isVectorType()) {
2115 if (!EvaluateVector(this, Result.Val, Info))
2116 return false;
2117 } else if (getType()->isIntegerType()) {
Daniel Dunbar30c37f42009-02-19 20:17:33 +00002118 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002119 return false;
Daniel Dunbar89588912009-02-26 20:52:22 +00002120 } else if (getType()->hasPointerRepresentation()) {
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002121 if (!EvaluatePointer(this, Result.Val, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002122 return false;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002123 } else if (getType()->isRealFloatingType()) {
2124 llvm::APFloat f(0.0);
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002125 if (!EvaluateFloat(this, f, Info))
2126 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002128 Result.Val = APValue(f);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002129 } else if (getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002130 ComplexValue c;
2131 if (!EvaluateComplex(this, c, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002132 return false;
John McCallf4cf1a12010-05-07 17:22:02 +00002133 c.moveInto(Result.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002134 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002135 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002136
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002137 return true;
2138}
2139
Mike Stump660e6f72009-10-26 23:05:19 +00002140bool Expr::EvaluateAsAny(EvalResult &Result, ASTContext &Ctx) const {
2141 EvalInfo Info(Ctx, Result, true);
2142
2143 if (getType()->isVectorType()) {
2144 if (!EvaluateVector(this, Result.Val, Info))
2145 return false;
2146 } else if (getType()->isIntegerType()) {
2147 if (!IntExprEvaluator(Info, Result.Val).Visit(const_cast<Expr*>(this)))
2148 return false;
2149 } else if (getType()->hasPointerRepresentation()) {
2150 if (!EvaluatePointer(this, Result.Val, Info))
2151 return false;
2152 } else if (getType()->isRealFloatingType()) {
2153 llvm::APFloat f(0.0);
2154 if (!EvaluateFloat(this, f, Info))
2155 return false;
2156
2157 Result.Val = APValue(f);
2158 } else if (getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002159 ComplexValue c;
2160 if (!EvaluateComplex(this, c, Info))
Mike Stump660e6f72009-10-26 23:05:19 +00002161 return false;
John McCallf4cf1a12010-05-07 17:22:02 +00002162 c.moveInto(Result.Val);
Mike Stump660e6f72009-10-26 23:05:19 +00002163 } else
2164 return false;
2165
2166 return true;
2167}
2168
John McCallcd7a4452010-01-05 23:42:56 +00002169bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2170 EvalResult Scratch;
2171 EvalInfo Info(Ctx, Scratch);
2172
2173 return HandleConversionToBool(this, Result, Info);
2174}
2175
Anders Carlsson1b782762009-04-10 04:54:13 +00002176bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2177 EvalInfo Info(Ctx, Result);
2178
2179 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2180}
2181
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002182bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2183 EvalInfo Info(Ctx, Result, true);
2184
2185 return EvaluateLValue(this, Result.Val, Info) && !Result.HasSideEffects;
2186}
2187
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002188/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002189/// folded, but discard the result.
2190bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002191 EvalResult Result;
2192 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002193}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002194
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002195bool Expr::HasSideEffects(ASTContext &Ctx) const {
2196 Expr::EvalResult Result;
2197 EvalInfo Info(Ctx, Result);
2198 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2199}
2200
Anders Carlsson51fe9962008-11-22 21:04:56 +00002201APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002202 EvalResult EvalResult;
2203 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00002204 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002205 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002206 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002207
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002208 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002209}
John McCalld905f5a2010-05-07 05:32:02 +00002210
2211/// isIntegerConstantExpr - this recursive routine will test if an expression is
2212/// an integer constant expression.
2213
2214/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2215/// comma, etc
2216///
2217/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2218/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2219/// cast+dereference.
2220
2221// CheckICE - This function does the fundamental ICE checking: the returned
2222// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2223// Note that to reduce code duplication, this helper does no evaluation
2224// itself; the caller checks whether the expression is evaluatable, and
2225// in the rare cases where CheckICE actually cares about the evaluated
2226// value, it calls into Evalute.
2227//
2228// Meanings of Val:
2229// 0: This expression is an ICE if it can be evaluated by Evaluate.
2230// 1: This expression is not an ICE, but if it isn't evaluated, it's
2231// a legal subexpression for an ICE. This return value is used to handle
2232// the comma operator in C99 mode.
2233// 2: This expression is not an ICE, and is not a legal subexpression for one.
2234
2235struct ICEDiag {
2236 unsigned Val;
2237 SourceLocation Loc;
2238
2239 public:
2240 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2241 ICEDiag() : Val(0) {}
2242};
2243
2244ICEDiag NoDiag() { return ICEDiag(); }
2245
2246static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2247 Expr::EvalResult EVResult;
2248 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2249 !EVResult.Val.isInt()) {
2250 return ICEDiag(2, E->getLocStart());
2251 }
2252 return NoDiag();
2253}
2254
2255static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2256 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
2257 if (!E->getType()->isIntegralType()) {
2258 return ICEDiag(2, E->getLocStart());
2259 }
2260
2261 switch (E->getStmtClass()) {
2262#define STMT(Node, Base) case Expr::Node##Class:
2263#define EXPR(Node, Base)
2264#include "clang/AST/StmtNodes.inc"
2265 case Expr::PredefinedExprClass:
2266 case Expr::FloatingLiteralClass:
2267 case Expr::ImaginaryLiteralClass:
2268 case Expr::StringLiteralClass:
2269 case Expr::ArraySubscriptExprClass:
2270 case Expr::MemberExprClass:
2271 case Expr::CompoundAssignOperatorClass:
2272 case Expr::CompoundLiteralExprClass:
2273 case Expr::ExtVectorElementExprClass:
2274 case Expr::InitListExprClass:
2275 case Expr::DesignatedInitExprClass:
2276 case Expr::ImplicitValueInitExprClass:
2277 case Expr::ParenListExprClass:
2278 case Expr::VAArgExprClass:
2279 case Expr::AddrLabelExprClass:
2280 case Expr::StmtExprClass:
2281 case Expr::CXXMemberCallExprClass:
2282 case Expr::CXXDynamicCastExprClass:
2283 case Expr::CXXTypeidExprClass:
2284 case Expr::CXXNullPtrLiteralExprClass:
2285 case Expr::CXXThisExprClass:
2286 case Expr::CXXThrowExprClass:
2287 case Expr::CXXNewExprClass:
2288 case Expr::CXXDeleteExprClass:
2289 case Expr::CXXPseudoDestructorExprClass:
2290 case Expr::UnresolvedLookupExprClass:
2291 case Expr::DependentScopeDeclRefExprClass:
2292 case Expr::CXXConstructExprClass:
2293 case Expr::CXXBindTemporaryExprClass:
2294 case Expr::CXXBindReferenceExprClass:
2295 case Expr::CXXExprWithTemporariesClass:
2296 case Expr::CXXTemporaryObjectExprClass:
2297 case Expr::CXXUnresolvedConstructExprClass:
2298 case Expr::CXXDependentScopeMemberExprClass:
2299 case Expr::UnresolvedMemberExprClass:
2300 case Expr::ObjCStringLiteralClass:
2301 case Expr::ObjCEncodeExprClass:
2302 case Expr::ObjCMessageExprClass:
2303 case Expr::ObjCSelectorExprClass:
2304 case Expr::ObjCProtocolExprClass:
2305 case Expr::ObjCIvarRefExprClass:
2306 case Expr::ObjCPropertyRefExprClass:
2307 case Expr::ObjCImplicitSetterGetterRefExprClass:
2308 case Expr::ObjCSuperExprClass:
2309 case Expr::ObjCIsaExprClass:
2310 case Expr::ShuffleVectorExprClass:
2311 case Expr::BlockExprClass:
2312 case Expr::BlockDeclRefExprClass:
2313 case Expr::NoStmtClass:
2314 return ICEDiag(2, E->getLocStart());
2315
2316 case Expr::GNUNullExprClass:
2317 // GCC considers the GNU __null value to be an integral constant expression.
2318 return NoDiag();
2319
2320 case Expr::ParenExprClass:
2321 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2322 case Expr::IntegerLiteralClass:
2323 case Expr::CharacterLiteralClass:
2324 case Expr::CXXBoolLiteralExprClass:
2325 case Expr::CXXZeroInitValueExprClass:
2326 case Expr::TypesCompatibleExprClass:
2327 case Expr::UnaryTypeTraitExprClass:
2328 return NoDiag();
2329 case Expr::CallExprClass:
2330 case Expr::CXXOperatorCallExprClass: {
2331 const CallExpr *CE = cast<CallExpr>(E);
2332 if (CE->isBuiltinCall(Ctx))
2333 return CheckEvalInICE(E, Ctx);
2334 return ICEDiag(2, E->getLocStart());
2335 }
2336 case Expr::DeclRefExprClass:
2337 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2338 return NoDiag();
2339 if (Ctx.getLangOptions().CPlusPlus &&
2340 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2341 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2342
2343 // Parameter variables are never constants. Without this check,
2344 // getAnyInitializer() can find a default argument, which leads
2345 // to chaos.
2346 if (isa<ParmVarDecl>(D))
2347 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2348
2349 // C++ 7.1.5.1p2
2350 // A variable of non-volatile const-qualified integral or enumeration
2351 // type initialized by an ICE can be used in ICEs.
2352 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2353 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2354 if (Quals.hasVolatile() || !Quals.hasConst())
2355 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2356
2357 // Look for a declaration of this variable that has an initializer.
2358 const VarDecl *ID = 0;
2359 const Expr *Init = Dcl->getAnyInitializer(ID);
2360 if (Init) {
2361 if (ID->isInitKnownICE()) {
2362 // We have already checked whether this subexpression is an
2363 // integral constant expression.
2364 if (ID->isInitICE())
2365 return NoDiag();
2366 else
2367 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2368 }
2369
2370 // It's an ICE whether or not the definition we found is
2371 // out-of-line. See DR 721 and the discussion in Clang PR
2372 // 6206 for details.
2373
2374 if (Dcl->isCheckingICE()) {
2375 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2376 }
2377
2378 Dcl->setCheckingICE();
2379 ICEDiag Result = CheckICE(Init, Ctx);
2380 // Cache the result of the ICE test.
2381 Dcl->setInitKnownICE(Result.Val == 0);
2382 return Result;
2383 }
2384 }
2385 }
2386 return ICEDiag(2, E->getLocStart());
2387 case Expr::UnaryOperatorClass: {
2388 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2389 switch (Exp->getOpcode()) {
2390 case UnaryOperator::PostInc:
2391 case UnaryOperator::PostDec:
2392 case UnaryOperator::PreInc:
2393 case UnaryOperator::PreDec:
2394 case UnaryOperator::AddrOf:
2395 case UnaryOperator::Deref:
2396 return ICEDiag(2, E->getLocStart());
2397 case UnaryOperator::Extension:
2398 case UnaryOperator::LNot:
2399 case UnaryOperator::Plus:
2400 case UnaryOperator::Minus:
2401 case UnaryOperator::Not:
2402 case UnaryOperator::Real:
2403 case UnaryOperator::Imag:
2404 return CheckICE(Exp->getSubExpr(), Ctx);
2405 case UnaryOperator::OffsetOf:
2406 break;
2407 }
2408
2409 // OffsetOf falls through here.
2410 }
2411 case Expr::OffsetOfExprClass: {
2412 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2413 // Evaluate matches the proposed gcc behavior for cases like
2414 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2415 // compliance: we should warn earlier for offsetof expressions with
2416 // array subscripts that aren't ICEs, and if the array subscripts
2417 // are ICEs, the value of the offsetof must be an integer constant.
2418 return CheckEvalInICE(E, Ctx);
2419 }
2420 case Expr::SizeOfAlignOfExprClass: {
2421 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2422 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2423 return ICEDiag(2, E->getLocStart());
2424 return NoDiag();
2425 }
2426 case Expr::BinaryOperatorClass: {
2427 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2428 switch (Exp->getOpcode()) {
2429 case BinaryOperator::PtrMemD:
2430 case BinaryOperator::PtrMemI:
2431 case BinaryOperator::Assign:
2432 case BinaryOperator::MulAssign:
2433 case BinaryOperator::DivAssign:
2434 case BinaryOperator::RemAssign:
2435 case BinaryOperator::AddAssign:
2436 case BinaryOperator::SubAssign:
2437 case BinaryOperator::ShlAssign:
2438 case BinaryOperator::ShrAssign:
2439 case BinaryOperator::AndAssign:
2440 case BinaryOperator::XorAssign:
2441 case BinaryOperator::OrAssign:
2442 return ICEDiag(2, E->getLocStart());
2443
2444 case BinaryOperator::Mul:
2445 case BinaryOperator::Div:
2446 case BinaryOperator::Rem:
2447 case BinaryOperator::Add:
2448 case BinaryOperator::Sub:
2449 case BinaryOperator::Shl:
2450 case BinaryOperator::Shr:
2451 case BinaryOperator::LT:
2452 case BinaryOperator::GT:
2453 case BinaryOperator::LE:
2454 case BinaryOperator::GE:
2455 case BinaryOperator::EQ:
2456 case BinaryOperator::NE:
2457 case BinaryOperator::And:
2458 case BinaryOperator::Xor:
2459 case BinaryOperator::Or:
2460 case BinaryOperator::Comma: {
2461 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2462 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2463 if (Exp->getOpcode() == BinaryOperator::Div ||
2464 Exp->getOpcode() == BinaryOperator::Rem) {
2465 // Evaluate gives an error for undefined Div/Rem, so make sure
2466 // we don't evaluate one.
2467 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2468 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2469 if (REval == 0)
2470 return ICEDiag(1, E->getLocStart());
2471 if (REval.isSigned() && REval.isAllOnesValue()) {
2472 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2473 if (LEval.isMinSignedValue())
2474 return ICEDiag(1, E->getLocStart());
2475 }
2476 }
2477 }
2478 if (Exp->getOpcode() == BinaryOperator::Comma) {
2479 if (Ctx.getLangOptions().C99) {
2480 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2481 // if it isn't evaluated.
2482 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2483 return ICEDiag(1, E->getLocStart());
2484 } else {
2485 // In both C89 and C++, commas in ICEs are illegal.
2486 return ICEDiag(2, E->getLocStart());
2487 }
2488 }
2489 if (LHSResult.Val >= RHSResult.Val)
2490 return LHSResult;
2491 return RHSResult;
2492 }
2493 case BinaryOperator::LAnd:
2494 case BinaryOperator::LOr: {
2495 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2496 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2497 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2498 // Rare case where the RHS has a comma "side-effect"; we need
2499 // to actually check the condition to see whether the side
2500 // with the comma is evaluated.
2501 if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
2502 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2503 return RHSResult;
2504 return NoDiag();
2505 }
2506
2507 if (LHSResult.Val >= RHSResult.Val)
2508 return LHSResult;
2509 return RHSResult;
2510 }
2511 }
2512 }
2513 case Expr::ImplicitCastExprClass:
2514 case Expr::CStyleCastExprClass:
2515 case Expr::CXXFunctionalCastExprClass:
2516 case Expr::CXXStaticCastExprClass:
2517 case Expr::CXXReinterpretCastExprClass:
2518 case Expr::CXXConstCastExprClass: {
2519 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
2520 if (SubExpr->getType()->isIntegralType())
2521 return CheckICE(SubExpr, Ctx);
2522 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2523 return NoDiag();
2524 return ICEDiag(2, E->getLocStart());
2525 }
2526 case Expr::ConditionalOperatorClass: {
2527 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2528 // If the condition (ignoring parens) is a __builtin_constant_p call,
2529 // then only the true side is actually considered in an integer constant
2530 // expression, and it is fully evaluated. This is an important GNU
2531 // extension. See GCC PR38377 for discussion.
2532 if (const CallExpr *CallCE
2533 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2534 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2535 Expr::EvalResult EVResult;
2536 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2537 !EVResult.Val.isInt()) {
2538 return ICEDiag(2, E->getLocStart());
2539 }
2540 return NoDiag();
2541 }
2542 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2543 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2544 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2545 if (CondResult.Val == 2)
2546 return CondResult;
2547 if (TrueResult.Val == 2)
2548 return TrueResult;
2549 if (FalseResult.Val == 2)
2550 return FalseResult;
2551 if (CondResult.Val == 1)
2552 return CondResult;
2553 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2554 return NoDiag();
2555 // Rare case where the diagnostics depend on which side is evaluated
2556 // Note that if we get here, CondResult is 0, and at least one of
2557 // TrueResult and FalseResult is non-zero.
2558 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2559 return FalseResult;
2560 }
2561 return TrueResult;
2562 }
2563 case Expr::CXXDefaultArgExprClass:
2564 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2565 case Expr::ChooseExprClass: {
2566 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2567 }
2568 }
2569
2570 // Silence a GCC warning
2571 return ICEDiag(2, E->getLocStart());
2572}
2573
2574bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2575 SourceLocation *Loc, bool isEvaluated) const {
2576 ICEDiag d = CheckICE(this, Ctx);
2577 if (d.Val != 0) {
2578 if (Loc) *Loc = d.Loc;
2579 return false;
2580 }
2581 EvalResult EvalResult;
2582 if (!Evaluate(EvalResult, Ctx))
2583 llvm_unreachable("ICE cannot be evaluated!");
2584 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2585 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2586 Result = EvalResult.Val.getInt();
2587 return true;
2588}