blob: 7479d9d9be21d405cca4ce3a73e0b9574aea98ef [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
John McCall2de56d12010-08-25 11:45:40 +0000340 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000341 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) {
John McCall2de56d12010-08-25 11:45:40 +0000484 if (E->getOpcode() != BO_Add &&
485 E->getOpcode() != BO_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
John McCall2de56d12010-08-25 11:45:40 +0000515 if (E->getOpcode() == BO_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
John McCall2de56d12010-08-25 11:45:40 +0000535 case CK_NoOp:
536 case CK_BitCast:
537 case CK_LValueBitCast:
538 case CK_AnyPointerToObjCPointerCast:
539 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000540 return Visit(SubExpr);
541
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000542 case CK_DerivedToBase:
543 case CK_UncheckedDerivedToBase: {
544 LValue BaseLV;
545 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
546 return false;
547
548 // Now figure out the necessary offset to add to the baseLV to get from
549 // the derived class to the base class.
550 uint64_t Offset = 0;
551
552 QualType Ty = E->getSubExpr()->getType();
553 const CXXRecordDecl *DerivedDecl =
554 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
555
556 for (CastExpr::path_const_iterator PathI = E->path_begin(),
557 PathE = E->path_end(); PathI != PathE; ++PathI) {
558 const CXXBaseSpecifier *Base = *PathI;
559
560 // FIXME: If the base is virtual, we'd need to determine the type of the
561 // most derived class and we don't support that right now.
562 if (Base->isVirtual())
563 return false;
564
565 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
566 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
567
Anders Carlssona14f5972010-10-31 23:22:37 +0000568 Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000569 DerivedDecl = BaseDecl;
570 }
571
572 Result.Base = BaseLV.getLValueBase();
573 Result.Offset = BaseLV.getLValueOffset() +
574 CharUnits::fromQuantity(Offset / Info.Ctx.getCharWidth());
575 return true;
576 }
577
John McCall404cd162010-11-13 01:35:44 +0000578 case CK_NullToPointer: {
579 Result.Base = 0;
580 Result.Offset = CharUnits::Zero();
581 return true;
582 }
583
John McCall2de56d12010-08-25 11:45:40 +0000584 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000585 APValue Value;
586 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000587 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000588
John McCallefdb83e2010-05-07 21:00:08 +0000589 if (Value.isInt()) {
590 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
591 Result.Base = 0;
592 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
593 return true;
594 } else {
595 // Cast is of an lvalue, no need to change value.
596 Result.Base = Value.getLValueBase();
597 Result.Offset = Value.getLValueOffset();
598 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000599 }
600 }
John McCall2de56d12010-08-25 11:45:40 +0000601 case CK_ArrayToPointerDecay:
602 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000603 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000604 }
605
John McCallefdb83e2010-05-07 21:00:08 +0000606 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000607}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000608
John McCallefdb83e2010-05-07 21:00:08 +0000609bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000610 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000611 Builtin::BI__builtin___CFStringMakeConstantString ||
612 E->isBuiltinCall(Info.Ctx) ==
613 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000614 return Success(E);
615 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000616}
617
John McCallefdb83e2010-05-07 21:00:08 +0000618bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000619 bool BoolResult;
620 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000621 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000622
623 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000624 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000625}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000626
627//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000628// Vector Evaluation
629//===----------------------------------------------------------------------===//
630
631namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000632 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000633 : public StmtVisitor<VectorExprEvaluator, APValue> {
634 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000635 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000636 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000637
Nate Begeman59b5da62009-01-18 03:20:47 +0000638 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000639
Nate Begeman59b5da62009-01-18 03:20:47 +0000640 APValue VisitStmt(Stmt *S) {
641 return APValue();
642 }
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Eli Friedman91110ee2009-02-23 04:23:56 +0000644 APValue VisitParenExpr(ParenExpr *E)
645 { return Visit(E->getSubExpr()); }
646 APValue VisitUnaryExtension(const UnaryOperator *E)
647 { return Visit(E->getSubExpr()); }
648 APValue VisitUnaryPlus(const UnaryOperator *E)
649 { return Visit(E->getSubExpr()); }
650 APValue VisitUnaryReal(const UnaryOperator *E)
651 { return Visit(E->getSubExpr()); }
652 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
653 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000654 APValue VisitCastExpr(const CastExpr* E);
655 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
656 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000657 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000658 APValue VisitChooseExpr(const ChooseExpr *E)
659 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000660 APValue VisitUnaryImag(const UnaryOperator *E);
661 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000662 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000663 // shufflevector, ExtVectorElementExpr
664 // (Note that these require implementing conversions
665 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000666 };
667} // end anonymous namespace
668
669static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
670 if (!E->getType()->isVectorType())
671 return false;
672 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
673 return !Result.isUninit();
674}
675
676APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000677 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000678 QualType EltTy = VTy->getElementType();
679 unsigned NElts = VTy->getNumElements();
680 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Nate Begeman59b5da62009-01-18 03:20:47 +0000682 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000683 QualType SETy = SE->getType();
684 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000685
Nate Begemane8c9e922009-06-26 18:22:18 +0000686 // Check for vector->vector bitcast and scalar->vector splat.
687 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000688 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000689 } else if (SETy->isIntegerType()) {
690 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000691 if (!EvaluateInteger(SE, IntResult, Info))
692 return APValue();
693 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000694 } else if (SETy->isRealFloatingType()) {
695 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000696 if (!EvaluateFloat(SE, F, Info))
697 return APValue();
698 Result = APValue(F);
699 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000700 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000701
Nate Begemanc0b8b192009-07-01 07:50:47 +0000702 // For casts of a scalar to ExtVector, convert the scalar to the element type
703 // and splat it to all elements.
704 if (E->getType()->isExtVectorType()) {
705 if (EltTy->isIntegerType() && Result.isInt())
706 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
707 Info.Ctx));
708 else if (EltTy->isIntegerType())
709 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
710 Info.Ctx));
711 else if (EltTy->isRealFloatingType() && Result.isInt())
712 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
713 Info.Ctx));
714 else if (EltTy->isRealFloatingType())
715 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
716 Info.Ctx));
717 else
718 return APValue();
719
720 // Splat and create vector APValue.
721 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
722 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000723 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000724
725 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
726 // to the vector. To construct the APValue vector initializer, bitcast the
727 // initializing value to an APInt, and shift out the bits pertaining to each
728 // element.
729 APSInt Init;
730 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Nate Begemanc0b8b192009-07-01 07:50:47 +0000732 llvm::SmallVector<APValue, 4> Elts;
733 for (unsigned i = 0; i != NElts; ++i) {
734 APSInt Tmp = Init;
735 Tmp.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000736
Nate Begemanc0b8b192009-07-01 07:50:47 +0000737 if (EltTy->isIntegerType())
738 Elts.push_back(APValue(Tmp));
739 else if (EltTy->isRealFloatingType())
740 Elts.push_back(APValue(APFloat(Tmp)));
741 else
742 return APValue();
743
744 Init >>= EltWidth;
745 }
746 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000747}
748
Mike Stump1eb44332009-09-09 15:08:12 +0000749APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000750VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
751 return this->Visit(const_cast<Expr*>(E->getInitializer()));
752}
753
Mike Stump1eb44332009-09-09 15:08:12 +0000754APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000755VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000756 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000757 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000758 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Nate Begeman59b5da62009-01-18 03:20:47 +0000760 QualType EltTy = VT->getElementType();
761 llvm::SmallVector<APValue, 4> Elements;
762
John McCalla7d6c222010-06-11 17:54:15 +0000763 // If a vector is initialized with a single element, that value
764 // becomes every element of the vector, not just the first.
765 // This is the behavior described in the IBM AltiVec documentation.
766 if (NumInits == 1) {
767 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000768 if (EltTy->isIntegerType()) {
769 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000770 if (!EvaluateInteger(E->getInit(0), sInt, Info))
771 return APValue();
772 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000773 } else {
774 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000775 if (!EvaluateFloat(E->getInit(0), f, Info))
776 return APValue();
777 InitValue = APValue(f);
778 }
779 for (unsigned i = 0; i < NumElements; i++) {
780 Elements.push_back(InitValue);
781 }
782 } else {
783 for (unsigned i = 0; i < NumElements; i++) {
784 if (EltTy->isIntegerType()) {
785 llvm::APSInt sInt(32);
786 if (i < NumInits) {
787 if (!EvaluateInteger(E->getInit(i), sInt, Info))
788 return APValue();
789 } else {
790 sInt = Info.Ctx.MakeIntValue(0, EltTy);
791 }
792 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000793 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000794 llvm::APFloat f(0.0);
795 if (i < NumInits) {
796 if (!EvaluateFloat(E->getInit(i), f, Info))
797 return APValue();
798 } else {
799 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
800 }
801 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000802 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000803 }
804 }
805 return APValue(&Elements[0], Elements.size());
806}
807
Mike Stump1eb44332009-09-09 15:08:12 +0000808APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000809VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000810 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000811 QualType EltTy = VT->getElementType();
812 APValue ZeroElement;
813 if (EltTy->isIntegerType())
814 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
815 else
816 ZeroElement =
817 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
818
819 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
820 return APValue(&Elements[0], Elements.size());
821}
822
823APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
824 bool BoolResult;
825 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
826 return APValue();
827
828 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
829
830 APValue Result;
831 if (EvaluateVector(EvalExpr, Result, Info))
832 return Result;
833 return APValue();
834}
835
Eli Friedman91110ee2009-02-23 04:23:56 +0000836APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
837 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
838 Info.EvalResult.HasSideEffects = true;
839 return GetZeroVector(E->getType());
840}
841
Nate Begeman59b5da62009-01-18 03:20:47 +0000842//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000843// Integer Evaluation
844//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000845
846namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000847class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000848 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000849 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000850 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000851public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000852 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000853 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000854
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000855 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000856 assert(E->getType()->isIntegralOrEnumerationType() &&
857 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000858 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000859 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000860 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000861 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000862 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000863 return true;
864 }
865
Daniel Dunbar131eb432009-02-19 09:06:44 +0000866 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000867 assert(E->getType()->isIntegralOrEnumerationType() &&
868 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000869 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000870 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000871 Result = APValue(APSInt(I));
872 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000873 return true;
874 }
875
876 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000877 assert(E->getType()->isIntegralOrEnumerationType() &&
878 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000879 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000880 return true;
881 }
882
Anders Carlsson82206e22008-11-30 18:14:57 +0000883 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000884 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000885 if (Info.EvalResult.Diag == 0) {
886 Info.EvalResult.DiagLoc = L;
887 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000888 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000889 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000890 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000891 }
Mike Stump1eb44332009-09-09 15:08:12 +0000892
Anders Carlssonc754aa62008-07-08 05:13:58 +0000893 //===--------------------------------------------------------------------===//
894 // Visitor Methods
895 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000896
Chris Lattner32fea9d2008-11-12 07:43:42 +0000897 bool VisitStmt(Stmt *) {
898 assert(0 && "This should be called on integers, stmts are not integers");
899 return false;
900 }
Mike Stump1eb44332009-09-09 15:08:12 +0000901
Chris Lattner32fea9d2008-11-12 07:43:42 +0000902 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000903 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000904 }
Mike Stump1eb44332009-09-09 15:08:12 +0000905
Chris Lattnerb542afe2008-07-11 19:10:17 +0000906 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000907
Chris Lattner4c4867e2008-07-12 00:38:25 +0000908 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000909 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000910 }
911 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000912 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000913 }
914 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarac620de2008-10-24 08:07:57 +0000915 // Per gcc docs "this built-in function ignores top level
916 // qualifiers". We need to use the canonical version to properly
917 // be able to strip CRV qualifiers from the type.
918 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
919 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump1eb44332009-09-09 15:08:12 +0000920 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar131eb432009-02-19 09:06:44 +0000921 T1.getUnqualifiedType()),
922 E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000923 }
Eli Friedman04309752009-11-24 05:28:59 +0000924
925 bool CheckReferencedDecl(const Expr *E, const Decl *D);
926 bool VisitDeclRefExpr(const DeclRefExpr *E) {
927 return CheckReferencedDecl(E, E->getDecl());
928 }
929 bool VisitMemberExpr(const MemberExpr *E) {
930 if (CheckReferencedDecl(E, E->getMemberDecl())) {
931 // Conservatively assume a MemberExpr will have side-effects
932 Info.EvalResult.HasSideEffects = true;
933 return true;
934 }
935 return false;
936 }
937
Eli Friedmanc4a26382010-02-13 00:10:10 +0000938 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000939 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000940 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000941 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000942 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000943
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000944 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000945 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
946
Anders Carlsson3068d112008-11-16 19:01:22 +0000947 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000948 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000949 }
Mike Stump1eb44332009-09-09 15:08:12 +0000950
Anders Carlsson3f704562008-12-21 22:39:40 +0000951 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000952 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000953 }
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Douglas Gregored8abf12010-07-08 06:14:04 +0000955 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000956 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000957 }
958
Eli Friedman664a1042009-02-27 04:45:43 +0000959 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
960 return Success(0, E);
961 }
962
Sebastian Redl64b45f72009-01-05 20:52:13 +0000963 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000964 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000965 }
966
Francois Pichet6ad6f282010-12-07 00:08:36 +0000967 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
968 return Success(E->getValue(), E);
969 }
970
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000971 bool VisitChooseExpr(const ChooseExpr *E) {
972 return Visit(E->getChosenSubExpr(Info.Ctx));
973 }
974
Eli Friedman722c7172009-02-28 03:59:05 +0000975 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000976 bool VisitUnaryImag(const UnaryOperator *E);
977
Sebastian Redl295995c2010-09-10 20:55:47 +0000978 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
979
Chris Lattnerfcee0012008-07-11 21:24:13 +0000980private:
Ken Dyck8b752f12010-01-27 17:10:57 +0000981 CharUnits GetAlignOfExpr(const Expr *E);
982 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +0000983 static QualType GetObjectType(const Expr *E);
984 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +0000985 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +0000986};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000987} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000988
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000989static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000990 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000991 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
992}
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000993
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000994static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000995 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +0000996
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000997 APValue Val;
998 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
999 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001000 Result = Val.getInt();
1001 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001002}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001003
Eli Friedman04309752009-11-24 05:28:59 +00001004bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001005 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001006 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1007 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001008
1009 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001010 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001011 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1012 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001013
1014 if (isa<ParmVarDecl>(D))
1015 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1016
Eli Friedman04309752009-11-24 05:28:59 +00001017 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001018 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001019 if (APValue *V = VD->getEvaluatedValue()) {
1020 if (V->isInt())
1021 return Success(V->getInt(), E);
1022 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1023 }
1024
1025 if (VD->isEvaluatingValue())
1026 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1027
1028 VD->setEvaluatingValue();
1029
Eli Friedmana7dedf72010-09-06 00:10:32 +00001030 Expr::EvalResult EResult;
1031 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1032 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001033 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001034 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001035 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001036 return true;
1037 }
1038
Eli Friedmanc0131182009-12-03 20:31:57 +00001039 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001040 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001041 }
1042 }
1043
Chris Lattner4c4867e2008-07-12 00:38:25 +00001044 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001045 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001046}
1047
Chris Lattnera4d55d82008-10-06 06:40:35 +00001048/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1049/// as GCC.
1050static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1051 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001052 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001053 enum gcc_type_class {
1054 no_type_class = -1,
1055 void_type_class, integer_type_class, char_type_class,
1056 enumeral_type_class, boolean_type_class,
1057 pointer_type_class, reference_type_class, offset_type_class,
1058 real_type_class, complex_type_class,
1059 function_type_class, method_type_class,
1060 record_type_class, union_type_class,
1061 array_type_class, string_type_class,
1062 lang_type_class
1063 };
Mike Stump1eb44332009-09-09 15:08:12 +00001064
1065 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001066 // ideal, however it is what gcc does.
1067 if (E->getNumArgs() == 0)
1068 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Chris Lattnera4d55d82008-10-06 06:40:35 +00001070 QualType ArgTy = E->getArg(0)->getType();
1071 if (ArgTy->isVoidType())
1072 return void_type_class;
1073 else if (ArgTy->isEnumeralType())
1074 return enumeral_type_class;
1075 else if (ArgTy->isBooleanType())
1076 return boolean_type_class;
1077 else if (ArgTy->isCharType())
1078 return string_type_class; // gcc doesn't appear to use char_type_class
1079 else if (ArgTy->isIntegerType())
1080 return integer_type_class;
1081 else if (ArgTy->isPointerType())
1082 return pointer_type_class;
1083 else if (ArgTy->isReferenceType())
1084 return reference_type_class;
1085 else if (ArgTy->isRealType())
1086 return real_type_class;
1087 else if (ArgTy->isComplexType())
1088 return complex_type_class;
1089 else if (ArgTy->isFunctionType())
1090 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001091 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001092 return record_type_class;
1093 else if (ArgTy->isUnionType())
1094 return union_type_class;
1095 else if (ArgTy->isArrayType())
1096 return array_type_class;
1097 else if (ArgTy->isUnionType())
1098 return union_type_class;
1099 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1100 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1101 return -1;
1102}
1103
John McCall42c8f872010-05-10 23:27:23 +00001104/// Retrieves the "underlying object type" of the given expression,
1105/// as used by __builtin_object_size.
1106QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1107 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1108 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1109 return VD->getType();
1110 } else if (isa<CompoundLiteralExpr>(E)) {
1111 return E->getType();
1112 }
1113
1114 return QualType();
1115}
1116
1117bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1118 // TODO: Perhaps we should let LLVM lower this?
1119 LValue Base;
1120 if (!EvaluatePointer(E->getArg(0), Base, Info))
1121 return false;
1122
1123 // If we can prove the base is null, lower to zero now.
1124 const Expr *LVBase = Base.getLValueBase();
1125 if (!LVBase) return Success(0, E);
1126
1127 QualType T = GetObjectType(LVBase);
1128 if (T.isNull() ||
1129 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001130 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001131 T->isVariablyModifiedType() ||
1132 T->isDependentType())
1133 return false;
1134
1135 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1136 CharUnits Offset = Base.getLValueOffset();
1137
1138 if (!Offset.isNegative() && Offset <= Size)
1139 Size -= Offset;
1140 else
1141 Size = CharUnits::Zero();
1142 return Success(Size.getQuantity(), E);
1143}
1144
Eli Friedmanc4a26382010-02-13 00:10:10 +00001145bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001146 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001147 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001148 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001149
1150 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001151 if (TryEvaluateBuiltinObjectSize(E))
1152 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001153
Eric Christopherb2aaf512010-01-19 22:58:35 +00001154 // If evaluating the argument has side-effects we can't determine
1155 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001156 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001157 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001158 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001159 return Success(0, E);
1160 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001161
Mike Stump64eda9e2009-10-26 18:35:08 +00001162 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1163 }
1164
Chris Lattner019f4e82008-10-06 05:28:25 +00001165 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001166 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001168 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001169 // __builtin_constant_p always has one operand: it returns true if that
1170 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001171 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001172
1173 case Builtin::BI__builtin_eh_return_data_regno: {
1174 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1175 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1176 return Success(Operand, E);
1177 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001178
1179 case Builtin::BI__builtin_expect:
1180 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001181
1182 case Builtin::BIstrlen:
1183 case Builtin::BI__builtin_strlen:
1184 // As an extension, we support strlen() and __builtin_strlen() as constant
1185 // expressions when the argument is a string literal.
1186 if (StringLiteral *S
1187 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1188 // The string literal may have embedded null characters. Find the first
1189 // one and truncate there.
1190 llvm::StringRef Str = S->getString();
1191 llvm::StringRef::size_type Pos = Str.find(0);
1192 if (Pos != llvm::StringRef::npos)
1193 Str = Str.substr(0, Pos);
1194
1195 return Success(Str.size(), E);
1196 }
1197
1198 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001199 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001200}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001201
Chris Lattnerb542afe2008-07-11 19:10:17 +00001202bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001203 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001204 if (!Visit(E->getRHS()))
1205 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001206
Eli Friedman33ef1452009-02-26 10:19:36 +00001207 // If we can't evaluate the LHS, it might have side effects;
1208 // conservatively mark it.
1209 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1210 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001211
Anders Carlsson027f62e2008-12-01 02:07:06 +00001212 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001213 }
1214
1215 if (E->isLogicalOp()) {
1216 // These need to be handled specially because the operands aren't
1217 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001218 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001219
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001220 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001221 // We were able to evaluate the LHS, see if we can get away with not
1222 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001223 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001224 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001225
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001226 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001227 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001228 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001229 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001230 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001231 }
1232 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001233 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001234 // We can't evaluate the LHS; however, sometimes the result
1235 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001236 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1237 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001238 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001239 // must have had side effects.
1240 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001241
1242 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001243 }
1244 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001245 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001246
Eli Friedmana6afa762008-11-13 06:09:17 +00001247 return false;
1248 }
1249
Anders Carlsson286f85e2008-11-16 07:17:21 +00001250 QualType LHSTy = E->getLHS()->getType();
1251 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001252
1253 if (LHSTy->isAnyComplexType()) {
1254 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001255 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001256
1257 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1258 return false;
1259
1260 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1261 return false;
1262
1263 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001264 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001265 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001266 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001267 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1268
John McCall2de56d12010-08-25 11:45:40 +00001269 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001270 return Success((CR_r == APFloat::cmpEqual &&
1271 CR_i == APFloat::cmpEqual), E);
1272 else {
John McCall2de56d12010-08-25 11:45:40 +00001273 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001274 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001275 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001276 CR_r == APFloat::cmpLessThan ||
1277 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001278 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001279 CR_i == APFloat::cmpLessThan ||
1280 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001281 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001282 } else {
John McCall2de56d12010-08-25 11:45:40 +00001283 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001284 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1285 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1286 else {
John McCall2de56d12010-08-25 11:45:40 +00001287 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001288 "Invalid compex comparison.");
1289 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1290 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1291 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001292 }
1293 }
Mike Stump1eb44332009-09-09 15:08:12 +00001294
Anders Carlsson286f85e2008-11-16 07:17:21 +00001295 if (LHSTy->isRealFloatingType() &&
1296 RHSTy->isRealFloatingType()) {
1297 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Anders Carlsson286f85e2008-11-16 07:17:21 +00001299 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1300 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Anders Carlsson286f85e2008-11-16 07:17:21 +00001302 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1303 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001304
Anders Carlsson286f85e2008-11-16 07:17:21 +00001305 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001306
Anders Carlsson286f85e2008-11-16 07:17:21 +00001307 switch (E->getOpcode()) {
1308 default:
1309 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001310 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001311 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001312 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001313 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001314 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001315 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001316 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001317 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001318 E);
John McCall2de56d12010-08-25 11:45:40 +00001319 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001320 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001321 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001322 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001323 || CR == APFloat::cmpLessThan
1324 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001325 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001326 }
Mike Stump1eb44332009-09-09 15:08:12 +00001327
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001328 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001329 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001330 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001331 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1332 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001333
John McCallefdb83e2010-05-07 21:00:08 +00001334 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001335 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1336 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001337
Eli Friedman5bc86102009-06-14 02:17:33 +00001338 // Reject any bases from the normal codepath; we special-case comparisons
1339 // to null.
1340 if (LHSValue.getLValueBase()) {
1341 if (!E->isEqualityOp())
1342 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001343 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001344 return false;
1345 bool bres;
1346 if (!EvalPointerValueAsBool(LHSValue, bres))
1347 return false;
John McCall2de56d12010-08-25 11:45:40 +00001348 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001349 } else if (RHSValue.getLValueBase()) {
1350 if (!E->isEqualityOp())
1351 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001352 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001353 return false;
1354 bool bres;
1355 if (!EvalPointerValueAsBool(RHSValue, bres))
1356 return false;
John McCall2de56d12010-08-25 11:45:40 +00001357 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001358 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001359
John McCall2de56d12010-08-25 11:45:40 +00001360 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001361 QualType Type = E->getLHS()->getType();
1362 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001363
Ken Dycka7305832010-01-15 12:37:54 +00001364 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001365 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001366 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001367
Ken Dycka7305832010-01-15 12:37:54 +00001368 CharUnits Diff = LHSValue.getLValueOffset() -
1369 RHSValue.getLValueOffset();
1370 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001371 }
1372 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001373 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001374 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001375 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001376 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1377 }
1378 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001379 }
1380 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001381 if (!LHSTy->isIntegralOrEnumerationType() ||
1382 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001383 // We can't continue from here for non-integral types, and they
1384 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001385 return false;
1386 }
1387
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001388 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001389 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001390 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001391
Eli Friedman42edd0d2009-03-24 01:14:50 +00001392 APValue RHSVal;
1393 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001394 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001395
1396 // Handle cases like (unsigned long)&a + 4.
1397 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001398 CharUnits Offset = Result.getLValueOffset();
1399 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1400 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001401 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001402 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001403 else
Ken Dycka7305832010-01-15 12:37:54 +00001404 Offset -= AdditionalOffset;
1405 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001406 return true;
1407 }
1408
1409 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001410 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001411 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001412 CharUnits Offset = RHSVal.getLValueOffset();
1413 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1414 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001415 return true;
1416 }
1417
1418 // All the following cases expect both operands to be an integer
1419 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001420 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001421
Eli Friedman42edd0d2009-03-24 01:14:50 +00001422 APSInt& RHS = RHSVal.getInt();
1423
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001424 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001425 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001426 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001427 case BO_Mul: return Success(Result.getInt() * RHS, E);
1428 case BO_Add: return Success(Result.getInt() + RHS, E);
1429 case BO_Sub: return Success(Result.getInt() - RHS, E);
1430 case BO_And: return Success(Result.getInt() & RHS, E);
1431 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1432 case BO_Or: return Success(Result.getInt() | RHS, E);
1433 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001434 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001435 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001436 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001437 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001438 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001439 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001440 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001441 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001442 // During constant-folding, a negative shift is an opposite shift.
1443 if (RHS.isSigned() && RHS.isNegative()) {
1444 RHS = -RHS;
1445 goto shift_right;
1446 }
1447
1448 shift_left:
1449 unsigned SA
1450 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001451 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001452 }
John McCall2de56d12010-08-25 11:45:40 +00001453 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001454 // During constant-folding, a negative shift is an opposite shift.
1455 if (RHS.isSigned() && RHS.isNegative()) {
1456 RHS = -RHS;
1457 goto shift_left;
1458 }
1459
1460 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001461 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001462 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1463 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001464 }
Mike Stump1eb44332009-09-09 15:08:12 +00001465
John McCall2de56d12010-08-25 11:45:40 +00001466 case BO_LT: return Success(Result.getInt() < RHS, E);
1467 case BO_GT: return Success(Result.getInt() > RHS, E);
1468 case BO_LE: return Success(Result.getInt() <= RHS, E);
1469 case BO_GE: return Success(Result.getInt() >= RHS, E);
1470 case BO_EQ: return Success(Result.getInt() == RHS, E);
1471 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001472 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001473}
1474
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001475bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001476 bool Cond;
1477 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001478 return false;
1479
Nuno Lopesa25bd552008-11-16 22:06:39 +00001480 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001481}
1482
Ken Dyck8b752f12010-01-27 17:10:57 +00001483CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001484 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1485 // the result is the size of the referenced type."
1486 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1487 // result shall be the alignment of the referenced type."
1488 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1489 T = Ref->getPointeeType();
1490
Chris Lattnere9feb472009-01-24 21:09:06 +00001491 // Get information about the alignment.
1492 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001493
Eli Friedman2be58612009-05-30 21:09:44 +00001494 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001495 return CharUnits::fromQuantity(
1496 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001497}
1498
Ken Dyck8b752f12010-01-27 17:10:57 +00001499CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001500 E = E->IgnoreParens();
1501
1502 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001503 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001504 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001505 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1506 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001507
Chris Lattneraf707ab2009-01-24 21:53:27 +00001508 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001509 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1510 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001511
Chris Lattnere9feb472009-01-24 21:09:06 +00001512 return GetAlignOfType(E->getType());
1513}
1514
1515
Sebastian Redl05189992008-11-11 17:56:53 +00001516/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1517/// expression's type.
1518bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001519 // Handle alignof separately.
1520 if (!E->isSizeOf()) {
1521 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001522 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001523 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001524 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001525 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001526
Sebastian Redl05189992008-11-11 17:56:53 +00001527 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001528 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1529 // the result is the size of the referenced type."
1530 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1531 // result shall be the alignment of the referenced type."
1532 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1533 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001534
Daniel Dunbar131eb432009-02-19 09:06:44 +00001535 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1536 // extension.
1537 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1538 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001539
Chris Lattnerfcee0012008-07-11 21:24:13 +00001540 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001541 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001542 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001543
Chris Lattnere9feb472009-01-24 21:09:06 +00001544 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001545 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001546}
1547
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001548bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1549 CharUnits Result;
1550 unsigned n = E->getNumComponents();
1551 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1552 if (n == 0)
1553 return false;
1554 QualType CurrentType = E->getTypeSourceInfo()->getType();
1555 for (unsigned i = 0; i != n; ++i) {
1556 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1557 switch (ON.getKind()) {
1558 case OffsetOfExpr::OffsetOfNode::Array: {
1559 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1560 APSInt IdxResult;
1561 if (!EvaluateInteger(Idx, IdxResult, Info))
1562 return false;
1563 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1564 if (!AT)
1565 return false;
1566 CurrentType = AT->getElementType();
1567 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1568 Result += IdxResult.getSExtValue() * ElementSize;
1569 break;
1570 }
1571
1572 case OffsetOfExpr::OffsetOfNode::Field: {
1573 FieldDecl *MemberDecl = ON.getField();
1574 const RecordType *RT = CurrentType->getAs<RecordType>();
1575 if (!RT)
1576 return false;
1577 RecordDecl *RD = RT->getDecl();
1578 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1579 unsigned i = 0;
1580 // FIXME: It would be nice if we didn't have to loop here!
1581 for (RecordDecl::field_iterator Field = RD->field_begin(),
1582 FieldEnd = RD->field_end();
1583 Field != FieldEnd; (void)++Field, ++i) {
1584 if (*Field == MemberDecl)
1585 break;
1586 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001587 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1588 Result += CharUnits::fromQuantity(
1589 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001590 CurrentType = MemberDecl->getType().getNonReferenceType();
1591 break;
1592 }
1593
1594 case OffsetOfExpr::OffsetOfNode::Identifier:
1595 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001596 return false;
1597
1598 case OffsetOfExpr::OffsetOfNode::Base: {
1599 CXXBaseSpecifier *BaseSpec = ON.getBase();
1600 if (BaseSpec->isVirtual())
1601 return false;
1602
1603 // Find the layout of the class whose base we are looking into.
1604 const RecordType *RT = CurrentType->getAs<RecordType>();
1605 if (!RT)
1606 return false;
1607 RecordDecl *RD = RT->getDecl();
1608 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1609
1610 // Find the base class itself.
1611 CurrentType = BaseSpec->getType();
1612 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1613 if (!BaseRT)
1614 return false;
1615
1616 // Add the offset to the base.
1617 Result += CharUnits::fromQuantity(
Anders Carlssona14f5972010-10-31 23:22:37 +00001618 RL.getBaseClassOffsetInBits(cast<CXXRecordDecl>(BaseRT->getDecl()))
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001619 / Info.Ctx.getCharWidth());
1620 break;
1621 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001622 }
1623 }
1624 return Success(Result.getQuantity(), E);
1625}
1626
Chris Lattnerb542afe2008-07-11 19:10:17 +00001627bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001628 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001629 // LNot's operand isn't necessarily an integer, so we handle it specially.
1630 bool bres;
1631 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1632 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001633 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001634 }
1635
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001636 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001637 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001638 return false;
1639
Chris Lattner87eae5e2008-07-11 22:52:41 +00001640 // Get the operand value into 'Result'.
1641 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001642 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001643
Chris Lattner75a48812008-07-11 22:15:16 +00001644 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001645 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001646 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1647 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001648 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001649 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001650 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1651 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001652 return true;
John McCall2de56d12010-08-25 11:45:40 +00001653 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001654 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001655 return true;
John McCall2de56d12010-08-25 11:45:40 +00001656 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001657 if (!Result.isInt()) return false;
1658 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001659 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001660 if (!Result.isInt()) return false;
1661 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001662 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001663}
Mike Stump1eb44332009-09-09 15:08:12 +00001664
Chris Lattner732b2232008-07-12 01:15:53 +00001665/// HandleCast - This is used to evaluate implicit or explicit casts where the
1666/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001667bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001668 Expr *SubExpr = E->getSubExpr();
1669 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001670 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001671
Eli Friedman4efaa272008-11-12 09:44:48 +00001672 if (DestType->isBooleanType()) {
1673 bool BoolResult;
1674 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1675 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001676 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001677 }
1678
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001679 // Handle simple integer->integer casts.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001680 if (SrcType->isIntegralOrEnumerationType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001681 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001682 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001683
Eli Friedmanbe265702009-02-20 01:15:07 +00001684 if (!Result.isInt()) {
1685 // Only allow casts of lvalues if they are lossless.
1686 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1687 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001688
Daniel Dunbardd211642009-02-19 22:24:01 +00001689 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001690 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001691 }
Mike Stump1eb44332009-09-09 15:08:12 +00001692
Chris Lattner732b2232008-07-12 01:15:53 +00001693 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001694 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001695 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001696 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001697 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001698
Daniel Dunbardd211642009-02-19 22:24:01 +00001699 if (LV.getLValueBase()) {
1700 // Only allow based lvalue casts if they are lossless.
1701 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1702 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001703
John McCallefdb83e2010-05-07 21:00:08 +00001704 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001705 return true;
1706 }
1707
Ken Dycka7305832010-01-15 12:37:54 +00001708 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1709 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001710 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001711 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001712
Eli Friedmanbe265702009-02-20 01:15:07 +00001713 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1714 // This handles double-conversion cases, where there's both
1715 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001716 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001717 if (!EvaluateLValue(SubExpr, LV, Info))
1718 return false;
1719
1720 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1721 return false;
1722
John McCallefdb83e2010-05-07 21:00:08 +00001723 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001724 return true;
1725 }
1726
Eli Friedman1725f682009-04-22 19:23:09 +00001727 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001728 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001729 if (!EvaluateComplex(SubExpr, C, Info))
1730 return false;
1731 if (C.isComplexFloat())
1732 return Success(HandleFloatToIntCast(DestType, SrcType,
1733 C.getComplexFloatReal(), Info.Ctx),
1734 E);
1735 else
1736 return Success(HandleIntToIntCast(DestType, SrcType,
1737 C.getComplexIntReal(), Info.Ctx), E);
1738 }
Eli Friedman2217c872009-02-22 11:46:18 +00001739 // FIXME: Handle vectors
1740
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001741 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001742 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001743
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001744 APFloat F(0.0);
1745 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001746 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001747
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001748 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001749}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001750
Eli Friedman722c7172009-02-28 03:59:05 +00001751bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1752 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001753 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001754 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1755 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1756 return Success(LV.getComplexIntReal(), E);
1757 }
1758
1759 return Visit(E->getSubExpr());
1760}
1761
Eli Friedman664a1042009-02-27 04:45:43 +00001762bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001763 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001764 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001765 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1766 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1767 return Success(LV.getComplexIntImag(), E);
1768 }
1769
Eli Friedman664a1042009-02-27 04:45:43 +00001770 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1771 Info.EvalResult.HasSideEffects = true;
1772 return Success(0, E);
1773}
1774
Sebastian Redl295995c2010-09-10 20:55:47 +00001775bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1776 return Success(E->getValue(), E);
1777}
1778
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001779//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001780// Float Evaluation
1781//===----------------------------------------------------------------------===//
1782
1783namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001784class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001785 : public StmtVisitor<FloatExprEvaluator, bool> {
1786 EvalInfo &Info;
1787 APFloat &Result;
1788public:
1789 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1790 : Info(info), Result(result) {}
1791
1792 bool VisitStmt(Stmt *S) {
1793 return false;
1794 }
1795
1796 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001797 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001798
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001799 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001800 bool VisitBinaryOperator(const BinaryOperator *E);
1801 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001802 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001803 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001804 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001805
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001806 bool VisitChooseExpr(const ChooseExpr *E)
1807 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1808 bool VisitUnaryExtension(const UnaryOperator *E)
1809 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001810 bool VisitUnaryReal(const UnaryOperator *E);
1811 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001812
John McCall189d6ef2010-10-09 01:34:31 +00001813 bool VisitDeclRefExpr(const DeclRefExpr *E);
1814
John McCallabd3a852010-05-07 22:08:54 +00001815 // FIXME: Missing: array subscript of vector, member of vector,
1816 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001817};
1818} // end anonymous namespace
1819
1820static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001821 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001822 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1823}
1824
John McCalldb7b72a2010-02-28 13:00:19 +00001825static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1826 QualType ResultTy,
1827 const Expr *Arg,
1828 bool SNaN,
1829 llvm::APFloat &Result) {
1830 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1831 if (!S) return false;
1832
1833 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1834
1835 llvm::APInt fill;
1836
1837 // Treat empty strings as if they were zero.
1838 if (S->getString().empty())
1839 fill = llvm::APInt(32, 0);
1840 else if (S->getString().getAsInteger(0, fill))
1841 return false;
1842
1843 if (SNaN)
1844 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1845 else
1846 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1847 return true;
1848}
1849
Chris Lattner019f4e82008-10-06 05:28:25 +00001850bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001851 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001852 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001853 case Builtin::BI__builtin_huge_val:
1854 case Builtin::BI__builtin_huge_valf:
1855 case Builtin::BI__builtin_huge_vall:
1856 case Builtin::BI__builtin_inf:
1857 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001858 case Builtin::BI__builtin_infl: {
1859 const llvm::fltSemantics &Sem =
1860 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001861 Result = llvm::APFloat::getInf(Sem);
1862 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001863 }
Mike Stump1eb44332009-09-09 15:08:12 +00001864
John McCalldb7b72a2010-02-28 13:00:19 +00001865 case Builtin::BI__builtin_nans:
1866 case Builtin::BI__builtin_nansf:
1867 case Builtin::BI__builtin_nansl:
1868 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1869 true, Result);
1870
Chris Lattner9e621712008-10-06 06:31:58 +00001871 case Builtin::BI__builtin_nan:
1872 case Builtin::BI__builtin_nanf:
1873 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001874 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001875 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001876 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1877 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001878
1879 case Builtin::BI__builtin_fabs:
1880 case Builtin::BI__builtin_fabsf:
1881 case Builtin::BI__builtin_fabsl:
1882 if (!EvaluateFloat(E->getArg(0), Result, Info))
1883 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001885 if (Result.isNegative())
1886 Result.changeSign();
1887 return true;
1888
Mike Stump1eb44332009-09-09 15:08:12 +00001889 case Builtin::BI__builtin_copysign:
1890 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001891 case Builtin::BI__builtin_copysignl: {
1892 APFloat RHS(0.);
1893 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1894 !EvaluateFloat(E->getArg(1), RHS, Info))
1895 return false;
1896 Result.copySign(RHS);
1897 return true;
1898 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001899 }
1900}
1901
John McCall189d6ef2010-10-09 01:34:31 +00001902bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1903 const Decl *D = E->getDecl();
1904 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
1905 const VarDecl *VD = cast<VarDecl>(D);
1906
1907 // Require the qualifiers to be const and not volatile.
1908 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
1909 if (!T.isConstQualified() || T.isVolatileQualified())
1910 return false;
1911
1912 const Expr *Init = VD->getAnyInitializer();
1913 if (!Init) return false;
1914
1915 if (APValue *V = VD->getEvaluatedValue()) {
1916 if (V->isFloat()) {
1917 Result = V->getFloat();
1918 return true;
1919 }
1920 return false;
1921 }
1922
1923 if (VD->isEvaluatingValue())
1924 return false;
1925
1926 VD->setEvaluatingValue();
1927
1928 Expr::EvalResult InitResult;
1929 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
1930 InitResult.Val.isFloat()) {
1931 // Cache the evaluated value in the variable declaration.
1932 Result = InitResult.Val.getFloat();
1933 VD->setEvaluatedValue(InitResult.Val);
1934 return true;
1935 }
1936
1937 VD->setEvaluatedValue(APValue());
1938 return false;
1939}
1940
John McCallabd3a852010-05-07 22:08:54 +00001941bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001942 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1943 ComplexValue CV;
1944 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1945 return false;
1946 Result = CV.FloatReal;
1947 return true;
1948 }
1949
1950 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00001951}
1952
1953bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001954 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1955 ComplexValue CV;
1956 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1957 return false;
1958 Result = CV.FloatImag;
1959 return true;
1960 }
1961
1962 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1963 Info.EvalResult.HasSideEffects = true;
1964 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
1965 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00001966 return true;
1967}
1968
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001969bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001970 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00001971 return false;
1972
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001973 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1974 return false;
1975
1976 switch (E->getOpcode()) {
1977 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00001978 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001979 return true;
John McCall2de56d12010-08-25 11:45:40 +00001980 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001981 Result.changeSign();
1982 return true;
1983 }
1984}
Chris Lattner019f4e82008-10-06 05:28:25 +00001985
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001986bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001987 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00001988 if (!EvaluateFloat(E->getRHS(), Result, Info))
1989 return false;
1990
1991 // If we can't evaluate the LHS, it might have side effects;
1992 // conservatively mark it.
1993 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1994 Info.EvalResult.HasSideEffects = true;
1995
1996 return true;
1997 }
1998
Anders Carlsson96e93662010-10-31 01:21:47 +00001999 // We can't evaluate pointer-to-member operations.
2000 if (E->isPtrMemOp())
2001 return false;
2002
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002003 // FIXME: Diagnostics? I really don't understand how the warnings
2004 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002005 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002006 if (!EvaluateFloat(E->getLHS(), Result, Info))
2007 return false;
2008 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2009 return false;
2010
2011 switch (E->getOpcode()) {
2012 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002013 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002014 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2015 return true;
John McCall2de56d12010-08-25 11:45:40 +00002016 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002017 Result.add(RHS, APFloat::rmNearestTiesToEven);
2018 return true;
John McCall2de56d12010-08-25 11:45:40 +00002019 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002020 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2021 return true;
John McCall2de56d12010-08-25 11:45:40 +00002022 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002023 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2024 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002025 }
2026}
2027
2028bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2029 Result = E->getValue();
2030 return true;
2031}
2032
Eli Friedman4efaa272008-11-12 09:44:48 +00002033bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2034 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002036 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002037 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002038 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002039 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002040 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002041 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002042 return true;
2043 }
2044 if (SubExpr->getType()->isRealFloatingType()) {
2045 if (!Visit(SubExpr))
2046 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002047 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2048 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002049 return true;
2050 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002051
2052 if (E->getCastKind() == CK_FloatingComplexToReal) {
2053 ComplexValue V;
2054 if (!EvaluateComplex(SubExpr, V, Info))
2055 return false;
2056 Result = V.getComplexFloatReal();
2057 return true;
2058 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002059
2060 return false;
2061}
2062
Douglas Gregored8abf12010-07-08 06:14:04 +00002063bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002064 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2065 return true;
2066}
2067
Eli Friedman67f85fc2009-12-04 02:12:53 +00002068bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2069 bool Cond;
2070 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2071 return false;
2072
2073 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2074}
2075
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002076//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002077// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002078//===----------------------------------------------------------------------===//
2079
2080namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002081class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002082 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002083 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002084 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002086public:
John McCallf4cf1a12010-05-07 17:22:02 +00002087 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2088 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002090 //===--------------------------------------------------------------------===//
2091 // Visitor Methods
2092 //===--------------------------------------------------------------------===//
2093
John McCallf4cf1a12010-05-07 17:22:02 +00002094 bool VisitStmt(Stmt *S) {
2095 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002096 }
Mike Stump1eb44332009-09-09 15:08:12 +00002097
John McCallf4cf1a12010-05-07 17:22:02 +00002098 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002099
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002100 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002101
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002102 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002103
John McCallf4cf1a12010-05-07 17:22:02 +00002104 bool VisitBinaryOperator(const BinaryOperator *E);
2105 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002106 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002107 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002108 { return Visit(E->getSubExpr()); }
2109 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedman2217c872009-02-22 11:46:18 +00002110 // conditional ?:, comma
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002111};
2112} // end anonymous namespace
2113
John McCallf4cf1a12010-05-07 17:22:02 +00002114static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2115 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002116 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002117 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002118}
2119
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002120bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2121 Expr* SubExpr = E->getSubExpr();
2122
2123 if (SubExpr->getType()->isRealFloatingType()) {
2124 Result.makeComplexFloat();
2125 APFloat &Imag = Result.FloatImag;
2126 if (!EvaluateFloat(SubExpr, Imag, Info))
2127 return false;
2128
2129 Result.FloatReal = APFloat(Imag.getSemantics());
2130 return true;
2131 } else {
2132 assert(SubExpr->getType()->isIntegerType() &&
2133 "Unexpected imaginary literal.");
2134
2135 Result.makeComplexInt();
2136 APSInt &Imag = Result.IntImag;
2137 if (!EvaluateInteger(SubExpr, Imag, Info))
2138 return false;
2139
2140 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2141 return true;
2142 }
2143}
2144
2145bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
2146 Expr* SubExpr = E->getSubExpr();
2147 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
2148 QualType SubType = SubExpr->getType();
2149
John McCall2bb5d002010-11-13 09:02:35 +00002150 // TODO: just trust CastKind
2151
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002152 if (SubType->isRealFloatingType()) {
2153 APFloat &Real = Result.FloatReal;
2154 if (!EvaluateFloat(SubExpr, Real, Info))
2155 return false;
2156
2157 if (EltType->isRealFloatingType()) {
2158 Result.makeComplexFloat();
2159 Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
2160 Result.FloatImag = APFloat(Real.getSemantics());
2161 return true;
2162 } else {
2163 Result.makeComplexInt();
2164 Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
2165 Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
2166 !Result.IntReal.isSigned());
2167 return true;
2168 }
2169 } else if (SubType->isIntegerType()) {
2170 APSInt &Real = Result.IntReal;
2171 if (!EvaluateInteger(SubExpr, Real, Info))
2172 return false;
2173
2174 if (EltType->isRealFloatingType()) {
2175 Result.makeComplexFloat();
2176 Result.FloatReal
2177 = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
2178 Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
2179 return true;
2180 } else {
2181 Result.makeComplexInt();
2182 Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
2183 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2184 return true;
2185 }
2186 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
2187 if (!Visit(SubExpr))
2188 return false;
2189
2190 QualType SrcType = CT->getElementType();
2191
2192 if (Result.isComplexFloat()) {
2193 if (EltType->isRealFloatingType()) {
2194 Result.makeComplexFloat();
2195 Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
2196 Result.FloatReal,
2197 Info.Ctx);
2198 Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
2199 Result.FloatImag,
2200 Info.Ctx);
2201 return true;
2202 } else {
2203 Result.makeComplexInt();
2204 Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
2205 Result.FloatReal,
2206 Info.Ctx);
2207 Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
2208 Result.FloatImag,
2209 Info.Ctx);
2210 return true;
2211 }
2212 } else {
2213 assert(Result.isComplexInt() && "Invalid evaluate result.");
2214 if (EltType->isRealFloatingType()) {
2215 Result.makeComplexFloat();
2216 Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
2217 Result.IntReal,
2218 Info.Ctx);
2219 Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2220 Result.IntImag,
2221 Info.Ctx);
2222 return true;
2223 } else {
2224 Result.makeComplexInt();
2225 Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2226 Result.IntReal,
2227 Info.Ctx);
2228 Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2229 Result.IntImag,
2230 Info.Ctx);
2231 return true;
2232 }
2233 }
2234 }
2235
2236 // FIXME: Handle more casts.
2237 return false;
2238}
2239
John McCallf4cf1a12010-05-07 17:22:02 +00002240bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2241 if (!Visit(E->getLHS()))
2242 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002243
John McCallf4cf1a12010-05-07 17:22:02 +00002244 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002245 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002246 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002247
Daniel Dunbar3f279872009-01-29 01:32:56 +00002248 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2249 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002250 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002251 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002252 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002253 if (Result.isComplexFloat()) {
2254 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2255 APFloat::rmNearestTiesToEven);
2256 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2257 APFloat::rmNearestTiesToEven);
2258 } else {
2259 Result.getComplexIntReal() += RHS.getComplexIntReal();
2260 Result.getComplexIntImag() += RHS.getComplexIntImag();
2261 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002262 break;
John McCall2de56d12010-08-25 11:45:40 +00002263 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002264 if (Result.isComplexFloat()) {
2265 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2266 APFloat::rmNearestTiesToEven);
2267 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2268 APFloat::rmNearestTiesToEven);
2269 } else {
2270 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2271 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2272 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002273 break;
John McCall2de56d12010-08-25 11:45:40 +00002274 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002275 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002276 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002277 APFloat &LHS_r = LHS.getComplexFloatReal();
2278 APFloat &LHS_i = LHS.getComplexFloatImag();
2279 APFloat &RHS_r = RHS.getComplexFloatReal();
2280 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Daniel Dunbar3f279872009-01-29 01:32:56 +00002282 APFloat Tmp = LHS_r;
2283 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2284 Result.getComplexFloatReal() = Tmp;
2285 Tmp = LHS_i;
2286 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2287 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2288
2289 Tmp = LHS_r;
2290 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2291 Result.getComplexFloatImag() = Tmp;
2292 Tmp = LHS_i;
2293 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2294 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2295 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002296 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002297 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002298 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2299 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002300 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002301 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2302 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2303 }
2304 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002305 }
2306
John McCallf4cf1a12010-05-07 17:22:02 +00002307 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002308}
2309
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002310//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002311// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002312//===----------------------------------------------------------------------===//
2313
John McCall42c8f872010-05-10 23:27:23 +00002314/// Evaluate - Return true if this is a constant which we can fold using
2315/// any crazy technique (that has nothing to do with language standards) that
2316/// we want to. If this function returns true, it returns the folded constant
2317/// in Result.
2318bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2319 const Expr *E = this;
2320 EvalInfo Info(Ctx, Result);
John McCallefdb83e2010-05-07 21:00:08 +00002321 if (E->getType()->isVectorType()) {
2322 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002323 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002324 } else if (E->getType()->isIntegerType()) {
2325 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002326 return false;
John McCall0f2b6922010-07-07 05:08:32 +00002327 if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2328 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002329 } else if (E->getType()->hasPointerRepresentation()) {
2330 LValue LV;
2331 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002332 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002333 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002334 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002335 LV.moveInto(Info.EvalResult.Val);
2336 } else if (E->getType()->isRealFloatingType()) {
2337 llvm::APFloat F(0.0);
2338 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002339 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002340
John McCallefdb83e2010-05-07 21:00:08 +00002341 Info.EvalResult.Val = APValue(F);
2342 } else if (E->getType()->isAnyComplexType()) {
2343 ComplexValue C;
2344 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002345 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002346 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002347 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002348 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002349
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002350 return true;
2351}
2352
John McCallcd7a4452010-01-05 23:42:56 +00002353bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2354 EvalResult Scratch;
2355 EvalInfo Info(Ctx, Scratch);
2356
2357 return HandleConversionToBool(this, Result, Info);
2358}
2359
Anders Carlsson1b782762009-04-10 04:54:13 +00002360bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2361 EvalInfo Info(Ctx, Result);
2362
John McCallefdb83e2010-05-07 21:00:08 +00002363 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002364 if (EvaluateLValue(this, LV, Info) &&
2365 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002366 IsGlobalLValue(LV.Base)) {
2367 LV.moveInto(Result.Val);
2368 return true;
2369 }
2370 return false;
2371}
2372
2373bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2374 EvalInfo Info(Ctx, Result);
2375
2376 LValue LV;
2377 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002378 LV.moveInto(Result.Val);
2379 return true;
2380 }
2381 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002382}
2383
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002384/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002385/// folded, but discard the result.
2386bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002387 EvalResult Result;
2388 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002389}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002390
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002391bool Expr::HasSideEffects(ASTContext &Ctx) const {
2392 Expr::EvalResult Result;
2393 EvalInfo Info(Ctx, Result);
2394 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2395}
2396
Anders Carlsson51fe9962008-11-22 21:04:56 +00002397APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002398 EvalResult EvalResult;
2399 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00002400 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002401 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002402 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002403
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002404 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002405}
John McCalld905f5a2010-05-07 05:32:02 +00002406
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002407 bool Expr::EvalResult::isGlobalLValue() const {
2408 assert(Val.isLValue());
2409 return IsGlobalLValue(Val.getLValueBase());
2410 }
2411
2412
John McCalld905f5a2010-05-07 05:32:02 +00002413/// isIntegerConstantExpr - this recursive routine will test if an expression is
2414/// an integer constant expression.
2415
2416/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2417/// comma, etc
2418///
2419/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2420/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2421/// cast+dereference.
2422
2423// CheckICE - This function does the fundamental ICE checking: the returned
2424// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2425// Note that to reduce code duplication, this helper does no evaluation
2426// itself; the caller checks whether the expression is evaluatable, and
2427// in the rare cases where CheckICE actually cares about the evaluated
2428// value, it calls into Evalute.
2429//
2430// Meanings of Val:
2431// 0: This expression is an ICE if it can be evaluated by Evaluate.
2432// 1: This expression is not an ICE, but if it isn't evaluated, it's
2433// a legal subexpression for an ICE. This return value is used to handle
2434// the comma operator in C99 mode.
2435// 2: This expression is not an ICE, and is not a legal subexpression for one.
2436
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002437namespace {
2438
John McCalld905f5a2010-05-07 05:32:02 +00002439struct ICEDiag {
2440 unsigned Val;
2441 SourceLocation Loc;
2442
2443 public:
2444 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2445 ICEDiag() : Val(0) {}
2446};
2447
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002448}
2449
2450static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002451
2452static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2453 Expr::EvalResult EVResult;
2454 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2455 !EVResult.Val.isInt()) {
2456 return ICEDiag(2, E->getLocStart());
2457 }
2458 return NoDiag();
2459}
2460
2461static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2462 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002463 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002464 return ICEDiag(2, E->getLocStart());
2465 }
2466
2467 switch (E->getStmtClass()) {
2468#define STMT(Node, Base) case Expr::Node##Class:
2469#define EXPR(Node, Base)
2470#include "clang/AST/StmtNodes.inc"
2471 case Expr::PredefinedExprClass:
2472 case Expr::FloatingLiteralClass:
2473 case Expr::ImaginaryLiteralClass:
2474 case Expr::StringLiteralClass:
2475 case Expr::ArraySubscriptExprClass:
2476 case Expr::MemberExprClass:
2477 case Expr::CompoundAssignOperatorClass:
2478 case Expr::CompoundLiteralExprClass:
2479 case Expr::ExtVectorElementExprClass:
2480 case Expr::InitListExprClass:
2481 case Expr::DesignatedInitExprClass:
2482 case Expr::ImplicitValueInitExprClass:
2483 case Expr::ParenListExprClass:
2484 case Expr::VAArgExprClass:
2485 case Expr::AddrLabelExprClass:
2486 case Expr::StmtExprClass:
2487 case Expr::CXXMemberCallExprClass:
2488 case Expr::CXXDynamicCastExprClass:
2489 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002490 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002491 case Expr::CXXNullPtrLiteralExprClass:
2492 case Expr::CXXThisExprClass:
2493 case Expr::CXXThrowExprClass:
2494 case Expr::CXXNewExprClass:
2495 case Expr::CXXDeleteExprClass:
2496 case Expr::CXXPseudoDestructorExprClass:
2497 case Expr::UnresolvedLookupExprClass:
2498 case Expr::DependentScopeDeclRefExprClass:
2499 case Expr::CXXConstructExprClass:
2500 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002501 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002502 case Expr::CXXTemporaryObjectExprClass:
2503 case Expr::CXXUnresolvedConstructExprClass:
2504 case Expr::CXXDependentScopeMemberExprClass:
2505 case Expr::UnresolvedMemberExprClass:
2506 case Expr::ObjCStringLiteralClass:
2507 case Expr::ObjCEncodeExprClass:
2508 case Expr::ObjCMessageExprClass:
2509 case Expr::ObjCSelectorExprClass:
2510 case Expr::ObjCProtocolExprClass:
2511 case Expr::ObjCIvarRefExprClass:
2512 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002513 case Expr::ObjCIsaExprClass:
2514 case Expr::ShuffleVectorExprClass:
2515 case Expr::BlockExprClass:
2516 case Expr::BlockDeclRefExprClass:
2517 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002518 case Expr::OpaqueValueExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002519 return ICEDiag(2, E->getLocStart());
2520
2521 case Expr::GNUNullExprClass:
2522 // GCC considers the GNU __null value to be an integral constant expression.
2523 return NoDiag();
2524
2525 case Expr::ParenExprClass:
2526 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2527 case Expr::IntegerLiteralClass:
2528 case Expr::CharacterLiteralClass:
2529 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002530 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002531 case Expr::TypesCompatibleExprClass:
2532 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002533 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002534 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002535 return NoDiag();
2536 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002537 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002538 const CallExpr *CE = cast<CallExpr>(E);
2539 if (CE->isBuiltinCall(Ctx))
2540 return CheckEvalInICE(E, Ctx);
2541 return ICEDiag(2, E->getLocStart());
2542 }
2543 case Expr::DeclRefExprClass:
2544 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2545 return NoDiag();
2546 if (Ctx.getLangOptions().CPlusPlus &&
2547 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2548 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2549
2550 // Parameter variables are never constants. Without this check,
2551 // getAnyInitializer() can find a default argument, which leads
2552 // to chaos.
2553 if (isa<ParmVarDecl>(D))
2554 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2555
2556 // C++ 7.1.5.1p2
2557 // A variable of non-volatile const-qualified integral or enumeration
2558 // type initialized by an ICE can be used in ICEs.
2559 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2560 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2561 if (Quals.hasVolatile() || !Quals.hasConst())
2562 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2563
2564 // Look for a declaration of this variable that has an initializer.
2565 const VarDecl *ID = 0;
2566 const Expr *Init = Dcl->getAnyInitializer(ID);
2567 if (Init) {
2568 if (ID->isInitKnownICE()) {
2569 // We have already checked whether this subexpression is an
2570 // integral constant expression.
2571 if (ID->isInitICE())
2572 return NoDiag();
2573 else
2574 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2575 }
2576
2577 // It's an ICE whether or not the definition we found is
2578 // out-of-line. See DR 721 and the discussion in Clang PR
2579 // 6206 for details.
2580
2581 if (Dcl->isCheckingICE()) {
2582 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2583 }
2584
2585 Dcl->setCheckingICE();
2586 ICEDiag Result = CheckICE(Init, Ctx);
2587 // Cache the result of the ICE test.
2588 Dcl->setInitKnownICE(Result.Val == 0);
2589 return Result;
2590 }
2591 }
2592 }
2593 return ICEDiag(2, E->getLocStart());
2594 case Expr::UnaryOperatorClass: {
2595 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2596 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002597 case UO_PostInc:
2598 case UO_PostDec:
2599 case UO_PreInc:
2600 case UO_PreDec:
2601 case UO_AddrOf:
2602 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002603 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002604 case UO_Extension:
2605 case UO_LNot:
2606 case UO_Plus:
2607 case UO_Minus:
2608 case UO_Not:
2609 case UO_Real:
2610 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002611 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002612 }
2613
2614 // OffsetOf falls through here.
2615 }
2616 case Expr::OffsetOfExprClass: {
2617 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2618 // Evaluate matches the proposed gcc behavior for cases like
2619 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2620 // compliance: we should warn earlier for offsetof expressions with
2621 // array subscripts that aren't ICEs, and if the array subscripts
2622 // are ICEs, the value of the offsetof must be an integer constant.
2623 return CheckEvalInICE(E, Ctx);
2624 }
2625 case Expr::SizeOfAlignOfExprClass: {
2626 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2627 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2628 return ICEDiag(2, E->getLocStart());
2629 return NoDiag();
2630 }
2631 case Expr::BinaryOperatorClass: {
2632 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2633 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002634 case BO_PtrMemD:
2635 case BO_PtrMemI:
2636 case BO_Assign:
2637 case BO_MulAssign:
2638 case BO_DivAssign:
2639 case BO_RemAssign:
2640 case BO_AddAssign:
2641 case BO_SubAssign:
2642 case BO_ShlAssign:
2643 case BO_ShrAssign:
2644 case BO_AndAssign:
2645 case BO_XorAssign:
2646 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002647 return ICEDiag(2, E->getLocStart());
2648
John McCall2de56d12010-08-25 11:45:40 +00002649 case BO_Mul:
2650 case BO_Div:
2651 case BO_Rem:
2652 case BO_Add:
2653 case BO_Sub:
2654 case BO_Shl:
2655 case BO_Shr:
2656 case BO_LT:
2657 case BO_GT:
2658 case BO_LE:
2659 case BO_GE:
2660 case BO_EQ:
2661 case BO_NE:
2662 case BO_And:
2663 case BO_Xor:
2664 case BO_Or:
2665 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002666 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2667 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002668 if (Exp->getOpcode() == BO_Div ||
2669 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002670 // Evaluate gives an error for undefined Div/Rem, so make sure
2671 // we don't evaluate one.
2672 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2673 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2674 if (REval == 0)
2675 return ICEDiag(1, E->getLocStart());
2676 if (REval.isSigned() && REval.isAllOnesValue()) {
2677 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2678 if (LEval.isMinSignedValue())
2679 return ICEDiag(1, E->getLocStart());
2680 }
2681 }
2682 }
John McCall2de56d12010-08-25 11:45:40 +00002683 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002684 if (Ctx.getLangOptions().C99) {
2685 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2686 // if it isn't evaluated.
2687 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2688 return ICEDiag(1, E->getLocStart());
2689 } else {
2690 // In both C89 and C++, commas in ICEs are illegal.
2691 return ICEDiag(2, E->getLocStart());
2692 }
2693 }
2694 if (LHSResult.Val >= RHSResult.Val)
2695 return LHSResult;
2696 return RHSResult;
2697 }
John McCall2de56d12010-08-25 11:45:40 +00002698 case BO_LAnd:
2699 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002700 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2701 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2702 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2703 // Rare case where the RHS has a comma "side-effect"; we need
2704 // to actually check the condition to see whether the side
2705 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00002706 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00002707 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2708 return RHSResult;
2709 return NoDiag();
2710 }
2711
2712 if (LHSResult.Val >= RHSResult.Val)
2713 return LHSResult;
2714 return RHSResult;
2715 }
2716 }
2717 }
2718 case Expr::ImplicitCastExprClass:
2719 case Expr::CStyleCastExprClass:
2720 case Expr::CXXFunctionalCastExprClass:
2721 case Expr::CXXStaticCastExprClass:
2722 case Expr::CXXReinterpretCastExprClass:
2723 case Expr::CXXConstCastExprClass: {
2724 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002725 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00002726 return CheckICE(SubExpr, Ctx);
2727 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2728 return NoDiag();
2729 return ICEDiag(2, E->getLocStart());
2730 }
2731 case Expr::ConditionalOperatorClass: {
2732 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2733 // If the condition (ignoring parens) is a __builtin_constant_p call,
2734 // then only the true side is actually considered in an integer constant
2735 // expression, and it is fully evaluated. This is an important GNU
2736 // extension. See GCC PR38377 for discussion.
2737 if (const CallExpr *CallCE
2738 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2739 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2740 Expr::EvalResult EVResult;
2741 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2742 !EVResult.Val.isInt()) {
2743 return ICEDiag(2, E->getLocStart());
2744 }
2745 return NoDiag();
2746 }
2747 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2748 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2749 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2750 if (CondResult.Val == 2)
2751 return CondResult;
2752 if (TrueResult.Val == 2)
2753 return TrueResult;
2754 if (FalseResult.Val == 2)
2755 return FalseResult;
2756 if (CondResult.Val == 1)
2757 return CondResult;
2758 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2759 return NoDiag();
2760 // Rare case where the diagnostics depend on which side is evaluated
2761 // Note that if we get here, CondResult is 0, and at least one of
2762 // TrueResult and FalseResult is non-zero.
2763 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2764 return FalseResult;
2765 }
2766 return TrueResult;
2767 }
2768 case Expr::CXXDefaultArgExprClass:
2769 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2770 case Expr::ChooseExprClass: {
2771 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2772 }
2773 }
2774
2775 // Silence a GCC warning
2776 return ICEDiag(2, E->getLocStart());
2777}
2778
2779bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2780 SourceLocation *Loc, bool isEvaluated) const {
2781 ICEDiag d = CheckICE(this, Ctx);
2782 if (d.Val != 0) {
2783 if (Loc) *Loc = d.Loc;
2784 return false;
2785 }
2786 EvalResult EvalResult;
2787 if (!Evaluate(EvalResult, Ctx))
2788 llvm_unreachable("ICE cannot be evaluated!");
2789 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2790 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2791 Result = EvalResult.Val.getInt();
2792 return true;
2793}