blob: b74b327c9cac42e37b07ed415624bf2757e96e67 [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
John McCall42c8f872010-05-10 23:27:23 +000051 EvalInfo(ASTContext &ctx, Expr::EvalResult& evalresult)
52 : Ctx(ctx), EvalResult(evalresult) {}
Chris Lattner87eae5e2008-07-11 22:52:41 +000053};
54
John McCallf4cf1a12010-05-07 17:22:02 +000055namespace {
56 struct ComplexValue {
57 private:
58 bool IsInt;
59
60 public:
61 APSInt IntReal, IntImag;
62 APFloat FloatReal, FloatImag;
63
64 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
65
66 void makeComplexFloat() { IsInt = false; }
67 bool isComplexFloat() const { return !IsInt; }
68 APFloat &getComplexFloatReal() { return FloatReal; }
69 APFloat &getComplexFloatImag() { return FloatImag; }
70
71 void makeComplexInt() { IsInt = true; }
72 bool isComplexInt() const { return IsInt; }
73 APSInt &getComplexIntReal() { return IntReal; }
74 APSInt &getComplexIntImag() { return IntImag; }
75
76 void moveInto(APValue &v) {
77 if (isComplexFloat())
78 v = APValue(FloatReal, FloatImag);
79 else
80 v = APValue(IntReal, IntImag);
81 }
82 };
John McCallefdb83e2010-05-07 21:00:08 +000083
84 struct LValue {
85 Expr *Base;
86 CharUnits Offset;
87
88 Expr *getLValueBase() { return Base; }
89 CharUnits getLValueOffset() { return Offset; }
90
91 void moveInto(APValue &v) {
92 v = APValue(Base, Offset);
93 }
94 };
John McCallf4cf1a12010-05-07 17:22:02 +000095}
Chris Lattner87eae5e2008-07-11 22:52:41 +000096
John McCallefdb83e2010-05-07 21:00:08 +000097static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
98static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +000099static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000100static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
101 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000102static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000103static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000104
105//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000106// Misc utilities
107//===----------------------------------------------------------------------===//
108
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000109static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000110 if (!E) return true;
111
112 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
113 if (isa<FunctionDecl>(DRE->getDecl()))
114 return true;
115 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
116 return VD->hasGlobalStorage();
117 return false;
118 }
119
120 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
121 return CLE->isFileScope();
122
123 return true;
124}
125
John McCallefdb83e2010-05-07 21:00:08 +0000126static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
127 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000128
John McCall35542832010-05-07 21:34:32 +0000129 // A null base expression indicates a null pointer. These are always
130 // evaluatable, and they are false unless the offset is zero.
131 if (!Base) {
132 Result = !Value.Offset.isZero();
133 return true;
134 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000135
John McCall42c8f872010-05-10 23:27:23 +0000136 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000137 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000138
John McCall35542832010-05-07 21:34:32 +0000139 // We have a non-null base expression. These are generally known to
140 // be true, but if it'a decl-ref to a weak symbol it can be null at
141 // runtime.
John McCall35542832010-05-07 21:34:32 +0000142 Result = true;
143
144 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000145 if (!DeclRef)
146 return true;
147
John McCall35542832010-05-07 21:34:32 +0000148 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000149 const ValueDecl* Decl = DeclRef->getDecl();
150 if (Decl->hasAttr<WeakAttr>() ||
151 Decl->hasAttr<WeakRefAttr>() ||
152 Decl->hasAttr<WeakImportAttr>())
153 return false;
154
Eli Friedman5bc86102009-06-14 02:17:33 +0000155 return true;
156}
157
John McCallcd7a4452010-01-05 23:42:56 +0000158static bool HandleConversionToBool(const Expr* E, bool& Result,
159 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000160 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000161 APSInt IntResult;
162 if (!EvaluateInteger(E, IntResult, Info))
163 return false;
164 Result = IntResult != 0;
165 return true;
166 } else if (E->getType()->isRealFloatingType()) {
167 APFloat FloatResult(0.0);
168 if (!EvaluateFloat(E, FloatResult, Info))
169 return false;
170 Result = !FloatResult.isZero();
171 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000172 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000173 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000174 if (!EvaluatePointer(E, PointerResult, Info))
175 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000176 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000177 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000178 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000179 if (!EvaluateComplex(E, ComplexResult, Info))
180 return false;
181 if (ComplexResult.isComplexFloat()) {
182 Result = !ComplexResult.getComplexFloatReal().isZero() ||
183 !ComplexResult.getComplexFloatImag().isZero();
184 } else {
185 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
186 ComplexResult.getComplexIntImag().getBoolValue();
187 }
188 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000189 }
190
191 return false;
192}
193
Mike Stump1eb44332009-09-09 15:08:12 +0000194static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000195 APFloat &Value, ASTContext &Ctx) {
196 unsigned DestWidth = Ctx.getIntWidth(DestType);
197 // Determine whether we are converting to unsigned or signed.
198 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000200 // FIXME: Warning for overflow.
201 uint64_t Space[4];
202 bool ignored;
203 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
204 llvm::APFloat::rmTowardZero, &ignored);
205 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
206}
207
Mike Stump1eb44332009-09-09 15:08:12 +0000208static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000209 APFloat &Value, ASTContext &Ctx) {
210 bool ignored;
211 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000212 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000213 APFloat::rmNearestTiesToEven, &ignored);
214 return Result;
215}
216
Mike Stump1eb44332009-09-09 15:08:12 +0000217static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000218 APSInt &Value, ASTContext &Ctx) {
219 unsigned DestWidth = Ctx.getIntWidth(DestType);
220 APSInt Result = Value;
221 // Figure out if this is a truncate, extend or noop cast.
222 // If the input is signed, do a sign extend, noop, or truncate.
223 Result.extOrTrunc(DestWidth);
224 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
225 return Result;
226}
227
Mike Stump1eb44332009-09-09 15:08:12 +0000228static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000229 APSInt &Value, ASTContext &Ctx) {
230
231 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
232 Result.convertFromAPInt(Value, Value.isSigned(),
233 APFloat::rmNearestTiesToEven);
234 return Result;
235}
236
Mike Stumpc4c90452009-10-27 22:09:17 +0000237namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000238class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000239 : public StmtVisitor<HasSideEffect, bool> {
240 EvalInfo &Info;
241public:
242
243 HasSideEffect(EvalInfo &info) : Info(info) {}
244
245 // Unhandled nodes conservatively default to having side effects.
246 bool VisitStmt(Stmt *S) {
247 return true;
248 }
249
250 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
251 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000252 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000253 return true;
254 return false;
255 }
256 // We don't want to evaluate BlockExprs multiple times, as they generate
257 // a ton of code.
258 bool VisitBlockExpr(BlockExpr *E) { return true; }
259 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
260 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
261 { return Visit(E->getInitializer()); }
262 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
263 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
264 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
265 bool VisitStringLiteral(StringLiteral *E) { return false; }
266 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
267 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
268 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000269 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000270 bool VisitChooseExpr(ChooseExpr *E)
271 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
272 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
273 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000274 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000275 bool VisitBinaryOperator(BinaryOperator *E)
276 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000277 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
278 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
279 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
280 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
281 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000282 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000283 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000284 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000285 }
286 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000287
288 // Has side effects if any element does.
289 bool VisitInitListExpr(InitListExpr *E) {
290 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
291 if (Visit(E->getInit(i))) return true;
292 return false;
293 }
Mike Stumpc4c90452009-10-27 22:09:17 +0000294};
295
Mike Stumpc4c90452009-10-27 22:09:17 +0000296} // end anonymous namespace
297
Eli Friedman4efaa272008-11-12 09:44:48 +0000298//===----------------------------------------------------------------------===//
299// LValue Evaluation
300//===----------------------------------------------------------------------===//
301namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000302class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000303 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000304 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000305 LValue &Result;
306
307 bool Success(Expr *E) {
308 Result.Base = E;
309 Result.Offset = CharUnits::Zero();
310 return true;
311 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000312public:
Mike Stump1eb44332009-09-09 15:08:12 +0000313
John McCallefdb83e2010-05-07 21:00:08 +0000314 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
315 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000316
John McCallefdb83e2010-05-07 21:00:08 +0000317 bool VisitStmt(Stmt *S) {
318 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000319 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000320
John McCallefdb83e2010-05-07 21:00:08 +0000321 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
322 bool VisitDeclRefExpr(DeclRefExpr *E);
323 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
324 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
325 bool VisitMemberExpr(MemberExpr *E);
326 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
327 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
328 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
329 bool VisitUnaryDeref(UnaryOperator *E);
330 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000331 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000332 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000333 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000334
John McCallefdb83e2010-05-07 21:00:08 +0000335 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000336 switch (E->getCastKind()) {
337 default:
John McCallefdb83e2010-05-07 21:00:08 +0000338 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000339
340 case CastExpr::CK_NoOp:
341 return Visit(E->getSubExpr());
342 }
343 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000344 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000345};
346} // end anonymous namespace
347
John McCallefdb83e2010-05-07 21:00:08 +0000348static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
349 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000350}
351
John McCallefdb83e2010-05-07 21:00:08 +0000352bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000353 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000354 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000355 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
356 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000357 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000358 // Reference parameters can refer to anything even if they have an
359 // "initializer" in the form of a default argument.
360 if (isa<ParmVarDecl>(VD))
361 return false;
Eli Friedmand933a012009-08-29 19:09:59 +0000362 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000363 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000364 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000365 }
366
John McCallefdb83e2010-05-07 21:00:08 +0000367 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000368}
369
John McCallefdb83e2010-05-07 21:00:08 +0000370bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000371 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000372}
373
John McCallefdb83e2010-05-07 21:00:08 +0000374bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000375 QualType Ty;
376 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000377 if (!EvaluatePointer(E->getBase(), Result, Info))
378 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000379 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000380 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000381 if (!Visit(E->getBase()))
382 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000383 Ty = E->getBase()->getType();
384 }
385
Ted Kremenek6217b802009-07-29 21:53:49 +0000386 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000387 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000388
389 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
390 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000391 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000392
393 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000394 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000395
Eli Friedman4efaa272008-11-12 09:44:48 +0000396 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000397 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000398 for (RecordDecl::field_iterator Field = RD->field_begin(),
399 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000400 Field != FieldEnd; (void)++Field, ++i) {
401 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000402 break;
403 }
404
John McCallefdb83e2010-05-07 21:00:08 +0000405 Result.Offset += CharUnits::fromQuantity(RL.getFieldOffset(i) / 8);
406 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000407}
408
John McCallefdb83e2010-05-07 21:00:08 +0000409bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000410 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000411 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Anders Carlsson3068d112008-11-16 19:01:22 +0000413 APSInt Index;
414 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000415 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000416
Ken Dyck199c3d62010-01-11 17:06:35 +0000417 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000418 Result.Offset += Index.getSExtValue() * ElementSize;
419 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000420}
Eli Friedman4efaa272008-11-12 09:44:48 +0000421
John McCallefdb83e2010-05-07 21:00:08 +0000422bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
423 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000424}
425
Eli Friedman4efaa272008-11-12 09:44:48 +0000426//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000427// Pointer Evaluation
428//===----------------------------------------------------------------------===//
429
Anders Carlssonc754aa62008-07-08 05:13:58 +0000430namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000431class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000432 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000433 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000434 LValue &Result;
435
436 bool Success(Expr *E) {
437 Result.Base = E;
438 Result.Offset = CharUnits::Zero();
439 return true;
440 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000441public:
Mike Stump1eb44332009-09-09 15:08:12 +0000442
John McCallefdb83e2010-05-07 21:00:08 +0000443 PointerExprEvaluator(EvalInfo &info, LValue &Result)
444 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000445
John McCallefdb83e2010-05-07 21:00:08 +0000446 bool VisitStmt(Stmt *S) {
447 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000448 }
449
John McCallefdb83e2010-05-07 21:00:08 +0000450 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000451
John McCallefdb83e2010-05-07 21:00:08 +0000452 bool VisitBinaryOperator(const BinaryOperator *E);
453 bool VisitCastExpr(CastExpr* E);
454 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000455 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000456 bool VisitUnaryAddrOf(const UnaryOperator *E);
457 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
458 { return Success(E); }
459 bool VisitAddrLabelExpr(AddrLabelExpr *E)
460 { return Success(E); }
461 bool VisitCallExpr(CallExpr *E);
462 bool VisitBlockExpr(BlockExpr *E) {
Mike Stumpb83d2872009-02-19 22:01:56 +0000463 if (!E->hasBlockDeclRefExprs())
John McCallefdb83e2010-05-07 21:00:08 +0000464 return Success(E);
465 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000466 }
John McCallefdb83e2010-05-07 21:00:08 +0000467 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
468 { return Success((Expr*)0); }
469 bool VisitConditionalOperator(ConditionalOperator *E);
470 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000471 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000472 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
473 { return Success((Expr*)0); }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000474 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000475};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000476} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000477
John McCallefdb83e2010-05-07 21:00:08 +0000478static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000479 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000480 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000481}
482
John McCallefdb83e2010-05-07 21:00:08 +0000483bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000484 if (E->getOpcode() != BinaryOperator::Add &&
485 E->getOpcode() != BinaryOperator::Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000486 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000487
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000488 const Expr *PExp = E->getLHS();
489 const Expr *IExp = E->getRHS();
490 if (IExp->getType()->isPointerType())
491 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000492
John McCallefdb83e2010-05-07 21:00:08 +0000493 if (!EvaluatePointer(PExp, Result, Info))
494 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000495
John McCallefdb83e2010-05-07 21:00:08 +0000496 llvm::APSInt Offset;
497 if (!EvaluateInteger(IExp, Offset, Info))
498 return false;
499 int64_t AdditionalOffset
500 = Offset.isSigned() ? Offset.getSExtValue()
501 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000502
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000503 // Compute the new offset in the appropriate width.
504
505 QualType PointeeType =
506 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000507 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000508
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000509 // Explicitly handle GNU void* and function pointer arithmetic extensions.
510 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000511 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000512 else
John McCallefdb83e2010-05-07 21:00:08 +0000513 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000514
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000515 if (E->getOpcode() == BinaryOperator::Add)
John McCallefdb83e2010-05-07 21:00:08 +0000516 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000517 else
John McCallefdb83e2010-05-07 21:00:08 +0000518 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000519
John McCallefdb83e2010-05-07 21:00:08 +0000520 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000521}
Eli Friedman4efaa272008-11-12 09:44:48 +0000522
John McCallefdb83e2010-05-07 21:00:08 +0000523bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
524 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000525}
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000527
John McCallefdb83e2010-05-07 21:00:08 +0000528bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000529 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000530
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000531 switch (E->getCastKind()) {
532 default:
533 break;
534
535 case CastExpr::CK_Unknown: {
536 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
537
538 // Check for pointer->pointer cast
539 if (SubExpr->getType()->isPointerType() ||
540 SubExpr->getType()->isObjCObjectPointerType() ||
541 SubExpr->getType()->isNullPtrType() ||
542 SubExpr->getType()->isBlockPointerType())
543 return Visit(SubExpr);
544
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000545 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
John McCallefdb83e2010-05-07 21:00:08 +0000546 APValue Value;
547 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000548 break;
549
John McCallefdb83e2010-05-07 21:00:08 +0000550 if (Value.isInt()) {
551 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
552 Result.Base = 0;
553 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
554 return true;
555 } else {
556 Result.Base = Value.getLValueBase();
557 Result.Offset = Value.getLValueOffset();
558 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000559 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000560 }
561 break;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000562 }
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000564 case CastExpr::CK_NoOp:
565 case CastExpr::CK_BitCast:
Douglas Gregore39a3892010-07-13 23:17:26 +0000566 case CastExpr::CK_LValueBitCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000567 case CastExpr::CK_AnyPointerToObjCPointerCast:
568 case CastExpr::CK_AnyPointerToBlockPointerCast:
569 return Visit(SubExpr);
570
571 case CastExpr::CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000572 APValue Value;
573 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000574 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000575
John McCallefdb83e2010-05-07 21:00:08 +0000576 if (Value.isInt()) {
577 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
578 Result.Base = 0;
579 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
580 return true;
581 } else {
582 // Cast is of an lvalue, no need to change value.
583 Result.Base = Value.getLValueBase();
584 Result.Offset = Value.getLValueOffset();
585 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000586 }
587 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000588 case CastExpr::CK_ArrayToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000589 case CastExpr::CK_FunctionToPointerDecay:
590 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000591 }
592
John McCallefdb83e2010-05-07 21:00:08 +0000593 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000594}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000595
John McCallefdb83e2010-05-07 21:00:08 +0000596bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000597 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000598 Builtin::BI__builtin___CFStringMakeConstantString ||
599 E->isBuiltinCall(Info.Ctx) ==
600 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000601 return Success(E);
602 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000603}
604
John McCallefdb83e2010-05-07 21:00:08 +0000605bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000606 bool BoolResult;
607 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000608 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000609
610 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000611 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000612}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000613
614//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000615// Vector Evaluation
616//===----------------------------------------------------------------------===//
617
618namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000619 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000620 : public StmtVisitor<VectorExprEvaluator, APValue> {
621 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000622 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000623 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000624
Nate Begeman59b5da62009-01-18 03:20:47 +0000625 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Nate Begeman59b5da62009-01-18 03:20:47 +0000627 APValue VisitStmt(Stmt *S) {
628 return APValue();
629 }
Mike Stump1eb44332009-09-09 15:08:12 +0000630
Eli Friedman91110ee2009-02-23 04:23:56 +0000631 APValue VisitParenExpr(ParenExpr *E)
632 { return Visit(E->getSubExpr()); }
633 APValue VisitUnaryExtension(const UnaryOperator *E)
634 { return Visit(E->getSubExpr()); }
635 APValue VisitUnaryPlus(const UnaryOperator *E)
636 { return Visit(E->getSubExpr()); }
637 APValue VisitUnaryReal(const UnaryOperator *E)
638 { return Visit(E->getSubExpr()); }
639 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
640 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000641 APValue VisitCastExpr(const CastExpr* E);
642 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
643 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000644 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000645 APValue VisitChooseExpr(const ChooseExpr *E)
646 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000647 APValue VisitUnaryImag(const UnaryOperator *E);
648 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000649 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000650 // shufflevector, ExtVectorElementExpr
651 // (Note that these require implementing conversions
652 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000653 };
654} // end anonymous namespace
655
656static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
657 if (!E->getType()->isVectorType())
658 return false;
659 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
660 return !Result.isUninit();
661}
662
663APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000664 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000665 QualType EltTy = VTy->getElementType();
666 unsigned NElts = VTy->getNumElements();
667 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Nate Begeman59b5da62009-01-18 03:20:47 +0000669 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000670 QualType SETy = SE->getType();
671 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000672
Nate Begemane8c9e922009-06-26 18:22:18 +0000673 // Check for vector->vector bitcast and scalar->vector splat.
674 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000675 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000676 } else if (SETy->isIntegerType()) {
677 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000678 if (!EvaluateInteger(SE, IntResult, Info))
679 return APValue();
680 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000681 } else if (SETy->isRealFloatingType()) {
682 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000683 if (!EvaluateFloat(SE, F, Info))
684 return APValue();
685 Result = APValue(F);
686 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000687 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000688
Nate Begemanc0b8b192009-07-01 07:50:47 +0000689 // For casts of a scalar to ExtVector, convert the scalar to the element type
690 // and splat it to all elements.
691 if (E->getType()->isExtVectorType()) {
692 if (EltTy->isIntegerType() && Result.isInt())
693 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
694 Info.Ctx));
695 else if (EltTy->isIntegerType())
696 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
697 Info.Ctx));
698 else if (EltTy->isRealFloatingType() && Result.isInt())
699 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
700 Info.Ctx));
701 else if (EltTy->isRealFloatingType())
702 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
703 Info.Ctx));
704 else
705 return APValue();
706
707 // Splat and create vector APValue.
708 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
709 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000710 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000711
712 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
713 // to the vector. To construct the APValue vector initializer, bitcast the
714 // initializing value to an APInt, and shift out the bits pertaining to each
715 // element.
716 APSInt Init;
717 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000718
Nate Begemanc0b8b192009-07-01 07:50:47 +0000719 llvm::SmallVector<APValue, 4> Elts;
720 for (unsigned i = 0; i != NElts; ++i) {
721 APSInt Tmp = Init;
722 Tmp.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Nate Begemanc0b8b192009-07-01 07:50:47 +0000724 if (EltTy->isIntegerType())
725 Elts.push_back(APValue(Tmp));
726 else if (EltTy->isRealFloatingType())
727 Elts.push_back(APValue(APFloat(Tmp)));
728 else
729 return APValue();
730
731 Init >>= EltWidth;
732 }
733 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000734}
735
Mike Stump1eb44332009-09-09 15:08:12 +0000736APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000737VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
738 return this->Visit(const_cast<Expr*>(E->getInitializer()));
739}
740
Mike Stump1eb44332009-09-09 15:08:12 +0000741APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000742VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000743 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000744 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000745 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000746
Nate Begeman59b5da62009-01-18 03:20:47 +0000747 QualType EltTy = VT->getElementType();
748 llvm::SmallVector<APValue, 4> Elements;
749
John McCalla7d6c222010-06-11 17:54:15 +0000750 // If a vector is initialized with a single element, that value
751 // becomes every element of the vector, not just the first.
752 // This is the behavior described in the IBM AltiVec documentation.
753 if (NumInits == 1) {
754 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000755 if (EltTy->isIntegerType()) {
756 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000757 if (!EvaluateInteger(E->getInit(0), sInt, Info))
758 return APValue();
759 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000760 } else {
761 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000762 if (!EvaluateFloat(E->getInit(0), f, Info))
763 return APValue();
764 InitValue = APValue(f);
765 }
766 for (unsigned i = 0; i < NumElements; i++) {
767 Elements.push_back(InitValue);
768 }
769 } else {
770 for (unsigned i = 0; i < NumElements; i++) {
771 if (EltTy->isIntegerType()) {
772 llvm::APSInt sInt(32);
773 if (i < NumInits) {
774 if (!EvaluateInteger(E->getInit(i), sInt, Info))
775 return APValue();
776 } else {
777 sInt = Info.Ctx.MakeIntValue(0, EltTy);
778 }
779 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000780 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000781 llvm::APFloat f(0.0);
782 if (i < NumInits) {
783 if (!EvaluateFloat(E->getInit(i), f, Info))
784 return APValue();
785 } else {
786 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
787 }
788 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000789 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000790 }
791 }
792 return APValue(&Elements[0], Elements.size());
793}
794
Mike Stump1eb44332009-09-09 15:08:12 +0000795APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000796VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000797 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000798 QualType EltTy = VT->getElementType();
799 APValue ZeroElement;
800 if (EltTy->isIntegerType())
801 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
802 else
803 ZeroElement =
804 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
805
806 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
807 return APValue(&Elements[0], Elements.size());
808}
809
810APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
811 bool BoolResult;
812 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
813 return APValue();
814
815 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
816
817 APValue Result;
818 if (EvaluateVector(EvalExpr, Result, Info))
819 return Result;
820 return APValue();
821}
822
Eli Friedman91110ee2009-02-23 04:23:56 +0000823APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
824 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
825 Info.EvalResult.HasSideEffects = true;
826 return GetZeroVector(E->getType());
827}
828
Nate Begeman59b5da62009-01-18 03:20:47 +0000829//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000830// Integer Evaluation
831//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000832
833namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000834class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000835 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000836 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000837 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000838public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000839 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000840 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000841
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000842 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000843 assert(E->getType()->isIntegralOrEnumerationType() &&
844 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000845 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000846 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000847 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000848 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000849 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000850 return true;
851 }
852
Daniel Dunbar131eb432009-02-19 09:06:44 +0000853 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000854 assert(E->getType()->isIntegralOrEnumerationType() &&
855 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000856 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000857 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000858 Result = APValue(APSInt(I));
859 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000860 return true;
861 }
862
863 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000864 assert(E->getType()->isIntegralOrEnumerationType() &&
865 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000866 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000867 return true;
868 }
869
Anders Carlsson82206e22008-11-30 18:14:57 +0000870 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000871 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000872 if (Info.EvalResult.Diag == 0) {
873 Info.EvalResult.DiagLoc = L;
874 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000875 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000876 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000877 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000878 }
Mike Stump1eb44332009-09-09 15:08:12 +0000879
Anders Carlssonc754aa62008-07-08 05:13:58 +0000880 //===--------------------------------------------------------------------===//
881 // Visitor Methods
882 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Chris Lattner32fea9d2008-11-12 07:43:42 +0000884 bool VisitStmt(Stmt *) {
885 assert(0 && "This should be called on integers, stmts are not integers");
886 return false;
887 }
Mike Stump1eb44332009-09-09 15:08:12 +0000888
Chris Lattner32fea9d2008-11-12 07:43:42 +0000889 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000890 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000891 }
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Chris Lattnerb542afe2008-07-11 19:10:17 +0000893 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000894
Chris Lattner4c4867e2008-07-12 00:38:25 +0000895 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000896 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000897 }
898 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000899 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000900 }
901 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarac620de2008-10-24 08:07:57 +0000902 // Per gcc docs "this built-in function ignores top level
903 // qualifiers". We need to use the canonical version to properly
904 // be able to strip CRV qualifiers from the type.
905 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
906 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump1eb44332009-09-09 15:08:12 +0000907 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar131eb432009-02-19 09:06:44 +0000908 T1.getUnqualifiedType()),
909 E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000910 }
Eli Friedman04309752009-11-24 05:28:59 +0000911
912 bool CheckReferencedDecl(const Expr *E, const Decl *D);
913 bool VisitDeclRefExpr(const DeclRefExpr *E) {
914 return CheckReferencedDecl(E, E->getDecl());
915 }
916 bool VisitMemberExpr(const MemberExpr *E) {
917 if (CheckReferencedDecl(E, E->getMemberDecl())) {
918 // Conservatively assume a MemberExpr will have side-effects
919 Info.EvalResult.HasSideEffects = true;
920 return true;
921 }
922 return false;
923 }
924
Eli Friedmanc4a26382010-02-13 00:10:10 +0000925 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000926 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000927 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000928 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000929 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000930
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000931 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000932 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
933
Anders Carlsson3068d112008-11-16 19:01:22 +0000934 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000935 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000936 }
Mike Stump1eb44332009-09-09 15:08:12 +0000937
Anders Carlsson3f704562008-12-21 22:39:40 +0000938 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000939 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000940 }
Mike Stump1eb44332009-09-09 15:08:12 +0000941
Douglas Gregored8abf12010-07-08 06:14:04 +0000942 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000943 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000944 }
945
Eli Friedman664a1042009-02-27 04:45:43 +0000946 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
947 return Success(0, E);
948 }
949
Sebastian Redl64b45f72009-01-05 20:52:13 +0000950 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Douglas Gregor5e03f9e2009-07-23 23:49:00 +0000951 return Success(E->EvaluateTrait(Info.Ctx), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000952 }
953
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000954 bool VisitChooseExpr(const ChooseExpr *E) {
955 return Visit(E->getChosenSubExpr(Info.Ctx));
956 }
957
Eli Friedman722c7172009-02-28 03:59:05 +0000958 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000959 bool VisitUnaryImag(const UnaryOperator *E);
960
Chris Lattnerfcee0012008-07-11 21:24:13 +0000961private:
Ken Dyck8b752f12010-01-27 17:10:57 +0000962 CharUnits GetAlignOfExpr(const Expr *E);
963 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +0000964 static QualType GetObjectType(const Expr *E);
965 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000966 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000967};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000968} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000969
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000970static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000971 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000972 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
973}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000974
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000975static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000976 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +0000977
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000978 APValue Val;
979 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
980 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000981 Result = Val.getInt();
982 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +0000983}
Anders Carlsson650c92f2008-07-08 15:34:11 +0000984
Eli Friedman04309752009-11-24 05:28:59 +0000985bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +0000986 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +0000987 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
988 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +0000989
990 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +0000991 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000992 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
993 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +0000994
995 if (isa<ParmVarDecl>(D))
996 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
997
Eli Friedman04309752009-11-24 05:28:59 +0000998 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +0000999 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001000 if (APValue *V = VD->getEvaluatedValue()) {
1001 if (V->isInt())
1002 return Success(V->getInt(), E);
1003 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1004 }
1005
1006 if (VD->isEvaluatingValue())
1007 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1008
1009 VD->setEvaluatingValue();
1010
Douglas Gregor78d15832009-05-26 18:54:04 +00001011 if (Visit(const_cast<Expr*>(Init))) {
1012 // Cache the evaluated value in the variable declaration.
Eli Friedmanc0131182009-12-03 20:31:57 +00001013 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001014 return true;
1015 }
1016
Eli Friedmanc0131182009-12-03 20:31:57 +00001017 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001018 return false;
1019 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001020 }
1021 }
1022
Chris Lattner4c4867e2008-07-12 00:38:25 +00001023 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001024 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001025}
1026
Chris Lattnera4d55d82008-10-06 06:40:35 +00001027/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1028/// as GCC.
1029static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1030 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001031 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001032 enum gcc_type_class {
1033 no_type_class = -1,
1034 void_type_class, integer_type_class, char_type_class,
1035 enumeral_type_class, boolean_type_class,
1036 pointer_type_class, reference_type_class, offset_type_class,
1037 real_type_class, complex_type_class,
1038 function_type_class, method_type_class,
1039 record_type_class, union_type_class,
1040 array_type_class, string_type_class,
1041 lang_type_class
1042 };
Mike Stump1eb44332009-09-09 15:08:12 +00001043
1044 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001045 // ideal, however it is what gcc does.
1046 if (E->getNumArgs() == 0)
1047 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Chris Lattnera4d55d82008-10-06 06:40:35 +00001049 QualType ArgTy = E->getArg(0)->getType();
1050 if (ArgTy->isVoidType())
1051 return void_type_class;
1052 else if (ArgTy->isEnumeralType())
1053 return enumeral_type_class;
1054 else if (ArgTy->isBooleanType())
1055 return boolean_type_class;
1056 else if (ArgTy->isCharType())
1057 return string_type_class; // gcc doesn't appear to use char_type_class
1058 else if (ArgTy->isIntegerType())
1059 return integer_type_class;
1060 else if (ArgTy->isPointerType())
1061 return pointer_type_class;
1062 else if (ArgTy->isReferenceType())
1063 return reference_type_class;
1064 else if (ArgTy->isRealType())
1065 return real_type_class;
1066 else if (ArgTy->isComplexType())
1067 return complex_type_class;
1068 else if (ArgTy->isFunctionType())
1069 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001070 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001071 return record_type_class;
1072 else if (ArgTy->isUnionType())
1073 return union_type_class;
1074 else if (ArgTy->isArrayType())
1075 return array_type_class;
1076 else if (ArgTy->isUnionType())
1077 return union_type_class;
1078 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1079 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1080 return -1;
1081}
1082
John McCall42c8f872010-05-10 23:27:23 +00001083/// Retrieves the "underlying object type" of the given expression,
1084/// as used by __builtin_object_size.
1085QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1086 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1087 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1088 return VD->getType();
1089 } else if (isa<CompoundLiteralExpr>(E)) {
1090 return E->getType();
1091 }
1092
1093 return QualType();
1094}
1095
1096bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1097 // TODO: Perhaps we should let LLVM lower this?
1098 LValue Base;
1099 if (!EvaluatePointer(E->getArg(0), Base, Info))
1100 return false;
1101
1102 // If we can prove the base is null, lower to zero now.
1103 const Expr *LVBase = Base.getLValueBase();
1104 if (!LVBase) return Success(0, E);
1105
1106 QualType T = GetObjectType(LVBase);
1107 if (T.isNull() ||
1108 T->isIncompleteType() ||
1109 !T->isObjectType() ||
1110 T->isVariablyModifiedType() ||
1111 T->isDependentType())
1112 return false;
1113
1114 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1115 CharUnits Offset = Base.getLValueOffset();
1116
1117 if (!Offset.isNegative() && Offset <= Size)
1118 Size -= Offset;
1119 else
1120 Size = CharUnits::Zero();
1121 return Success(Size.getQuantity(), E);
1122}
1123
Eli Friedmanc4a26382010-02-13 00:10:10 +00001124bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001125 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001126 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001127 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001128
1129 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001130 if (TryEvaluateBuiltinObjectSize(E))
1131 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001132
Eric Christopherb2aaf512010-01-19 22:58:35 +00001133 // If evaluating the argument has side-effects we can't determine
1134 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001135 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001136 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001137 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001138 return Success(0, E);
1139 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001140
Mike Stump64eda9e2009-10-26 18:35:08 +00001141 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1142 }
1143
Chris Lattner019f4e82008-10-06 05:28:25 +00001144 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001145 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001146
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001147 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001148 // __builtin_constant_p always has one operand: it returns true if that
1149 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001150 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001151
1152 case Builtin::BI__builtin_eh_return_data_regno: {
1153 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1154 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1155 return Success(Operand, E);
1156 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001157
1158 case Builtin::BI__builtin_expect:
1159 return Visit(E->getArg(0));
Chris Lattner019f4e82008-10-06 05:28:25 +00001160 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001161}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001162
Chris Lattnerb542afe2008-07-11 19:10:17 +00001163bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001164 if (E->getOpcode() == BinaryOperator::Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001165 if (!Visit(E->getRHS()))
1166 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001167
Eli Friedman33ef1452009-02-26 10:19:36 +00001168 // If we can't evaluate the LHS, it might have side effects;
1169 // conservatively mark it.
1170 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1171 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001172
Anders Carlsson027f62e2008-12-01 02:07:06 +00001173 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001174 }
1175
1176 if (E->isLogicalOp()) {
1177 // These need to be handled specially because the operands aren't
1178 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001179 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001180
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001181 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001182 // We were able to evaluate the LHS, see if we can get away with not
1183 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Eli Friedman33ef1452009-02-26 10:19:36 +00001184 if (lhsResult == (E->getOpcode() == BinaryOperator::LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001185 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001186
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001187 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001188 if (E->getOpcode() == BinaryOperator::LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001189 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001190 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001191 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001192 }
1193 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001194 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001195 // We can't evaluate the LHS; however, sometimes the result
1196 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Mike Stump1eb44332009-09-09 15:08:12 +00001197 if (rhsResult == (E->getOpcode() == BinaryOperator::LOr) ||
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001198 !rhsResult == (E->getOpcode() == BinaryOperator::LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001199 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001200 // must have had side effects.
1201 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001202
1203 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001204 }
1205 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001206 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001207
Eli Friedmana6afa762008-11-13 06:09:17 +00001208 return false;
1209 }
1210
Anders Carlsson286f85e2008-11-16 07:17:21 +00001211 QualType LHSTy = E->getLHS()->getType();
1212 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001213
1214 if (LHSTy->isAnyComplexType()) {
1215 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001216 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001217
1218 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1219 return false;
1220
1221 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1222 return false;
1223
1224 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001225 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001226 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001227 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001228 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1229
Daniel Dunbar4087e242009-01-29 06:43:41 +00001230 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001231 return Success((CR_r == APFloat::cmpEqual &&
1232 CR_i == APFloat::cmpEqual), E);
1233 else {
1234 assert(E->getOpcode() == BinaryOperator::NE &&
1235 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001236 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001237 CR_r == APFloat::cmpLessThan ||
1238 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001239 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001240 CR_i == APFloat::cmpLessThan ||
1241 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001242 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001243 } else {
Daniel Dunbar4087e242009-01-29 06:43:41 +00001244 if (E->getOpcode() == BinaryOperator::EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001245 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1246 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1247 else {
1248 assert(E->getOpcode() == BinaryOperator::NE &&
1249 "Invalid compex comparison.");
1250 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1251 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1252 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001253 }
1254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Anders Carlsson286f85e2008-11-16 07:17:21 +00001256 if (LHSTy->isRealFloatingType() &&
1257 RHSTy->isRealFloatingType()) {
1258 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001259
Anders Carlsson286f85e2008-11-16 07:17:21 +00001260 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1261 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Anders Carlsson286f85e2008-11-16 07:17:21 +00001263 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1264 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001265
Anders Carlsson286f85e2008-11-16 07:17:21 +00001266 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001267
Anders Carlsson286f85e2008-11-16 07:17:21 +00001268 switch (E->getOpcode()) {
1269 default:
1270 assert(0 && "Invalid binary operator!");
1271 case BinaryOperator::LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001272 return Success(CR == APFloat::cmpLessThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001273 case BinaryOperator::GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001274 return Success(CR == APFloat::cmpGreaterThan, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001275 case BinaryOperator::LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001276 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001277 case BinaryOperator::GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001278 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001279 E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001280 case BinaryOperator::EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001281 return Success(CR == APFloat::cmpEqual, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001282 case BinaryOperator::NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001283 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001284 || CR == APFloat::cmpLessThan
1285 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001286 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001287 }
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001289 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
1290 if (E->getOpcode() == BinaryOperator::Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001291 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001292 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1293 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001294
John McCallefdb83e2010-05-07 21:00:08 +00001295 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001296 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1297 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001298
Eli Friedman5bc86102009-06-14 02:17:33 +00001299 // Reject any bases from the normal codepath; we special-case comparisons
1300 // to null.
1301 if (LHSValue.getLValueBase()) {
1302 if (!E->isEqualityOp())
1303 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001304 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001305 return false;
1306 bool bres;
1307 if (!EvalPointerValueAsBool(LHSValue, bres))
1308 return false;
1309 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1310 } else if (RHSValue.getLValueBase()) {
1311 if (!E->isEqualityOp())
1312 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001313 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001314 return false;
1315 bool bres;
1316 if (!EvalPointerValueAsBool(RHSValue, bres))
1317 return false;
1318 return Success(bres ^ (E->getOpcode() == BinaryOperator::EQ), E);
1319 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001320
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001321 if (E->getOpcode() == BinaryOperator::Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001322 QualType Type = E->getLHS()->getType();
1323 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001324
Ken Dycka7305832010-01-15 12:37:54 +00001325 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001326 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001327 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001328
Ken Dycka7305832010-01-15 12:37:54 +00001329 CharUnits Diff = LHSValue.getLValueOffset() -
1330 RHSValue.getLValueOffset();
1331 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001332 }
1333 bool Result;
1334 if (E->getOpcode() == BinaryOperator::EQ) {
1335 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001336 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001337 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1338 }
1339 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001340 }
1341 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001342 if (!LHSTy->isIntegralOrEnumerationType() ||
1343 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001344 // We can't continue from here for non-integral types, and they
1345 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001346 return false;
1347 }
1348
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001349 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001350 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001351 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001352
Eli Friedman42edd0d2009-03-24 01:14:50 +00001353 APValue RHSVal;
1354 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001355 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001356
1357 // Handle cases like (unsigned long)&a + 4.
1358 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001359 CharUnits Offset = Result.getLValueOffset();
1360 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1361 RHSVal.getInt().getZExtValue());
Eli Friedman42edd0d2009-03-24 01:14:50 +00001362 if (E->getOpcode() == BinaryOperator::Add)
Ken Dycka7305832010-01-15 12:37:54 +00001363 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001364 else
Ken Dycka7305832010-01-15 12:37:54 +00001365 Offset -= AdditionalOffset;
1366 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001367 return true;
1368 }
1369
1370 // Handle cases like 4 + (unsigned long)&a
1371 if (E->getOpcode() == BinaryOperator::Add &&
1372 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001373 CharUnits Offset = RHSVal.getLValueOffset();
1374 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1375 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001376 return true;
1377 }
1378
1379 // All the following cases expect both operands to be an integer
1380 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001381 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001382
Eli Friedman42edd0d2009-03-24 01:14:50 +00001383 APSInt& RHS = RHSVal.getInt();
1384
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001385 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001386 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001387 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001388 case BinaryOperator::Mul: return Success(Result.getInt() * RHS, E);
1389 case BinaryOperator::Add: return Success(Result.getInt() + RHS, E);
1390 case BinaryOperator::Sub: return Success(Result.getInt() - RHS, E);
1391 case BinaryOperator::And: return Success(Result.getInt() & RHS, E);
1392 case BinaryOperator::Xor: return Success(Result.getInt() ^ RHS, E);
1393 case BinaryOperator::Or: return Success(Result.getInt() | RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001394 case BinaryOperator::Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001395 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001396 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001397 return Success(Result.getInt() / RHS, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001398 case BinaryOperator::Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001399 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001400 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001401 return Success(Result.getInt() % RHS, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001402 case BinaryOperator::Shl: {
Chris Lattner54176fd2008-07-12 00:14:42 +00001403 // FIXME: Warn about out of range shift amounts!
Mike Stump1eb44332009-09-09 15:08:12 +00001404 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001405 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1406 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001407 }
1408 case BinaryOperator::Shr: {
Mike Stump1eb44332009-09-09 15:08:12 +00001409 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001410 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1411 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001412 }
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001414 case BinaryOperator::LT: return Success(Result.getInt() < RHS, E);
1415 case BinaryOperator::GT: return Success(Result.getInt() > RHS, E);
1416 case BinaryOperator::LE: return Success(Result.getInt() <= RHS, E);
1417 case BinaryOperator::GE: return Success(Result.getInt() >= RHS, E);
1418 case BinaryOperator::EQ: return Success(Result.getInt() == RHS, E);
1419 case BinaryOperator::NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001420 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001421}
1422
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001423bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001424 bool Cond;
1425 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001426 return false;
1427
Nuno Lopesa25bd552008-11-16 22:06:39 +00001428 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001429}
1430
Ken Dyck8b752f12010-01-27 17:10:57 +00001431CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001432 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1433 // the result is the size of the referenced type."
1434 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1435 // result shall be the alignment of the referenced type."
1436 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1437 T = Ref->getPointeeType();
1438
Chris Lattnere9feb472009-01-24 21:09:06 +00001439 // Get information about the alignment.
1440 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001441
Eli Friedman2be58612009-05-30 21:09:44 +00001442 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001443 return CharUnits::fromQuantity(
1444 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001445}
1446
Ken Dyck8b752f12010-01-27 17:10:57 +00001447CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001448 E = E->IgnoreParens();
1449
1450 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001451 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001452 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001453 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1454 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001455
Chris Lattneraf707ab2009-01-24 21:53:27 +00001456 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001457 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1458 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001459
Chris Lattnere9feb472009-01-24 21:09:06 +00001460 return GetAlignOfType(E->getType());
1461}
1462
1463
Sebastian Redl05189992008-11-11 17:56:53 +00001464/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1465/// expression's type.
1466bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001467 // Handle alignof separately.
1468 if (!E->isSizeOf()) {
1469 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001470 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001471 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001472 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001473 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001474
Sebastian Redl05189992008-11-11 17:56:53 +00001475 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001476 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1477 // the result is the size of the referenced type."
1478 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1479 // result shall be the alignment of the referenced type."
1480 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1481 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001482
Daniel Dunbar131eb432009-02-19 09:06:44 +00001483 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1484 // extension.
1485 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1486 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001487
Chris Lattnerfcee0012008-07-11 21:24:13 +00001488 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001489 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001490 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001491
Chris Lattnere9feb472009-01-24 21:09:06 +00001492 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001493 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001494}
1495
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001496bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1497 CharUnits Result;
1498 unsigned n = E->getNumComponents();
1499 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1500 if (n == 0)
1501 return false;
1502 QualType CurrentType = E->getTypeSourceInfo()->getType();
1503 for (unsigned i = 0; i != n; ++i) {
1504 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1505 switch (ON.getKind()) {
1506 case OffsetOfExpr::OffsetOfNode::Array: {
1507 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1508 APSInt IdxResult;
1509 if (!EvaluateInteger(Idx, IdxResult, Info))
1510 return false;
1511 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1512 if (!AT)
1513 return false;
1514 CurrentType = AT->getElementType();
1515 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1516 Result += IdxResult.getSExtValue() * ElementSize;
1517 break;
1518 }
1519
1520 case OffsetOfExpr::OffsetOfNode::Field: {
1521 FieldDecl *MemberDecl = ON.getField();
1522 const RecordType *RT = CurrentType->getAs<RecordType>();
1523 if (!RT)
1524 return false;
1525 RecordDecl *RD = RT->getDecl();
1526 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1527 unsigned i = 0;
1528 // FIXME: It would be nice if we didn't have to loop here!
1529 for (RecordDecl::field_iterator Field = RD->field_begin(),
1530 FieldEnd = RD->field_end();
1531 Field != FieldEnd; (void)++Field, ++i) {
1532 if (*Field == MemberDecl)
1533 break;
1534 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001535 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1536 Result += CharUnits::fromQuantity(
1537 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001538 CurrentType = MemberDecl->getType().getNonReferenceType();
1539 break;
1540 }
1541
1542 case OffsetOfExpr::OffsetOfNode::Identifier:
1543 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001544 return false;
1545
1546 case OffsetOfExpr::OffsetOfNode::Base: {
1547 CXXBaseSpecifier *BaseSpec = ON.getBase();
1548 if (BaseSpec->isVirtual())
1549 return false;
1550
1551 // Find the layout of the class whose base we are looking into.
1552 const RecordType *RT = CurrentType->getAs<RecordType>();
1553 if (!RT)
1554 return false;
1555 RecordDecl *RD = RT->getDecl();
1556 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1557
1558 // Find the base class itself.
1559 CurrentType = BaseSpec->getType();
1560 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1561 if (!BaseRT)
1562 return false;
1563
1564 // Add the offset to the base.
1565 Result += CharUnits::fromQuantity(
1566 RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()))
1567 / Info.Ctx.getCharWidth());
1568 break;
1569 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001570 }
1571 }
1572 return Success(Result.getQuantity(), E);
1573}
1574
Chris Lattnerb542afe2008-07-11 19:10:17 +00001575bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001576 // Special case unary operators that do not need their subexpression
1577 // evaluated. offsetof/sizeof/alignof are all special.
Eli Friedman35183ac2009-02-27 06:44:11 +00001578 if (E->isOffsetOfOp()) {
1579 // The AST for offsetof is defined in such a way that we can just
1580 // directly Evaluate it as an l-value.
John McCallefdb83e2010-05-07 21:00:08 +00001581 LValue LV;
Eli Friedman35183ac2009-02-27 06:44:11 +00001582 if (!EvaluateLValue(E->getSubExpr(), LV, Info))
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001583 return false;
Eli Friedman35183ac2009-02-27 06:44:11 +00001584 if (LV.getLValueBase())
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001585 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001586 return Success(LV.getLValueOffset().getQuantity(), E);
Eli Friedman35183ac2009-02-27 06:44:11 +00001587 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001588
Eli Friedmana6afa762008-11-13 06:09:17 +00001589 if (E->getOpcode() == UnaryOperator::LNot) {
1590 // LNot's operand isn't necessarily an integer, so we handle it specially.
1591 bool bres;
1592 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1593 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001594 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001595 }
1596
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001597 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001598 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001599 return false;
1600
Chris Lattner87eae5e2008-07-11 22:52:41 +00001601 // Get the operand value into 'Result'.
1602 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001603 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001604
Chris Lattner75a48812008-07-11 22:15:16 +00001605 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001606 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001607 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1608 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001609 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner75a48812008-07-11 22:15:16 +00001610 case UnaryOperator::Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001611 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1612 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001613 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001614 case UnaryOperator::Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001615 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001616 return true;
Chris Lattner75a48812008-07-11 22:15:16 +00001617 case UnaryOperator::Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001618 if (!Result.isInt()) return false;
1619 return Success(-Result.getInt(), E);
Chris Lattner75a48812008-07-11 22:15:16 +00001620 case UnaryOperator::Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001621 if (!Result.isInt()) return false;
1622 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001623 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001624}
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Chris Lattner732b2232008-07-12 01:15:53 +00001626/// HandleCast - This is used to evaluate implicit or explicit casts where the
1627/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001628bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001629 Expr *SubExpr = E->getSubExpr();
1630 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001631 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001632
Eli Friedman4efaa272008-11-12 09:44:48 +00001633 if (DestType->isBooleanType()) {
1634 bool BoolResult;
1635 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1636 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001637 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001638 }
1639
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001640 // Handle simple integer->integer casts.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001641 if (SrcType->isIntegralOrEnumerationType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001642 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001643 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001644
Eli Friedmanbe265702009-02-20 01:15:07 +00001645 if (!Result.isInt()) {
1646 // Only allow casts of lvalues if they are lossless.
1647 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1648 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001649
Daniel Dunbardd211642009-02-19 22:24:01 +00001650 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001651 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001652 }
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Chris Lattner732b2232008-07-12 01:15:53 +00001654 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001655 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001656 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001657 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001658 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001659
Daniel Dunbardd211642009-02-19 22:24:01 +00001660 if (LV.getLValueBase()) {
1661 // Only allow based lvalue casts if they are lossless.
1662 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1663 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001664
John McCallefdb83e2010-05-07 21:00:08 +00001665 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001666 return true;
1667 }
1668
Ken Dycka7305832010-01-15 12:37:54 +00001669 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1670 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001671 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001672 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001673
Eli Friedmanbe265702009-02-20 01:15:07 +00001674 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1675 // This handles double-conversion cases, where there's both
1676 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001677 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001678 if (!EvaluateLValue(SubExpr, LV, Info))
1679 return false;
1680
1681 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1682 return false;
1683
John McCallefdb83e2010-05-07 21:00:08 +00001684 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001685 return true;
1686 }
1687
Eli Friedman1725f682009-04-22 19:23:09 +00001688 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001689 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001690 if (!EvaluateComplex(SubExpr, C, Info))
1691 return false;
1692 if (C.isComplexFloat())
1693 return Success(HandleFloatToIntCast(DestType, SrcType,
1694 C.getComplexFloatReal(), Info.Ctx),
1695 E);
1696 else
1697 return Success(HandleIntToIntCast(DestType, SrcType,
1698 C.getComplexIntReal(), Info.Ctx), E);
1699 }
Eli Friedman2217c872009-02-22 11:46:18 +00001700 // FIXME: Handle vectors
1701
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001702 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001703 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001704
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001705 APFloat F(0.0);
1706 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001707 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001709 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001710}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001711
Eli Friedman722c7172009-02-28 03:59:05 +00001712bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1713 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001714 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001715 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1716 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1717 return Success(LV.getComplexIntReal(), E);
1718 }
1719
1720 return Visit(E->getSubExpr());
1721}
1722
Eli Friedman664a1042009-02-27 04:45:43 +00001723bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001724 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001725 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001726 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1727 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1728 return Success(LV.getComplexIntImag(), E);
1729 }
1730
Eli Friedman664a1042009-02-27 04:45:43 +00001731 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1732 Info.EvalResult.HasSideEffects = true;
1733 return Success(0, E);
1734}
1735
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001736//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001737// Float Evaluation
1738//===----------------------------------------------------------------------===//
1739
1740namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001741class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001742 : public StmtVisitor<FloatExprEvaluator, bool> {
1743 EvalInfo &Info;
1744 APFloat &Result;
1745public:
1746 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1747 : Info(info), Result(result) {}
1748
1749 bool VisitStmt(Stmt *S) {
1750 return false;
1751 }
1752
1753 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001754 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001755
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001756 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001757 bool VisitBinaryOperator(const BinaryOperator *E);
1758 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001759 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001760 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001761 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001762
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001763 bool VisitChooseExpr(const ChooseExpr *E)
1764 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1765 bool VisitUnaryExtension(const UnaryOperator *E)
1766 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001767 bool VisitUnaryReal(const UnaryOperator *E);
1768 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001769
John McCallabd3a852010-05-07 22:08:54 +00001770 // FIXME: Missing: array subscript of vector, member of vector,
1771 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001772};
1773} // end anonymous namespace
1774
1775static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001776 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001777 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1778}
1779
John McCalldb7b72a2010-02-28 13:00:19 +00001780static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1781 QualType ResultTy,
1782 const Expr *Arg,
1783 bool SNaN,
1784 llvm::APFloat &Result) {
1785 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1786 if (!S) return false;
1787
1788 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1789
1790 llvm::APInt fill;
1791
1792 // Treat empty strings as if they were zero.
1793 if (S->getString().empty())
1794 fill = llvm::APInt(32, 0);
1795 else if (S->getString().getAsInteger(0, fill))
1796 return false;
1797
1798 if (SNaN)
1799 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1800 else
1801 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1802 return true;
1803}
1804
Chris Lattner019f4e82008-10-06 05:28:25 +00001805bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001806 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001807 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001808 case Builtin::BI__builtin_huge_val:
1809 case Builtin::BI__builtin_huge_valf:
1810 case Builtin::BI__builtin_huge_vall:
1811 case Builtin::BI__builtin_inf:
1812 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001813 case Builtin::BI__builtin_infl: {
1814 const llvm::fltSemantics &Sem =
1815 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001816 Result = llvm::APFloat::getInf(Sem);
1817 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001818 }
Mike Stump1eb44332009-09-09 15:08:12 +00001819
John McCalldb7b72a2010-02-28 13:00:19 +00001820 case Builtin::BI__builtin_nans:
1821 case Builtin::BI__builtin_nansf:
1822 case Builtin::BI__builtin_nansl:
1823 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1824 true, Result);
1825
Chris Lattner9e621712008-10-06 06:31:58 +00001826 case Builtin::BI__builtin_nan:
1827 case Builtin::BI__builtin_nanf:
1828 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001829 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001830 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001831 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1832 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001833
1834 case Builtin::BI__builtin_fabs:
1835 case Builtin::BI__builtin_fabsf:
1836 case Builtin::BI__builtin_fabsl:
1837 if (!EvaluateFloat(E->getArg(0), Result, Info))
1838 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001839
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001840 if (Result.isNegative())
1841 Result.changeSign();
1842 return true;
1843
Mike Stump1eb44332009-09-09 15:08:12 +00001844 case Builtin::BI__builtin_copysign:
1845 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001846 case Builtin::BI__builtin_copysignl: {
1847 APFloat RHS(0.);
1848 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1849 !EvaluateFloat(E->getArg(1), RHS, Info))
1850 return false;
1851 Result.copySign(RHS);
1852 return true;
1853 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001854 }
1855}
1856
John McCallabd3a852010-05-07 22:08:54 +00001857bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1858 ComplexValue CV;
1859 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1860 return false;
1861 Result = CV.FloatReal;
1862 return true;
1863}
1864
1865bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
1866 ComplexValue CV;
1867 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1868 return false;
1869 Result = CV.FloatImag;
1870 return true;
1871}
1872
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001873bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Nuno Lopesa468d342008-11-19 17:44:31 +00001874 if (E->getOpcode() == UnaryOperator::Deref)
1875 return false;
1876
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001877 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1878 return false;
1879
1880 switch (E->getOpcode()) {
1881 default: return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001882 case UnaryOperator::Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001883 return true;
1884 case UnaryOperator::Minus:
1885 Result.changeSign();
1886 return true;
1887 }
1888}
Chris Lattner019f4e82008-10-06 05:28:25 +00001889
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001890bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Eli Friedman7f92f032009-11-16 04:25:37 +00001891 if (E->getOpcode() == BinaryOperator::Comma) {
1892 if (!EvaluateFloat(E->getRHS(), Result, Info))
1893 return false;
1894
1895 // If we can't evaluate the LHS, it might have side effects;
1896 // conservatively mark it.
1897 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1898 Info.EvalResult.HasSideEffects = true;
1899
1900 return true;
1901 }
1902
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001903 // FIXME: Diagnostics? I really don't understand how the warnings
1904 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001905 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001906 if (!EvaluateFloat(E->getLHS(), Result, Info))
1907 return false;
1908 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1909 return false;
1910
1911 switch (E->getOpcode()) {
1912 default: return false;
1913 case BinaryOperator::Mul:
1914 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
1915 return true;
1916 case BinaryOperator::Add:
1917 Result.add(RHS, APFloat::rmNearestTiesToEven);
1918 return true;
1919 case BinaryOperator::Sub:
1920 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
1921 return true;
1922 case BinaryOperator::Div:
1923 Result.divide(RHS, APFloat::rmNearestTiesToEven);
1924 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001925 }
1926}
1927
1928bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
1929 Result = E->getValue();
1930 return true;
1931}
1932
Eli Friedman4efaa272008-11-12 09:44:48 +00001933bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
1934 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00001935
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001936 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +00001937 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001938 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00001939 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001940 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001941 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001942 return true;
1943 }
1944 if (SubExpr->getType()->isRealFloatingType()) {
1945 if (!Visit(SubExpr))
1946 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001947 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
1948 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00001949 return true;
1950 }
Eli Friedman2217c872009-02-22 11:46:18 +00001951 // FIXME: Handle complex types
Eli Friedman4efaa272008-11-12 09:44:48 +00001952
1953 return false;
1954}
1955
Douglas Gregored8abf12010-07-08 06:14:04 +00001956bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00001957 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1958 return true;
1959}
1960
Eli Friedman67f85fc2009-12-04 02:12:53 +00001961bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
1962 bool Cond;
1963 if (!HandleConversionToBool(E->getCond(), Cond, Info))
1964 return false;
1965
1966 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
1967}
1968
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001969//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001970// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001971//===----------------------------------------------------------------------===//
1972
1973namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001974class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00001975 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001976 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00001977 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001979public:
John McCallf4cf1a12010-05-07 17:22:02 +00001980 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
1981 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00001982
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001983 //===--------------------------------------------------------------------===//
1984 // Visitor Methods
1985 //===--------------------------------------------------------------------===//
1986
John McCallf4cf1a12010-05-07 17:22:02 +00001987 bool VisitStmt(Stmt *S) {
1988 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001989 }
Mike Stump1eb44332009-09-09 15:08:12 +00001990
John McCallf4cf1a12010-05-07 17:22:02 +00001991 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00001992
John McCallf4cf1a12010-05-07 17:22:02 +00001993 bool VisitImaginaryLiteral(ImaginaryLiteral *E) {
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00001994 Expr* SubExpr = E->getSubExpr();
1995
1996 if (SubExpr->getType()->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001997 Result.makeComplexFloat();
1998 APFloat &Imag = Result.FloatImag;
1999 if (!EvaluateFloat(SubExpr, Imag, Info))
2000 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002001
John McCallf4cf1a12010-05-07 17:22:02 +00002002 Result.FloatReal = APFloat(Imag.getSemantics());
2003 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002004 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00002005 assert(SubExpr->getType()->isIntegerType() &&
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002006 "Unexpected imaginary literal.");
2007
John McCallf4cf1a12010-05-07 17:22:02 +00002008 Result.makeComplexInt();
2009 APSInt &Imag = Result.IntImag;
2010 if (!EvaluateInteger(SubExpr, Imag, Info))
2011 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCallf4cf1a12010-05-07 17:22:02 +00002013 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2014 return true;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002015 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002016 }
2017
John McCallf4cf1a12010-05-07 17:22:02 +00002018 bool VisitCastExpr(CastExpr *E) {
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002019 Expr* SubExpr = E->getSubExpr();
John McCall183700f2009-09-21 23:43:11 +00002020 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002021 QualType SubType = SubExpr->getType();
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002022
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002023 if (SubType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002024 APFloat &Real = Result.FloatReal;
2025 if (!EvaluateFloat(SubExpr, Real, Info))
2026 return false;
Eli Friedman1725f682009-04-22 19:23:09 +00002027
2028 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002029 Result.makeComplexFloat();
2030 Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
2031 Result.FloatImag = APFloat(Real.getSemantics());
2032 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002033 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002034 Result.makeComplexInt();
2035 Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
2036 Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
2037 !Result.IntReal.isSigned());
2038 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002039 }
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002040 } else if (SubType->isIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002041 APSInt &Real = Result.IntReal;
2042 if (!EvaluateInteger(SubExpr, Real, Info))
2043 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002044
Eli Friedman1725f682009-04-22 19:23:09 +00002045 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002046 Result.makeComplexFloat();
2047 Result.FloatReal
2048 = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
2049 Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
2050 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002051 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002052 Result.makeComplexInt();
2053 Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
2054 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2055 return true;
Eli Friedman1725f682009-04-22 19:23:09 +00002056 }
John McCall183700f2009-09-21 23:43:11 +00002057 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002058 if (!Visit(SubExpr))
2059 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002060
2061 QualType SrcType = CT->getElementType();
2062
John McCallf4cf1a12010-05-07 17:22:02 +00002063 if (Result.isComplexFloat()) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002064 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002065 Result.makeComplexFloat();
2066 Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
2067 Result.FloatReal,
2068 Info.Ctx);
2069 Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
2070 Result.FloatImag,
2071 Info.Ctx);
2072 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002073 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002074 Result.makeComplexInt();
2075 Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
2076 Result.FloatReal,
2077 Info.Ctx);
2078 Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
2079 Result.FloatImag,
2080 Info.Ctx);
2081 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002082 }
2083 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002084 assert(Result.isComplexInt() && "Invalid evaluate result.");
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002085 if (EltType->isRealFloatingType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002086 Result.makeComplexFloat();
2087 Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
2088 Result.IntReal,
2089 Info.Ctx);
2090 Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2091 Result.IntImag,
2092 Info.Ctx);
2093 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002094 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002095 Result.makeComplexInt();
2096 Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2097 Result.IntReal,
2098 Info.Ctx);
2099 Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2100 Result.IntImag,
2101 Info.Ctx);
2102 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002103 }
2104 }
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002105 }
2106
2107 // FIXME: Handle more casts.
John McCallf4cf1a12010-05-07 17:22:02 +00002108 return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002109 }
Mike Stump1eb44332009-09-09 15:08:12 +00002110
John McCallf4cf1a12010-05-07 17:22:02 +00002111 bool VisitBinaryOperator(const BinaryOperator *E);
2112 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002113 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002114 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002115 { return Visit(E->getSubExpr()); }
2116 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedman2217c872009-02-22 11:46:18 +00002117 // conditional ?:, comma
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002118};
2119} // end anonymous namespace
2120
John McCallf4cf1a12010-05-07 17:22:02 +00002121static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2122 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002123 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002124 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002125}
2126
John McCallf4cf1a12010-05-07 17:22:02 +00002127bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2128 if (!Visit(E->getLHS()))
2129 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002130
John McCallf4cf1a12010-05-07 17:22:02 +00002131 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002132 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002133 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002134
Daniel Dunbar3f279872009-01-29 01:32:56 +00002135 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2136 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002137 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002138 default: return false;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002139 case BinaryOperator::Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002140 if (Result.isComplexFloat()) {
2141 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2142 APFloat::rmNearestTiesToEven);
2143 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2144 APFloat::rmNearestTiesToEven);
2145 } else {
2146 Result.getComplexIntReal() += RHS.getComplexIntReal();
2147 Result.getComplexIntImag() += RHS.getComplexIntImag();
2148 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002149 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002150 case BinaryOperator::Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002151 if (Result.isComplexFloat()) {
2152 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2153 APFloat::rmNearestTiesToEven);
2154 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2155 APFloat::rmNearestTiesToEven);
2156 } else {
2157 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2158 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2159 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002160 break;
2161 case BinaryOperator::Mul:
2162 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002163 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002164 APFloat &LHS_r = LHS.getComplexFloatReal();
2165 APFloat &LHS_i = LHS.getComplexFloatImag();
2166 APFloat &RHS_r = RHS.getComplexFloatReal();
2167 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002168
Daniel Dunbar3f279872009-01-29 01:32:56 +00002169 APFloat Tmp = LHS_r;
2170 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2171 Result.getComplexFloatReal() = Tmp;
2172 Tmp = LHS_i;
2173 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2174 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2175
2176 Tmp = LHS_r;
2177 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2178 Result.getComplexFloatImag() = Tmp;
2179 Tmp = LHS_i;
2180 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2181 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2182 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002183 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002184 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002185 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2186 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002187 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002188 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2189 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2190 }
2191 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002192 }
2193
John McCallf4cf1a12010-05-07 17:22:02 +00002194 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002195}
2196
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002197//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002198// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002199//===----------------------------------------------------------------------===//
2200
John McCall42c8f872010-05-10 23:27:23 +00002201/// Evaluate - Return true if this is a constant which we can fold using
2202/// any crazy technique (that has nothing to do with language standards) that
2203/// we want to. If this function returns true, it returns the folded constant
2204/// in Result.
2205bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2206 const Expr *E = this;
2207 EvalInfo Info(Ctx, Result);
John McCallefdb83e2010-05-07 21:00:08 +00002208 if (E->getType()->isVectorType()) {
2209 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002210 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002211 } else if (E->getType()->isIntegerType()) {
2212 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002213 return false;
John McCall0f2b6922010-07-07 05:08:32 +00002214 if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2215 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002216 } else if (E->getType()->hasPointerRepresentation()) {
2217 LValue LV;
2218 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002219 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002220 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002221 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002222 LV.moveInto(Info.EvalResult.Val);
2223 } else if (E->getType()->isRealFloatingType()) {
2224 llvm::APFloat F(0.0);
2225 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002226 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002227
John McCallefdb83e2010-05-07 21:00:08 +00002228 Info.EvalResult.Val = APValue(F);
2229 } else if (E->getType()->isAnyComplexType()) {
2230 ComplexValue C;
2231 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002232 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002233 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002234 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002235 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002236
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002237 return true;
2238}
2239
John McCallcd7a4452010-01-05 23:42:56 +00002240bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2241 EvalResult Scratch;
2242 EvalInfo Info(Ctx, Scratch);
2243
2244 return HandleConversionToBool(this, Result, Info);
2245}
2246
Anders Carlsson1b782762009-04-10 04:54:13 +00002247bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2248 EvalInfo Info(Ctx, Result);
2249
John McCallefdb83e2010-05-07 21:00:08 +00002250 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002251 if (EvaluateLValue(this, LV, Info) &&
2252 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002253 IsGlobalLValue(LV.Base)) {
2254 LV.moveInto(Result.Val);
2255 return true;
2256 }
2257 return false;
2258}
2259
2260bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2261 EvalInfo Info(Ctx, Result);
2262
2263 LValue LV;
2264 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002265 LV.moveInto(Result.Val);
2266 return true;
2267 }
2268 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002269}
2270
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002271/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002272/// folded, but discard the result.
2273bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002274 EvalResult Result;
2275 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002276}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002277
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002278bool Expr::HasSideEffects(ASTContext &Ctx) const {
2279 Expr::EvalResult Result;
2280 EvalInfo Info(Ctx, Result);
2281 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2282}
2283
Anders Carlsson51fe9962008-11-22 21:04:56 +00002284APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002285 EvalResult EvalResult;
2286 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00002287 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002288 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002289 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002290
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002291 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002292}
John McCalld905f5a2010-05-07 05:32:02 +00002293
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002294 bool Expr::EvalResult::isGlobalLValue() const {
2295 assert(Val.isLValue());
2296 return IsGlobalLValue(Val.getLValueBase());
2297 }
2298
2299
John McCalld905f5a2010-05-07 05:32:02 +00002300/// isIntegerConstantExpr - this recursive routine will test if an expression is
2301/// an integer constant expression.
2302
2303/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2304/// comma, etc
2305///
2306/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2307/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2308/// cast+dereference.
2309
2310// CheckICE - This function does the fundamental ICE checking: the returned
2311// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2312// Note that to reduce code duplication, this helper does no evaluation
2313// itself; the caller checks whether the expression is evaluatable, and
2314// in the rare cases where CheckICE actually cares about the evaluated
2315// value, it calls into Evalute.
2316//
2317// Meanings of Val:
2318// 0: This expression is an ICE if it can be evaluated by Evaluate.
2319// 1: This expression is not an ICE, but if it isn't evaluated, it's
2320// a legal subexpression for an ICE. This return value is used to handle
2321// the comma operator in C99 mode.
2322// 2: This expression is not an ICE, and is not a legal subexpression for one.
2323
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002324namespace {
2325
John McCalld905f5a2010-05-07 05:32:02 +00002326struct ICEDiag {
2327 unsigned Val;
2328 SourceLocation Loc;
2329
2330 public:
2331 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2332 ICEDiag() : Val(0) {}
2333};
2334
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002335}
2336
2337static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002338
2339static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2340 Expr::EvalResult EVResult;
2341 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2342 !EVResult.Val.isInt()) {
2343 return ICEDiag(2, E->getLocStart());
2344 }
2345 return NoDiag();
2346}
2347
2348static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2349 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002350 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002351 return ICEDiag(2, E->getLocStart());
2352 }
2353
2354 switch (E->getStmtClass()) {
2355#define STMT(Node, Base) case Expr::Node##Class:
2356#define EXPR(Node, Base)
2357#include "clang/AST/StmtNodes.inc"
2358 case Expr::PredefinedExprClass:
2359 case Expr::FloatingLiteralClass:
2360 case Expr::ImaginaryLiteralClass:
2361 case Expr::StringLiteralClass:
2362 case Expr::ArraySubscriptExprClass:
2363 case Expr::MemberExprClass:
2364 case Expr::CompoundAssignOperatorClass:
2365 case Expr::CompoundLiteralExprClass:
2366 case Expr::ExtVectorElementExprClass:
2367 case Expr::InitListExprClass:
2368 case Expr::DesignatedInitExprClass:
2369 case Expr::ImplicitValueInitExprClass:
2370 case Expr::ParenListExprClass:
2371 case Expr::VAArgExprClass:
2372 case Expr::AddrLabelExprClass:
2373 case Expr::StmtExprClass:
2374 case Expr::CXXMemberCallExprClass:
2375 case Expr::CXXDynamicCastExprClass:
2376 case Expr::CXXTypeidExprClass:
2377 case Expr::CXXNullPtrLiteralExprClass:
2378 case Expr::CXXThisExprClass:
2379 case Expr::CXXThrowExprClass:
2380 case Expr::CXXNewExprClass:
2381 case Expr::CXXDeleteExprClass:
2382 case Expr::CXXPseudoDestructorExprClass:
2383 case Expr::UnresolvedLookupExprClass:
2384 case Expr::DependentScopeDeclRefExprClass:
2385 case Expr::CXXConstructExprClass:
2386 case Expr::CXXBindTemporaryExprClass:
2387 case Expr::CXXBindReferenceExprClass:
2388 case Expr::CXXExprWithTemporariesClass:
2389 case Expr::CXXTemporaryObjectExprClass:
2390 case Expr::CXXUnresolvedConstructExprClass:
2391 case Expr::CXXDependentScopeMemberExprClass:
2392 case Expr::UnresolvedMemberExprClass:
2393 case Expr::ObjCStringLiteralClass:
2394 case Expr::ObjCEncodeExprClass:
2395 case Expr::ObjCMessageExprClass:
2396 case Expr::ObjCSelectorExprClass:
2397 case Expr::ObjCProtocolExprClass:
2398 case Expr::ObjCIvarRefExprClass:
2399 case Expr::ObjCPropertyRefExprClass:
2400 case Expr::ObjCImplicitSetterGetterRefExprClass:
2401 case Expr::ObjCSuperExprClass:
2402 case Expr::ObjCIsaExprClass:
2403 case Expr::ShuffleVectorExprClass:
2404 case Expr::BlockExprClass:
2405 case Expr::BlockDeclRefExprClass:
2406 case Expr::NoStmtClass:
2407 return ICEDiag(2, E->getLocStart());
2408
2409 case Expr::GNUNullExprClass:
2410 // GCC considers the GNU __null value to be an integral constant expression.
2411 return NoDiag();
2412
2413 case Expr::ParenExprClass:
2414 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2415 case Expr::IntegerLiteralClass:
2416 case Expr::CharacterLiteralClass:
2417 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002418 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002419 case Expr::TypesCompatibleExprClass:
2420 case Expr::UnaryTypeTraitExprClass:
2421 return NoDiag();
2422 case Expr::CallExprClass:
2423 case Expr::CXXOperatorCallExprClass: {
2424 const CallExpr *CE = cast<CallExpr>(E);
2425 if (CE->isBuiltinCall(Ctx))
2426 return CheckEvalInICE(E, Ctx);
2427 return ICEDiag(2, E->getLocStart());
2428 }
2429 case Expr::DeclRefExprClass:
2430 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2431 return NoDiag();
2432 if (Ctx.getLangOptions().CPlusPlus &&
2433 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2434 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2435
2436 // Parameter variables are never constants. Without this check,
2437 // getAnyInitializer() can find a default argument, which leads
2438 // to chaos.
2439 if (isa<ParmVarDecl>(D))
2440 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2441
2442 // C++ 7.1.5.1p2
2443 // A variable of non-volatile const-qualified integral or enumeration
2444 // type initialized by an ICE can be used in ICEs.
2445 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2446 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2447 if (Quals.hasVolatile() || !Quals.hasConst())
2448 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2449
2450 // Look for a declaration of this variable that has an initializer.
2451 const VarDecl *ID = 0;
2452 const Expr *Init = Dcl->getAnyInitializer(ID);
2453 if (Init) {
2454 if (ID->isInitKnownICE()) {
2455 // We have already checked whether this subexpression is an
2456 // integral constant expression.
2457 if (ID->isInitICE())
2458 return NoDiag();
2459 else
2460 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2461 }
2462
2463 // It's an ICE whether or not the definition we found is
2464 // out-of-line. See DR 721 and the discussion in Clang PR
2465 // 6206 for details.
2466
2467 if (Dcl->isCheckingICE()) {
2468 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2469 }
2470
2471 Dcl->setCheckingICE();
2472 ICEDiag Result = CheckICE(Init, Ctx);
2473 // Cache the result of the ICE test.
2474 Dcl->setInitKnownICE(Result.Val == 0);
2475 return Result;
2476 }
2477 }
2478 }
2479 return ICEDiag(2, E->getLocStart());
2480 case Expr::UnaryOperatorClass: {
2481 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2482 switch (Exp->getOpcode()) {
2483 case UnaryOperator::PostInc:
2484 case UnaryOperator::PostDec:
2485 case UnaryOperator::PreInc:
2486 case UnaryOperator::PreDec:
2487 case UnaryOperator::AddrOf:
2488 case UnaryOperator::Deref:
2489 return ICEDiag(2, E->getLocStart());
2490 case UnaryOperator::Extension:
2491 case UnaryOperator::LNot:
2492 case UnaryOperator::Plus:
2493 case UnaryOperator::Minus:
2494 case UnaryOperator::Not:
2495 case UnaryOperator::Real:
2496 case UnaryOperator::Imag:
2497 return CheckICE(Exp->getSubExpr(), Ctx);
2498 case UnaryOperator::OffsetOf:
2499 break;
2500 }
2501
2502 // OffsetOf falls through here.
2503 }
2504 case Expr::OffsetOfExprClass: {
2505 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2506 // Evaluate matches the proposed gcc behavior for cases like
2507 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2508 // compliance: we should warn earlier for offsetof expressions with
2509 // array subscripts that aren't ICEs, and if the array subscripts
2510 // are ICEs, the value of the offsetof must be an integer constant.
2511 return CheckEvalInICE(E, Ctx);
2512 }
2513 case Expr::SizeOfAlignOfExprClass: {
2514 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2515 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2516 return ICEDiag(2, E->getLocStart());
2517 return NoDiag();
2518 }
2519 case Expr::BinaryOperatorClass: {
2520 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2521 switch (Exp->getOpcode()) {
2522 case BinaryOperator::PtrMemD:
2523 case BinaryOperator::PtrMemI:
2524 case BinaryOperator::Assign:
2525 case BinaryOperator::MulAssign:
2526 case BinaryOperator::DivAssign:
2527 case BinaryOperator::RemAssign:
2528 case BinaryOperator::AddAssign:
2529 case BinaryOperator::SubAssign:
2530 case BinaryOperator::ShlAssign:
2531 case BinaryOperator::ShrAssign:
2532 case BinaryOperator::AndAssign:
2533 case BinaryOperator::XorAssign:
2534 case BinaryOperator::OrAssign:
2535 return ICEDiag(2, E->getLocStart());
2536
2537 case BinaryOperator::Mul:
2538 case BinaryOperator::Div:
2539 case BinaryOperator::Rem:
2540 case BinaryOperator::Add:
2541 case BinaryOperator::Sub:
2542 case BinaryOperator::Shl:
2543 case BinaryOperator::Shr:
2544 case BinaryOperator::LT:
2545 case BinaryOperator::GT:
2546 case BinaryOperator::LE:
2547 case BinaryOperator::GE:
2548 case BinaryOperator::EQ:
2549 case BinaryOperator::NE:
2550 case BinaryOperator::And:
2551 case BinaryOperator::Xor:
2552 case BinaryOperator::Or:
2553 case BinaryOperator::Comma: {
2554 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2555 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2556 if (Exp->getOpcode() == BinaryOperator::Div ||
2557 Exp->getOpcode() == BinaryOperator::Rem) {
2558 // Evaluate gives an error for undefined Div/Rem, so make sure
2559 // we don't evaluate one.
2560 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2561 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2562 if (REval == 0)
2563 return ICEDiag(1, E->getLocStart());
2564 if (REval.isSigned() && REval.isAllOnesValue()) {
2565 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2566 if (LEval.isMinSignedValue())
2567 return ICEDiag(1, E->getLocStart());
2568 }
2569 }
2570 }
2571 if (Exp->getOpcode() == BinaryOperator::Comma) {
2572 if (Ctx.getLangOptions().C99) {
2573 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2574 // if it isn't evaluated.
2575 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2576 return ICEDiag(1, E->getLocStart());
2577 } else {
2578 // In both C89 and C++, commas in ICEs are illegal.
2579 return ICEDiag(2, E->getLocStart());
2580 }
2581 }
2582 if (LHSResult.Val >= RHSResult.Val)
2583 return LHSResult;
2584 return RHSResult;
2585 }
2586 case BinaryOperator::LAnd:
2587 case BinaryOperator::LOr: {
2588 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2589 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2590 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2591 // Rare case where the RHS has a comma "side-effect"; we need
2592 // to actually check the condition to see whether the side
2593 // with the comma is evaluated.
2594 if ((Exp->getOpcode() == BinaryOperator::LAnd) !=
2595 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2596 return RHSResult;
2597 return NoDiag();
2598 }
2599
2600 if (LHSResult.Val >= RHSResult.Val)
2601 return LHSResult;
2602 return RHSResult;
2603 }
2604 }
2605 }
2606 case Expr::ImplicitCastExprClass:
2607 case Expr::CStyleCastExprClass:
2608 case Expr::CXXFunctionalCastExprClass:
2609 case Expr::CXXStaticCastExprClass:
2610 case Expr::CXXReinterpretCastExprClass:
2611 case Expr::CXXConstCastExprClass: {
2612 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002613 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00002614 return CheckICE(SubExpr, Ctx);
2615 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2616 return NoDiag();
2617 return ICEDiag(2, E->getLocStart());
2618 }
2619 case Expr::ConditionalOperatorClass: {
2620 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2621 // If the condition (ignoring parens) is a __builtin_constant_p call,
2622 // then only the true side is actually considered in an integer constant
2623 // expression, and it is fully evaluated. This is an important GNU
2624 // extension. See GCC PR38377 for discussion.
2625 if (const CallExpr *CallCE
2626 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2627 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2628 Expr::EvalResult EVResult;
2629 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2630 !EVResult.Val.isInt()) {
2631 return ICEDiag(2, E->getLocStart());
2632 }
2633 return NoDiag();
2634 }
2635 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2636 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2637 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2638 if (CondResult.Val == 2)
2639 return CondResult;
2640 if (TrueResult.Val == 2)
2641 return TrueResult;
2642 if (FalseResult.Val == 2)
2643 return FalseResult;
2644 if (CondResult.Val == 1)
2645 return CondResult;
2646 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2647 return NoDiag();
2648 // Rare case where the diagnostics depend on which side is evaluated
2649 // Note that if we get here, CondResult is 0, and at least one of
2650 // TrueResult and FalseResult is non-zero.
2651 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2652 return FalseResult;
2653 }
2654 return TrueResult;
2655 }
2656 case Expr::CXXDefaultArgExprClass:
2657 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2658 case Expr::ChooseExprClass: {
2659 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2660 }
2661 }
2662
2663 // Silence a GCC warning
2664 return ICEDiag(2, E->getLocStart());
2665}
2666
2667bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2668 SourceLocation *Loc, bool isEvaluated) const {
2669 ICEDiag d = CheckICE(this, Ctx);
2670 if (d.Val != 0) {
2671 if (Loc) *Loc = d.Loc;
2672 return false;
2673 }
2674 EvalResult EvalResult;
2675 if (!Evaluate(EvalResult, Ctx))
2676 llvm_unreachable("ICE cannot be evaluated!");
2677 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2678 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2679 Result = EvalResult.Val.getInt();
2680 return true;
2681}