blob: d0b4c3193722c6b7e5bbe466b95ed958126191cb [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_Unknown: {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000536 // FIXME: The handling for CK_Unknown is ugly/shouldn't be necessary!
537
538 // Check for pointer->pointer cast
539 if (SubExpr->getType()->isPointerType() ||
540 SubExpr->getType()->isObjCObjectPointerType() ||
541 SubExpr->getType()->isNullPtrType() ||
542 SubExpr->getType()->isBlockPointerType())
543 return Visit(SubExpr);
544
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000545 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
John McCallefdb83e2010-05-07 21:00:08 +0000546 APValue Value;
547 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000548 break;
549
John McCallefdb83e2010-05-07 21:00:08 +0000550 if (Value.isInt()) {
551 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
552 Result.Base = 0;
553 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
554 return true;
555 } else {
556 Result.Base = Value.getLValueBase();
557 Result.Offset = Value.getLValueOffset();
558 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000559 }
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000560 }
561 break;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000562 }
Mike Stump1eb44332009-09-09 15:08:12 +0000563
John McCall2de56d12010-08-25 11:45:40 +0000564 case CK_NoOp:
565 case CK_BitCast:
566 case CK_LValueBitCast:
567 case CK_AnyPointerToObjCPointerCast:
568 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000569 return Visit(SubExpr);
570
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000571 case CK_DerivedToBase:
572 case CK_UncheckedDerivedToBase: {
573 LValue BaseLV;
574 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
575 return false;
576
577 // Now figure out the necessary offset to add to the baseLV to get from
578 // the derived class to the base class.
579 uint64_t Offset = 0;
580
581 QualType Ty = E->getSubExpr()->getType();
582 const CXXRecordDecl *DerivedDecl =
583 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
584
585 for (CastExpr::path_const_iterator PathI = E->path_begin(),
586 PathE = E->path_end(); PathI != PathE; ++PathI) {
587 const CXXBaseSpecifier *Base = *PathI;
588
589 // FIXME: If the base is virtual, we'd need to determine the type of the
590 // most derived class and we don't support that right now.
591 if (Base->isVirtual())
592 return false;
593
594 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
595 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
596
Anders Carlssona14f5972010-10-31 23:22:37 +0000597 Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000598 DerivedDecl = BaseDecl;
599 }
600
601 Result.Base = BaseLV.getLValueBase();
602 Result.Offset = BaseLV.getLValueOffset() +
603 CharUnits::fromQuantity(Offset / Info.Ctx.getCharWidth());
604 return true;
605 }
606
John McCall404cd162010-11-13 01:35:44 +0000607 case CK_NullToPointer: {
608 Result.Base = 0;
609 Result.Offset = CharUnits::Zero();
610 return true;
611 }
612
John McCall2de56d12010-08-25 11:45:40 +0000613 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000614 APValue Value;
615 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000616 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000617
John McCallefdb83e2010-05-07 21:00:08 +0000618 if (Value.isInt()) {
619 Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
620 Result.Base = 0;
621 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
622 return true;
623 } else {
624 // Cast is of an lvalue, no need to change value.
625 Result.Base = Value.getLValueBase();
626 Result.Offset = Value.getLValueOffset();
627 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000628 }
629 }
John McCall2de56d12010-08-25 11:45:40 +0000630 case CK_ArrayToPointerDecay:
631 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000632 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000633 }
634
John McCallefdb83e2010-05-07 21:00:08 +0000635 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000636}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000637
John McCallefdb83e2010-05-07 21:00:08 +0000638bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000639 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000640 Builtin::BI__builtin___CFStringMakeConstantString ||
641 E->isBuiltinCall(Info.Ctx) ==
642 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000643 return Success(E);
644 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000645}
646
John McCallefdb83e2010-05-07 21:00:08 +0000647bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000648 bool BoolResult;
649 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000650 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000651
652 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000653 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000654}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000655
656//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000657// Vector Evaluation
658//===----------------------------------------------------------------------===//
659
660namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000661 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000662 : public StmtVisitor<VectorExprEvaluator, APValue> {
663 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000664 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000665 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000666
Nate Begeman59b5da62009-01-18 03:20:47 +0000667 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Nate Begeman59b5da62009-01-18 03:20:47 +0000669 APValue VisitStmt(Stmt *S) {
670 return APValue();
671 }
Mike Stump1eb44332009-09-09 15:08:12 +0000672
Eli Friedman91110ee2009-02-23 04:23:56 +0000673 APValue VisitParenExpr(ParenExpr *E)
674 { return Visit(E->getSubExpr()); }
675 APValue VisitUnaryExtension(const UnaryOperator *E)
676 { return Visit(E->getSubExpr()); }
677 APValue VisitUnaryPlus(const UnaryOperator *E)
678 { return Visit(E->getSubExpr()); }
679 APValue VisitUnaryReal(const UnaryOperator *E)
680 { return Visit(E->getSubExpr()); }
681 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
682 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000683 APValue VisitCastExpr(const CastExpr* E);
684 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
685 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000686 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000687 APValue VisitChooseExpr(const ChooseExpr *E)
688 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000689 APValue VisitUnaryImag(const UnaryOperator *E);
690 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000691 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000692 // shufflevector, ExtVectorElementExpr
693 // (Note that these require implementing conversions
694 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000695 };
696} // end anonymous namespace
697
698static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
699 if (!E->getType()->isVectorType())
700 return false;
701 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
702 return !Result.isUninit();
703}
704
705APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000706 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000707 QualType EltTy = VTy->getElementType();
708 unsigned NElts = VTy->getNumElements();
709 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000710
Nate Begeman59b5da62009-01-18 03:20:47 +0000711 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000712 QualType SETy = SE->getType();
713 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000714
Nate Begemane8c9e922009-06-26 18:22:18 +0000715 // Check for vector->vector bitcast and scalar->vector splat.
716 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000717 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000718 } else if (SETy->isIntegerType()) {
719 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000720 if (!EvaluateInteger(SE, IntResult, Info))
721 return APValue();
722 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000723 } else if (SETy->isRealFloatingType()) {
724 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000725 if (!EvaluateFloat(SE, F, Info))
726 return APValue();
727 Result = APValue(F);
728 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000729 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000730
Nate Begemanc0b8b192009-07-01 07:50:47 +0000731 // For casts of a scalar to ExtVector, convert the scalar to the element type
732 // and splat it to all elements.
733 if (E->getType()->isExtVectorType()) {
734 if (EltTy->isIntegerType() && Result.isInt())
735 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
736 Info.Ctx));
737 else if (EltTy->isIntegerType())
738 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
739 Info.Ctx));
740 else if (EltTy->isRealFloatingType() && Result.isInt())
741 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
742 Info.Ctx));
743 else if (EltTy->isRealFloatingType())
744 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
745 Info.Ctx));
746 else
747 return APValue();
748
749 // Splat and create vector APValue.
750 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
751 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000752 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000753
754 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
755 // to the vector. To construct the APValue vector initializer, bitcast the
756 // initializing value to an APInt, and shift out the bits pertaining to each
757 // element.
758 APSInt Init;
759 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Nate Begemanc0b8b192009-07-01 07:50:47 +0000761 llvm::SmallVector<APValue, 4> Elts;
762 for (unsigned i = 0; i != NElts; ++i) {
763 APSInt Tmp = Init;
764 Tmp.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000765
Nate Begemanc0b8b192009-07-01 07:50:47 +0000766 if (EltTy->isIntegerType())
767 Elts.push_back(APValue(Tmp));
768 else if (EltTy->isRealFloatingType())
769 Elts.push_back(APValue(APFloat(Tmp)));
770 else
771 return APValue();
772
773 Init >>= EltWidth;
774 }
775 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000776}
777
Mike Stump1eb44332009-09-09 15:08:12 +0000778APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000779VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
780 return this->Visit(const_cast<Expr*>(E->getInitializer()));
781}
782
Mike Stump1eb44332009-09-09 15:08:12 +0000783APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000784VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000785 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000786 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000787 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000788
Nate Begeman59b5da62009-01-18 03:20:47 +0000789 QualType EltTy = VT->getElementType();
790 llvm::SmallVector<APValue, 4> Elements;
791
John McCalla7d6c222010-06-11 17:54:15 +0000792 // If a vector is initialized with a single element, that value
793 // becomes every element of the vector, not just the first.
794 // This is the behavior described in the IBM AltiVec documentation.
795 if (NumInits == 1) {
796 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000797 if (EltTy->isIntegerType()) {
798 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000799 if (!EvaluateInteger(E->getInit(0), sInt, Info))
800 return APValue();
801 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000802 } else {
803 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000804 if (!EvaluateFloat(E->getInit(0), f, Info))
805 return APValue();
806 InitValue = APValue(f);
807 }
808 for (unsigned i = 0; i < NumElements; i++) {
809 Elements.push_back(InitValue);
810 }
811 } else {
812 for (unsigned i = 0; i < NumElements; i++) {
813 if (EltTy->isIntegerType()) {
814 llvm::APSInt sInt(32);
815 if (i < NumInits) {
816 if (!EvaluateInteger(E->getInit(i), sInt, Info))
817 return APValue();
818 } else {
819 sInt = Info.Ctx.MakeIntValue(0, EltTy);
820 }
821 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000822 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000823 llvm::APFloat f(0.0);
824 if (i < NumInits) {
825 if (!EvaluateFloat(E->getInit(i), f, Info))
826 return APValue();
827 } else {
828 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
829 }
830 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000831 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000832 }
833 }
834 return APValue(&Elements[0], Elements.size());
835}
836
Mike Stump1eb44332009-09-09 15:08:12 +0000837APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000838VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000839 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000840 QualType EltTy = VT->getElementType();
841 APValue ZeroElement;
842 if (EltTy->isIntegerType())
843 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
844 else
845 ZeroElement =
846 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
847
848 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
849 return APValue(&Elements[0], Elements.size());
850}
851
852APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
853 bool BoolResult;
854 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
855 return APValue();
856
857 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
858
859 APValue Result;
860 if (EvaluateVector(EvalExpr, Result, Info))
861 return Result;
862 return APValue();
863}
864
Eli Friedman91110ee2009-02-23 04:23:56 +0000865APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
866 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
867 Info.EvalResult.HasSideEffects = true;
868 return GetZeroVector(E->getType());
869}
870
Nate Begeman59b5da62009-01-18 03:20:47 +0000871//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000872// Integer Evaluation
873//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000874
875namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000876class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000877 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000878 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000879 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000880public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000881 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000882 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000883
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000884 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000885 assert(E->getType()->isIntegralOrEnumerationType() &&
886 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000887 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000888 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000889 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000890 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000891 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000892 return true;
893 }
894
Daniel Dunbar131eb432009-02-19 09:06:44 +0000895 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000896 assert(E->getType()->isIntegralOrEnumerationType() &&
897 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000898 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000899 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000900 Result = APValue(APSInt(I));
901 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000902 return true;
903 }
904
905 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000906 assert(E->getType()->isIntegralOrEnumerationType() &&
907 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000908 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000909 return true;
910 }
911
Anders Carlsson82206e22008-11-30 18:14:57 +0000912 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000913 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000914 if (Info.EvalResult.Diag == 0) {
915 Info.EvalResult.DiagLoc = L;
916 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000917 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000918 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000919 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000920 }
Mike Stump1eb44332009-09-09 15:08:12 +0000921
Anders Carlssonc754aa62008-07-08 05:13:58 +0000922 //===--------------------------------------------------------------------===//
923 // Visitor Methods
924 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000925
Chris Lattner32fea9d2008-11-12 07:43:42 +0000926 bool VisitStmt(Stmt *) {
927 assert(0 && "This should be called on integers, stmts are not integers");
928 return false;
929 }
Mike Stump1eb44332009-09-09 15:08:12 +0000930
Chris Lattner32fea9d2008-11-12 07:43:42 +0000931 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000932 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000933 }
Mike Stump1eb44332009-09-09 15:08:12 +0000934
Chris Lattnerb542afe2008-07-11 19:10:17 +0000935 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000936
Chris Lattner4c4867e2008-07-12 00:38:25 +0000937 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000938 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000939 }
940 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000941 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000942 }
943 bool VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Daniel Dunbarac620de2008-10-24 08:07:57 +0000944 // Per gcc docs "this built-in function ignores top level
945 // qualifiers". We need to use the canonical version to properly
946 // be able to strip CRV qualifiers from the type.
947 QualType T0 = Info.Ctx.getCanonicalType(E->getArgType1());
948 QualType T1 = Info.Ctx.getCanonicalType(E->getArgType2());
Mike Stump1eb44332009-09-09 15:08:12 +0000949 return Success(Info.Ctx.typesAreCompatible(T0.getUnqualifiedType(),
Daniel Dunbar131eb432009-02-19 09:06:44 +0000950 T1.getUnqualifiedType()),
951 E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000952 }
Eli Friedman04309752009-11-24 05:28:59 +0000953
954 bool CheckReferencedDecl(const Expr *E, const Decl *D);
955 bool VisitDeclRefExpr(const DeclRefExpr *E) {
956 return CheckReferencedDecl(E, E->getDecl());
957 }
958 bool VisitMemberExpr(const MemberExpr *E) {
959 if (CheckReferencedDecl(E, E->getMemberDecl())) {
960 // Conservatively assume a MemberExpr will have side-effects
961 Info.EvalResult.HasSideEffects = true;
962 return true;
963 }
964 return false;
965 }
966
Eli Friedmanc4a26382010-02-13 00:10:10 +0000967 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000968 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000969 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +0000970 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +0000971 bool VisitConditionalOperator(const ConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +0000972
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000973 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +0000974 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
975
Anders Carlsson3068d112008-11-16 19:01:22 +0000976 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000977 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Anders Carlsson3f704562008-12-21 22:39:40 +0000980 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000981 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +0000982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Douglas Gregored8abf12010-07-08 06:14:04 +0000984 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000985 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +0000986 }
987
Eli Friedman664a1042009-02-27 04:45:43 +0000988 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
989 return Success(0, E);
990 }
991
Sebastian Redl64b45f72009-01-05 20:52:13 +0000992 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000993 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +0000994 }
995
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000996 bool VisitChooseExpr(const ChooseExpr *E) {
997 return Visit(E->getChosenSubExpr(Info.Ctx));
998 }
999
Eli Friedman722c7172009-02-28 03:59:05 +00001000 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001001 bool VisitUnaryImag(const UnaryOperator *E);
1002
Sebastian Redl295995c2010-09-10 20:55:47 +00001003 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
1004
Chris Lattnerfcee0012008-07-11 21:24:13 +00001005private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001006 CharUnits GetAlignOfExpr(const Expr *E);
1007 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001008 static QualType GetObjectType(const Expr *E);
1009 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001010 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001011};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001012} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001013
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001014static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001015 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001016 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1017}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001018
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001019static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001020 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001021
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001022 APValue Val;
1023 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1024 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001025 Result = Val.getInt();
1026 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001027}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001028
Eli Friedman04309752009-11-24 05:28:59 +00001029bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001030 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001031 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1032 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001033
1034 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001035 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001036 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1037 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001038
1039 if (isa<ParmVarDecl>(D))
1040 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1041
Eli Friedman04309752009-11-24 05:28:59 +00001042 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001043 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001044 if (APValue *V = VD->getEvaluatedValue()) {
1045 if (V->isInt())
1046 return Success(V->getInt(), E);
1047 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1048 }
1049
1050 if (VD->isEvaluatingValue())
1051 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1052
1053 VD->setEvaluatingValue();
1054
Eli Friedmana7dedf72010-09-06 00:10:32 +00001055 Expr::EvalResult EResult;
1056 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1057 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001058 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001059 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001060 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001061 return true;
1062 }
1063
Eli Friedmanc0131182009-12-03 20:31:57 +00001064 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001065 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001066 }
1067 }
1068
Chris Lattner4c4867e2008-07-12 00:38:25 +00001069 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001070 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001071}
1072
Chris Lattnera4d55d82008-10-06 06:40:35 +00001073/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1074/// as GCC.
1075static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1076 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001077 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001078 enum gcc_type_class {
1079 no_type_class = -1,
1080 void_type_class, integer_type_class, char_type_class,
1081 enumeral_type_class, boolean_type_class,
1082 pointer_type_class, reference_type_class, offset_type_class,
1083 real_type_class, complex_type_class,
1084 function_type_class, method_type_class,
1085 record_type_class, union_type_class,
1086 array_type_class, string_type_class,
1087 lang_type_class
1088 };
Mike Stump1eb44332009-09-09 15:08:12 +00001089
1090 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001091 // ideal, however it is what gcc does.
1092 if (E->getNumArgs() == 0)
1093 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Chris Lattnera4d55d82008-10-06 06:40:35 +00001095 QualType ArgTy = E->getArg(0)->getType();
1096 if (ArgTy->isVoidType())
1097 return void_type_class;
1098 else if (ArgTy->isEnumeralType())
1099 return enumeral_type_class;
1100 else if (ArgTy->isBooleanType())
1101 return boolean_type_class;
1102 else if (ArgTy->isCharType())
1103 return string_type_class; // gcc doesn't appear to use char_type_class
1104 else if (ArgTy->isIntegerType())
1105 return integer_type_class;
1106 else if (ArgTy->isPointerType())
1107 return pointer_type_class;
1108 else if (ArgTy->isReferenceType())
1109 return reference_type_class;
1110 else if (ArgTy->isRealType())
1111 return real_type_class;
1112 else if (ArgTy->isComplexType())
1113 return complex_type_class;
1114 else if (ArgTy->isFunctionType())
1115 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001116 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001117 return record_type_class;
1118 else if (ArgTy->isUnionType())
1119 return union_type_class;
1120 else if (ArgTy->isArrayType())
1121 return array_type_class;
1122 else if (ArgTy->isUnionType())
1123 return union_type_class;
1124 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1125 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1126 return -1;
1127}
1128
John McCall42c8f872010-05-10 23:27:23 +00001129/// Retrieves the "underlying object type" of the given expression,
1130/// as used by __builtin_object_size.
1131QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1132 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1133 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1134 return VD->getType();
1135 } else if (isa<CompoundLiteralExpr>(E)) {
1136 return E->getType();
1137 }
1138
1139 return QualType();
1140}
1141
1142bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1143 // TODO: Perhaps we should let LLVM lower this?
1144 LValue Base;
1145 if (!EvaluatePointer(E->getArg(0), Base, Info))
1146 return false;
1147
1148 // If we can prove the base is null, lower to zero now.
1149 const Expr *LVBase = Base.getLValueBase();
1150 if (!LVBase) return Success(0, E);
1151
1152 QualType T = GetObjectType(LVBase);
1153 if (T.isNull() ||
1154 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001155 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001156 T->isVariablyModifiedType() ||
1157 T->isDependentType())
1158 return false;
1159
1160 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1161 CharUnits Offset = Base.getLValueOffset();
1162
1163 if (!Offset.isNegative() && Offset <= Size)
1164 Size -= Offset;
1165 else
1166 Size = CharUnits::Zero();
1167 return Success(Size.getQuantity(), E);
1168}
1169
Eli Friedmanc4a26382010-02-13 00:10:10 +00001170bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001171 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001172 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001173 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001174
1175 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001176 if (TryEvaluateBuiltinObjectSize(E))
1177 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001178
Eric Christopherb2aaf512010-01-19 22:58:35 +00001179 // If evaluating the argument has side-effects we can't determine
1180 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001181 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001182 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001183 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001184 return Success(0, E);
1185 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001186
Mike Stump64eda9e2009-10-26 18:35:08 +00001187 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1188 }
1189
Chris Lattner019f4e82008-10-06 05:28:25 +00001190 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001191 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001193 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001194 // __builtin_constant_p always has one operand: it returns true if that
1195 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001196 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001197
1198 case Builtin::BI__builtin_eh_return_data_regno: {
1199 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1200 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1201 return Success(Operand, E);
1202 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001203
1204 case Builtin::BI__builtin_expect:
1205 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001206
1207 case Builtin::BIstrlen:
1208 case Builtin::BI__builtin_strlen:
1209 // As an extension, we support strlen() and __builtin_strlen() as constant
1210 // expressions when the argument is a string literal.
1211 if (StringLiteral *S
1212 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1213 // The string literal may have embedded null characters. Find the first
1214 // one and truncate there.
1215 llvm::StringRef Str = S->getString();
1216 llvm::StringRef::size_type Pos = Str.find(0);
1217 if (Pos != llvm::StringRef::npos)
1218 Str = Str.substr(0, Pos);
1219
1220 return Success(Str.size(), E);
1221 }
1222
1223 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001224 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001225}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001226
Chris Lattnerb542afe2008-07-11 19:10:17 +00001227bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001228 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001229 if (!Visit(E->getRHS()))
1230 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001231
Eli Friedman33ef1452009-02-26 10:19:36 +00001232 // If we can't evaluate the LHS, it might have side effects;
1233 // conservatively mark it.
1234 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1235 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001236
Anders Carlsson027f62e2008-12-01 02:07:06 +00001237 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001238 }
1239
1240 if (E->isLogicalOp()) {
1241 // These need to be handled specially because the operands aren't
1242 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001243 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001244
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001245 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001246 // We were able to evaluate the LHS, see if we can get away with not
1247 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001248 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001249 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001250
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001251 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001252 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001253 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001254 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001255 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001256 }
1257 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001258 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001259 // We can't evaluate the LHS; however, sometimes the result
1260 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001261 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1262 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001263 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001264 // must have had side effects.
1265 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001266
1267 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001268 }
1269 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001270 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001271
Eli Friedmana6afa762008-11-13 06:09:17 +00001272 return false;
1273 }
1274
Anders Carlsson286f85e2008-11-16 07:17:21 +00001275 QualType LHSTy = E->getLHS()->getType();
1276 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001277
1278 if (LHSTy->isAnyComplexType()) {
1279 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001280 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001281
1282 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1283 return false;
1284
1285 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1286 return false;
1287
1288 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001289 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001290 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001291 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001292 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1293
John McCall2de56d12010-08-25 11:45:40 +00001294 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001295 return Success((CR_r == APFloat::cmpEqual &&
1296 CR_i == APFloat::cmpEqual), E);
1297 else {
John McCall2de56d12010-08-25 11:45:40 +00001298 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001299 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001300 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001301 CR_r == APFloat::cmpLessThan ||
1302 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001303 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001304 CR_i == APFloat::cmpLessThan ||
1305 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001306 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001307 } else {
John McCall2de56d12010-08-25 11:45:40 +00001308 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001309 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1310 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1311 else {
John McCall2de56d12010-08-25 11:45:40 +00001312 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001313 "Invalid compex comparison.");
1314 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1315 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1316 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001317 }
1318 }
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Anders Carlsson286f85e2008-11-16 07:17:21 +00001320 if (LHSTy->isRealFloatingType() &&
1321 RHSTy->isRealFloatingType()) {
1322 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001323
Anders Carlsson286f85e2008-11-16 07:17:21 +00001324 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1325 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001326
Anders Carlsson286f85e2008-11-16 07:17:21 +00001327 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1328 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001329
Anders Carlsson286f85e2008-11-16 07:17:21 +00001330 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001331
Anders Carlsson286f85e2008-11-16 07:17:21 +00001332 switch (E->getOpcode()) {
1333 default:
1334 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001335 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001336 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001337 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001338 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001339 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001340 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001341 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001342 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001343 E);
John McCall2de56d12010-08-25 11:45:40 +00001344 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001345 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001346 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001347 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001348 || CR == APFloat::cmpLessThan
1349 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001350 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001351 }
Mike Stump1eb44332009-09-09 15:08:12 +00001352
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001353 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001354 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001355 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001356 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1357 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001358
John McCallefdb83e2010-05-07 21:00:08 +00001359 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001360 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1361 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001362
Eli Friedman5bc86102009-06-14 02:17:33 +00001363 // Reject any bases from the normal codepath; we special-case comparisons
1364 // to null.
1365 if (LHSValue.getLValueBase()) {
1366 if (!E->isEqualityOp())
1367 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001368 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001369 return false;
1370 bool bres;
1371 if (!EvalPointerValueAsBool(LHSValue, bres))
1372 return false;
John McCall2de56d12010-08-25 11:45:40 +00001373 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001374 } else if (RHSValue.getLValueBase()) {
1375 if (!E->isEqualityOp())
1376 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001377 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001378 return false;
1379 bool bres;
1380 if (!EvalPointerValueAsBool(RHSValue, bres))
1381 return false;
John McCall2de56d12010-08-25 11:45:40 +00001382 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001383 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001384
John McCall2de56d12010-08-25 11:45:40 +00001385 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001386 QualType Type = E->getLHS()->getType();
1387 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001388
Ken Dycka7305832010-01-15 12:37:54 +00001389 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001390 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001391 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001392
Ken Dycka7305832010-01-15 12:37:54 +00001393 CharUnits Diff = LHSValue.getLValueOffset() -
1394 RHSValue.getLValueOffset();
1395 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001396 }
1397 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001398 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001399 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001400 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001401 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1402 }
1403 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001404 }
1405 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001406 if (!LHSTy->isIntegralOrEnumerationType() ||
1407 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001408 // We can't continue from here for non-integral types, and they
1409 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001410 return false;
1411 }
1412
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001413 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001414 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001415 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001416
Eli Friedman42edd0d2009-03-24 01:14:50 +00001417 APValue RHSVal;
1418 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001419 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001420
1421 // Handle cases like (unsigned long)&a + 4.
1422 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001423 CharUnits Offset = Result.getLValueOffset();
1424 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1425 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001426 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001427 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001428 else
Ken Dycka7305832010-01-15 12:37:54 +00001429 Offset -= AdditionalOffset;
1430 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001431 return true;
1432 }
1433
1434 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001435 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001436 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001437 CharUnits Offset = RHSVal.getLValueOffset();
1438 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1439 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001440 return true;
1441 }
1442
1443 // All the following cases expect both operands to be an integer
1444 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001445 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001446
Eli Friedman42edd0d2009-03-24 01:14:50 +00001447 APSInt& RHS = RHSVal.getInt();
1448
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001449 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001450 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001451 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001452 case BO_Mul: return Success(Result.getInt() * RHS, E);
1453 case BO_Add: return Success(Result.getInt() + RHS, E);
1454 case BO_Sub: return Success(Result.getInt() - RHS, E);
1455 case BO_And: return Success(Result.getInt() & RHS, E);
1456 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1457 case BO_Or: return Success(Result.getInt() | RHS, E);
1458 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001459 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001460 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001461 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001462 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001463 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001464 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001465 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001466 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001467 // During constant-folding, a negative shift is an opposite shift.
1468 if (RHS.isSigned() && RHS.isNegative()) {
1469 RHS = -RHS;
1470 goto shift_right;
1471 }
1472
1473 shift_left:
1474 unsigned SA
1475 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001476 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001477 }
John McCall2de56d12010-08-25 11:45:40 +00001478 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001479 // During constant-folding, a negative shift is an opposite shift.
1480 if (RHS.isSigned() && RHS.isNegative()) {
1481 RHS = -RHS;
1482 goto shift_left;
1483 }
1484
1485 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001486 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001487 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1488 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001489 }
Mike Stump1eb44332009-09-09 15:08:12 +00001490
John McCall2de56d12010-08-25 11:45:40 +00001491 case BO_LT: return Success(Result.getInt() < RHS, E);
1492 case BO_GT: return Success(Result.getInt() > RHS, E);
1493 case BO_LE: return Success(Result.getInt() <= RHS, E);
1494 case BO_GE: return Success(Result.getInt() >= RHS, E);
1495 case BO_EQ: return Success(Result.getInt() == RHS, E);
1496 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001497 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001498}
1499
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001500bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001501 bool Cond;
1502 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001503 return false;
1504
Nuno Lopesa25bd552008-11-16 22:06:39 +00001505 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001506}
1507
Ken Dyck8b752f12010-01-27 17:10:57 +00001508CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001509 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1510 // the result is the size of the referenced type."
1511 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1512 // result shall be the alignment of the referenced type."
1513 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1514 T = Ref->getPointeeType();
1515
Chris Lattnere9feb472009-01-24 21:09:06 +00001516 // Get information about the alignment.
1517 unsigned CharSize = Info.Ctx.Target.getCharWidth();
Douglas Gregor18857642009-04-30 17:32:17 +00001518
Eli Friedman2be58612009-05-30 21:09:44 +00001519 // __alignof is defined to return the preferred alignment.
Ken Dyck8b752f12010-01-27 17:10:57 +00001520 return CharUnits::fromQuantity(
1521 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()) / CharSize);
Chris Lattnere9feb472009-01-24 21:09:06 +00001522}
1523
Ken Dyck8b752f12010-01-27 17:10:57 +00001524CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001525 E = E->IgnoreParens();
1526
1527 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001528 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001529 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001530 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1531 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001532
Chris Lattneraf707ab2009-01-24 21:53:27 +00001533 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001534 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1535 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001536
Chris Lattnere9feb472009-01-24 21:09:06 +00001537 return GetAlignOfType(E->getType());
1538}
1539
1540
Sebastian Redl05189992008-11-11 17:56:53 +00001541/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1542/// expression's type.
1543bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001544 // Handle alignof separately.
1545 if (!E->isSizeOf()) {
1546 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001547 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001548 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001549 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001550 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001551
Sebastian Redl05189992008-11-11 17:56:53 +00001552 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001553 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1554 // the result is the size of the referenced type."
1555 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1556 // result shall be the alignment of the referenced type."
1557 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1558 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001559
Daniel Dunbar131eb432009-02-19 09:06:44 +00001560 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1561 // extension.
1562 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1563 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001564
Chris Lattnerfcee0012008-07-11 21:24:13 +00001565 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001566 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001567 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001568
Chris Lattnere9feb472009-01-24 21:09:06 +00001569 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001570 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001571}
1572
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001573bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1574 CharUnits Result;
1575 unsigned n = E->getNumComponents();
1576 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1577 if (n == 0)
1578 return false;
1579 QualType CurrentType = E->getTypeSourceInfo()->getType();
1580 for (unsigned i = 0; i != n; ++i) {
1581 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1582 switch (ON.getKind()) {
1583 case OffsetOfExpr::OffsetOfNode::Array: {
1584 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1585 APSInt IdxResult;
1586 if (!EvaluateInteger(Idx, IdxResult, Info))
1587 return false;
1588 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1589 if (!AT)
1590 return false;
1591 CurrentType = AT->getElementType();
1592 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1593 Result += IdxResult.getSExtValue() * ElementSize;
1594 break;
1595 }
1596
1597 case OffsetOfExpr::OffsetOfNode::Field: {
1598 FieldDecl *MemberDecl = ON.getField();
1599 const RecordType *RT = CurrentType->getAs<RecordType>();
1600 if (!RT)
1601 return false;
1602 RecordDecl *RD = RT->getDecl();
1603 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1604 unsigned i = 0;
1605 // FIXME: It would be nice if we didn't have to loop here!
1606 for (RecordDecl::field_iterator Field = RD->field_begin(),
1607 FieldEnd = RD->field_end();
1608 Field != FieldEnd; (void)++Field, ++i) {
1609 if (*Field == MemberDecl)
1610 break;
1611 }
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001612 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1613 Result += CharUnits::fromQuantity(
1614 RL.getFieldOffset(i) / Info.Ctx.getCharWidth());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001615 CurrentType = MemberDecl->getType().getNonReferenceType();
1616 break;
1617 }
1618
1619 case OffsetOfExpr::OffsetOfNode::Identifier:
1620 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001621 return false;
1622
1623 case OffsetOfExpr::OffsetOfNode::Base: {
1624 CXXBaseSpecifier *BaseSpec = ON.getBase();
1625 if (BaseSpec->isVirtual())
1626 return false;
1627
1628 // Find the layout of the class whose base we are looking into.
1629 const RecordType *RT = CurrentType->getAs<RecordType>();
1630 if (!RT)
1631 return false;
1632 RecordDecl *RD = RT->getDecl();
1633 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1634
1635 // Find the base class itself.
1636 CurrentType = BaseSpec->getType();
1637 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1638 if (!BaseRT)
1639 return false;
1640
1641 // Add the offset to the base.
1642 Result += CharUnits::fromQuantity(
Anders Carlssona14f5972010-10-31 23:22:37 +00001643 RL.getBaseClassOffsetInBits(cast<CXXRecordDecl>(BaseRT->getDecl()))
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001644 / Info.Ctx.getCharWidth());
1645 break;
1646 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001647 }
1648 }
1649 return Success(Result.getQuantity(), E);
1650}
1651
Chris Lattnerb542afe2008-07-11 19:10:17 +00001652bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001653 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001654 // LNot's operand isn't necessarily an integer, so we handle it specially.
1655 bool bres;
1656 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1657 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001658 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001659 }
1660
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001661 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001662 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001663 return false;
1664
Chris Lattner87eae5e2008-07-11 22:52:41 +00001665 // Get the operand value into 'Result'.
1666 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001667 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001668
Chris Lattner75a48812008-07-11 22:15:16 +00001669 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001670 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001671 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1672 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001673 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001674 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001675 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1676 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001677 return true;
John McCall2de56d12010-08-25 11:45:40 +00001678 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001679 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001680 return true;
John McCall2de56d12010-08-25 11:45:40 +00001681 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001682 if (!Result.isInt()) return false;
1683 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001684 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001685 if (!Result.isInt()) return false;
1686 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001687 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001688}
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Chris Lattner732b2232008-07-12 01:15:53 +00001690/// HandleCast - This is used to evaluate implicit or explicit casts where the
1691/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001692bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001693 Expr *SubExpr = E->getSubExpr();
1694 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001695 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001696
Eli Friedman4efaa272008-11-12 09:44:48 +00001697 if (DestType->isBooleanType()) {
1698 bool BoolResult;
1699 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1700 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001701 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001702 }
1703
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001704 // Handle simple integer->integer casts.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001705 if (SrcType->isIntegralOrEnumerationType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001706 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001707 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001708
Eli Friedmanbe265702009-02-20 01:15:07 +00001709 if (!Result.isInt()) {
1710 // Only allow casts of lvalues if they are lossless.
1711 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1712 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001713
Daniel Dunbardd211642009-02-19 22:24:01 +00001714 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001715 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001716 }
Mike Stump1eb44332009-09-09 15:08:12 +00001717
Chris Lattner732b2232008-07-12 01:15:53 +00001718 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001719 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001720 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001721 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001722 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001723
Daniel Dunbardd211642009-02-19 22:24:01 +00001724 if (LV.getLValueBase()) {
1725 // Only allow based lvalue casts if they are lossless.
1726 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1727 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001728
John McCallefdb83e2010-05-07 21:00:08 +00001729 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001730 return true;
1731 }
1732
Ken Dycka7305832010-01-15 12:37:54 +00001733 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1734 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001735 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001736 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001737
Eli Friedmanbe265702009-02-20 01:15:07 +00001738 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1739 // This handles double-conversion cases, where there's both
1740 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001741 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001742 if (!EvaluateLValue(SubExpr, LV, Info))
1743 return false;
1744
1745 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1746 return false;
1747
John McCallefdb83e2010-05-07 21:00:08 +00001748 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001749 return true;
1750 }
1751
Eli Friedman1725f682009-04-22 19:23:09 +00001752 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001753 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001754 if (!EvaluateComplex(SubExpr, C, Info))
1755 return false;
1756 if (C.isComplexFloat())
1757 return Success(HandleFloatToIntCast(DestType, SrcType,
1758 C.getComplexFloatReal(), Info.Ctx),
1759 E);
1760 else
1761 return Success(HandleIntToIntCast(DestType, SrcType,
1762 C.getComplexIntReal(), Info.Ctx), E);
1763 }
Eli Friedman2217c872009-02-22 11:46:18 +00001764 // FIXME: Handle vectors
1765
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001766 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001767 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001768
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001769 APFloat F(0.0);
1770 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001771 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001772
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001773 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001774}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001775
Eli Friedman722c7172009-02-28 03:59:05 +00001776bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1777 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001778 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001779 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1780 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1781 return Success(LV.getComplexIntReal(), E);
1782 }
1783
1784 return Visit(E->getSubExpr());
1785}
1786
Eli Friedman664a1042009-02-27 04:45:43 +00001787bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001788 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001789 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001790 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1791 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1792 return Success(LV.getComplexIntImag(), E);
1793 }
1794
Eli Friedman664a1042009-02-27 04:45:43 +00001795 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1796 Info.EvalResult.HasSideEffects = true;
1797 return Success(0, E);
1798}
1799
Sebastian Redl295995c2010-09-10 20:55:47 +00001800bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1801 return Success(E->getValue(), E);
1802}
1803
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001804//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001805// Float Evaluation
1806//===----------------------------------------------------------------------===//
1807
1808namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001809class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001810 : public StmtVisitor<FloatExprEvaluator, bool> {
1811 EvalInfo &Info;
1812 APFloat &Result;
1813public:
1814 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1815 : Info(info), Result(result) {}
1816
1817 bool VisitStmt(Stmt *S) {
1818 return false;
1819 }
1820
1821 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001822 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001823
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001824 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001825 bool VisitBinaryOperator(const BinaryOperator *E);
1826 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001827 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001828 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001829 bool VisitConditionalOperator(ConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001830
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001831 bool VisitChooseExpr(const ChooseExpr *E)
1832 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1833 bool VisitUnaryExtension(const UnaryOperator *E)
1834 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001835 bool VisitUnaryReal(const UnaryOperator *E);
1836 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001837
John McCall189d6ef2010-10-09 01:34:31 +00001838 bool VisitDeclRefExpr(const DeclRefExpr *E);
1839
John McCallabd3a852010-05-07 22:08:54 +00001840 // FIXME: Missing: array subscript of vector, member of vector,
1841 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001842};
1843} // end anonymous namespace
1844
1845static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001846 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001847 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1848}
1849
John McCalldb7b72a2010-02-28 13:00:19 +00001850static bool TryEvaluateBuiltinNaN(ASTContext &Context,
1851 QualType ResultTy,
1852 const Expr *Arg,
1853 bool SNaN,
1854 llvm::APFloat &Result) {
1855 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1856 if (!S) return false;
1857
1858 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1859
1860 llvm::APInt fill;
1861
1862 // Treat empty strings as if they were zero.
1863 if (S->getString().empty())
1864 fill = llvm::APInt(32, 0);
1865 else if (S->getString().getAsInteger(0, fill))
1866 return false;
1867
1868 if (SNaN)
1869 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1870 else
1871 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1872 return true;
1873}
1874
Chris Lattner019f4e82008-10-06 05:28:25 +00001875bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001876 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001877 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001878 case Builtin::BI__builtin_huge_val:
1879 case Builtin::BI__builtin_huge_valf:
1880 case Builtin::BI__builtin_huge_vall:
1881 case Builtin::BI__builtin_inf:
1882 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001883 case Builtin::BI__builtin_infl: {
1884 const llvm::fltSemantics &Sem =
1885 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001886 Result = llvm::APFloat::getInf(Sem);
1887 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001888 }
Mike Stump1eb44332009-09-09 15:08:12 +00001889
John McCalldb7b72a2010-02-28 13:00:19 +00001890 case Builtin::BI__builtin_nans:
1891 case Builtin::BI__builtin_nansf:
1892 case Builtin::BI__builtin_nansl:
1893 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1894 true, Result);
1895
Chris Lattner9e621712008-10-06 06:31:58 +00001896 case Builtin::BI__builtin_nan:
1897 case Builtin::BI__builtin_nanf:
1898 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001899 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001900 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001901 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1902 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001903
1904 case Builtin::BI__builtin_fabs:
1905 case Builtin::BI__builtin_fabsf:
1906 case Builtin::BI__builtin_fabsl:
1907 if (!EvaluateFloat(E->getArg(0), Result, Info))
1908 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001909
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001910 if (Result.isNegative())
1911 Result.changeSign();
1912 return true;
1913
Mike Stump1eb44332009-09-09 15:08:12 +00001914 case Builtin::BI__builtin_copysign:
1915 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001916 case Builtin::BI__builtin_copysignl: {
1917 APFloat RHS(0.);
1918 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1919 !EvaluateFloat(E->getArg(1), RHS, Info))
1920 return false;
1921 Result.copySign(RHS);
1922 return true;
1923 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001924 }
1925}
1926
John McCall189d6ef2010-10-09 01:34:31 +00001927bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1928 const Decl *D = E->getDecl();
1929 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
1930 const VarDecl *VD = cast<VarDecl>(D);
1931
1932 // Require the qualifiers to be const and not volatile.
1933 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
1934 if (!T.isConstQualified() || T.isVolatileQualified())
1935 return false;
1936
1937 const Expr *Init = VD->getAnyInitializer();
1938 if (!Init) return false;
1939
1940 if (APValue *V = VD->getEvaluatedValue()) {
1941 if (V->isFloat()) {
1942 Result = V->getFloat();
1943 return true;
1944 }
1945 return false;
1946 }
1947
1948 if (VD->isEvaluatingValue())
1949 return false;
1950
1951 VD->setEvaluatingValue();
1952
1953 Expr::EvalResult InitResult;
1954 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
1955 InitResult.Val.isFloat()) {
1956 // Cache the evaluated value in the variable declaration.
1957 Result = InitResult.Val.getFloat();
1958 VD->setEvaluatedValue(InitResult.Val);
1959 return true;
1960 }
1961
1962 VD->setEvaluatedValue(APValue());
1963 return false;
1964}
1965
John McCallabd3a852010-05-07 22:08:54 +00001966bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001967 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1968 ComplexValue CV;
1969 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1970 return false;
1971 Result = CV.FloatReal;
1972 return true;
1973 }
1974
1975 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00001976}
1977
1978bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00001979 if (E->getSubExpr()->getType()->isAnyComplexType()) {
1980 ComplexValue CV;
1981 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
1982 return false;
1983 Result = CV.FloatImag;
1984 return true;
1985 }
1986
1987 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1988 Info.EvalResult.HasSideEffects = true;
1989 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
1990 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00001991 return true;
1992}
1993
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001994bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001995 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00001996 return false;
1997
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001998 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
1999 return false;
2000
2001 switch (E->getOpcode()) {
2002 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002003 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002004 return true;
John McCall2de56d12010-08-25 11:45:40 +00002005 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002006 Result.changeSign();
2007 return true;
2008 }
2009}
Chris Lattner019f4e82008-10-06 05:28:25 +00002010
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002011bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002012 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002013 if (!EvaluateFloat(E->getRHS(), Result, Info))
2014 return false;
2015
2016 // If we can't evaluate the LHS, it might have side effects;
2017 // conservatively mark it.
2018 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2019 Info.EvalResult.HasSideEffects = true;
2020
2021 return true;
2022 }
2023
Anders Carlsson96e93662010-10-31 01:21:47 +00002024 // We can't evaluate pointer-to-member operations.
2025 if (E->isPtrMemOp())
2026 return false;
2027
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002028 // FIXME: Diagnostics? I really don't understand how the warnings
2029 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002030 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002031 if (!EvaluateFloat(E->getLHS(), Result, Info))
2032 return false;
2033 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2034 return false;
2035
2036 switch (E->getOpcode()) {
2037 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002038 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002039 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2040 return true;
John McCall2de56d12010-08-25 11:45:40 +00002041 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002042 Result.add(RHS, APFloat::rmNearestTiesToEven);
2043 return true;
John McCall2de56d12010-08-25 11:45:40 +00002044 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002045 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2046 return true;
John McCall2de56d12010-08-25 11:45:40 +00002047 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002048 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2049 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002050 }
2051}
2052
2053bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2054 Result = E->getValue();
2055 return true;
2056}
2057
Eli Friedman4efaa272008-11-12 09:44:48 +00002058bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2059 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002061 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002062 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002063 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002064 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002065 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002066 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002067 return true;
2068 }
2069 if (SubExpr->getType()->isRealFloatingType()) {
2070 if (!Visit(SubExpr))
2071 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002072 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2073 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002074 return true;
2075 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002076
2077 if (E->getCastKind() == CK_FloatingComplexToReal) {
2078 ComplexValue V;
2079 if (!EvaluateComplex(SubExpr, V, Info))
2080 return false;
2081 Result = V.getComplexFloatReal();
2082 return true;
2083 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002084
2085 return false;
2086}
2087
Douglas Gregored8abf12010-07-08 06:14:04 +00002088bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002089 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2090 return true;
2091}
2092
Eli Friedman67f85fc2009-12-04 02:12:53 +00002093bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2094 bool Cond;
2095 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2096 return false;
2097
2098 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2099}
2100
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002101//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002102// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002103//===----------------------------------------------------------------------===//
2104
2105namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002106class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002107 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002108 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002109 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002111public:
John McCallf4cf1a12010-05-07 17:22:02 +00002112 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2113 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002115 //===--------------------------------------------------------------------===//
2116 // Visitor Methods
2117 //===--------------------------------------------------------------------===//
2118
John McCallf4cf1a12010-05-07 17:22:02 +00002119 bool VisitStmt(Stmt *S) {
2120 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002121 }
Mike Stump1eb44332009-09-09 15:08:12 +00002122
John McCallf4cf1a12010-05-07 17:22:02 +00002123 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002124
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002125 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002126
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002127 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002128
John McCallf4cf1a12010-05-07 17:22:02 +00002129 bool VisitBinaryOperator(const BinaryOperator *E);
2130 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002131 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002132 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002133 { return Visit(E->getSubExpr()); }
2134 // FIXME Missing: unary +/-/~, binary div, ImplicitValueInitExpr,
Eli Friedman2217c872009-02-22 11:46:18 +00002135 // conditional ?:, comma
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002136};
2137} // end anonymous namespace
2138
John McCallf4cf1a12010-05-07 17:22:02 +00002139static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2140 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002141 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002142 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002143}
2144
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002145bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2146 Expr* SubExpr = E->getSubExpr();
2147
2148 if (SubExpr->getType()->isRealFloatingType()) {
2149 Result.makeComplexFloat();
2150 APFloat &Imag = Result.FloatImag;
2151 if (!EvaluateFloat(SubExpr, Imag, Info))
2152 return false;
2153
2154 Result.FloatReal = APFloat(Imag.getSemantics());
2155 return true;
2156 } else {
2157 assert(SubExpr->getType()->isIntegerType() &&
2158 "Unexpected imaginary literal.");
2159
2160 Result.makeComplexInt();
2161 APSInt &Imag = Result.IntImag;
2162 if (!EvaluateInteger(SubExpr, Imag, Info))
2163 return false;
2164
2165 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2166 return true;
2167 }
2168}
2169
2170bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
2171 Expr* SubExpr = E->getSubExpr();
2172 QualType EltType = E->getType()->getAs<ComplexType>()->getElementType();
2173 QualType SubType = SubExpr->getType();
2174
John McCall2bb5d002010-11-13 09:02:35 +00002175 // TODO: just trust CastKind
2176
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002177 if (SubType->isRealFloatingType()) {
2178 APFloat &Real = Result.FloatReal;
2179 if (!EvaluateFloat(SubExpr, Real, Info))
2180 return false;
2181
2182 if (EltType->isRealFloatingType()) {
2183 Result.makeComplexFloat();
2184 Real = HandleFloatToFloatCast(EltType, SubType, Real, Info.Ctx);
2185 Result.FloatImag = APFloat(Real.getSemantics());
2186 return true;
2187 } else {
2188 Result.makeComplexInt();
2189 Result.IntReal = HandleFloatToIntCast(EltType, SubType, Real, Info.Ctx);
2190 Result.IntImag = APSInt(Result.IntReal.getBitWidth(),
2191 !Result.IntReal.isSigned());
2192 return true;
2193 }
2194 } else if (SubType->isIntegerType()) {
2195 APSInt &Real = Result.IntReal;
2196 if (!EvaluateInteger(SubExpr, Real, Info))
2197 return false;
2198
2199 if (EltType->isRealFloatingType()) {
2200 Result.makeComplexFloat();
2201 Result.FloatReal
2202 = HandleIntToFloatCast(EltType, SubType, Real, Info.Ctx);
2203 Result.FloatImag = APFloat(Result.FloatReal.getSemantics());
2204 return true;
2205 } else {
2206 Result.makeComplexInt();
2207 Real = HandleIntToIntCast(EltType, SubType, Real, Info.Ctx);
2208 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2209 return true;
2210 }
2211 } else if (const ComplexType *CT = SubType->getAs<ComplexType>()) {
2212 if (!Visit(SubExpr))
2213 return false;
2214
2215 QualType SrcType = CT->getElementType();
2216
2217 if (Result.isComplexFloat()) {
2218 if (EltType->isRealFloatingType()) {
2219 Result.makeComplexFloat();
2220 Result.FloatReal = HandleFloatToFloatCast(EltType, SrcType,
2221 Result.FloatReal,
2222 Info.Ctx);
2223 Result.FloatImag = HandleFloatToFloatCast(EltType, SrcType,
2224 Result.FloatImag,
2225 Info.Ctx);
2226 return true;
2227 } else {
2228 Result.makeComplexInt();
2229 Result.IntReal = HandleFloatToIntCast(EltType, SrcType,
2230 Result.FloatReal,
2231 Info.Ctx);
2232 Result.IntImag = HandleFloatToIntCast(EltType, SrcType,
2233 Result.FloatImag,
2234 Info.Ctx);
2235 return true;
2236 }
2237 } else {
2238 assert(Result.isComplexInt() && "Invalid evaluate result.");
2239 if (EltType->isRealFloatingType()) {
2240 Result.makeComplexFloat();
2241 Result.FloatReal = HandleIntToFloatCast(EltType, SrcType,
2242 Result.IntReal,
2243 Info.Ctx);
2244 Result.FloatImag = HandleIntToFloatCast(EltType, SrcType,
2245 Result.IntImag,
2246 Info.Ctx);
2247 return true;
2248 } else {
2249 Result.makeComplexInt();
2250 Result.IntReal = HandleIntToIntCast(EltType, SrcType,
2251 Result.IntReal,
2252 Info.Ctx);
2253 Result.IntImag = HandleIntToIntCast(EltType, SrcType,
2254 Result.IntImag,
2255 Info.Ctx);
2256 return true;
2257 }
2258 }
2259 }
2260
2261 // FIXME: Handle more casts.
2262 return false;
2263}
2264
John McCallf4cf1a12010-05-07 17:22:02 +00002265bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
2266 if (!Visit(E->getLHS()))
2267 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002268
John McCallf4cf1a12010-05-07 17:22:02 +00002269 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002270 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002271 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002272
Daniel Dunbar3f279872009-01-29 01:32:56 +00002273 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2274 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002275 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002276 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002277 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002278 if (Result.isComplexFloat()) {
2279 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2280 APFloat::rmNearestTiesToEven);
2281 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2282 APFloat::rmNearestTiesToEven);
2283 } else {
2284 Result.getComplexIntReal() += RHS.getComplexIntReal();
2285 Result.getComplexIntImag() += RHS.getComplexIntImag();
2286 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002287 break;
John McCall2de56d12010-08-25 11:45:40 +00002288 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002289 if (Result.isComplexFloat()) {
2290 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2291 APFloat::rmNearestTiesToEven);
2292 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2293 APFloat::rmNearestTiesToEven);
2294 } else {
2295 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2296 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2297 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002298 break;
John McCall2de56d12010-08-25 11:45:40 +00002299 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002300 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002301 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002302 APFloat &LHS_r = LHS.getComplexFloatReal();
2303 APFloat &LHS_i = LHS.getComplexFloatImag();
2304 APFloat &RHS_r = RHS.getComplexFloatReal();
2305 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002306
Daniel Dunbar3f279872009-01-29 01:32:56 +00002307 APFloat Tmp = LHS_r;
2308 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2309 Result.getComplexFloatReal() = Tmp;
2310 Tmp = LHS_i;
2311 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2312 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2313
2314 Tmp = LHS_r;
2315 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2316 Result.getComplexFloatImag() = Tmp;
2317 Tmp = LHS_i;
2318 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2319 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2320 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002321 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002322 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002323 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2324 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002325 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002326 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2327 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2328 }
2329 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002330 }
2331
John McCallf4cf1a12010-05-07 17:22:02 +00002332 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002333}
2334
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002335//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002336// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002337//===----------------------------------------------------------------------===//
2338
John McCall42c8f872010-05-10 23:27:23 +00002339/// Evaluate - Return true if this is a constant which we can fold using
2340/// any crazy technique (that has nothing to do with language standards) that
2341/// we want to. If this function returns true, it returns the folded constant
2342/// in Result.
2343bool Expr::Evaluate(EvalResult &Result, ASTContext &Ctx) const {
2344 const Expr *E = this;
2345 EvalInfo Info(Ctx, Result);
John McCallefdb83e2010-05-07 21:00:08 +00002346 if (E->getType()->isVectorType()) {
2347 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002348 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002349 } else if (E->getType()->isIntegerType()) {
2350 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002351 return false;
John McCall0f2b6922010-07-07 05:08:32 +00002352 if (Result.Val.isLValue() && !IsGlobalLValue(Result.Val.getLValueBase()))
2353 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002354 } else if (E->getType()->hasPointerRepresentation()) {
2355 LValue LV;
2356 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002357 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002358 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002359 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002360 LV.moveInto(Info.EvalResult.Val);
2361 } else if (E->getType()->isRealFloatingType()) {
2362 llvm::APFloat F(0.0);
2363 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002364 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002365
John McCallefdb83e2010-05-07 21:00:08 +00002366 Info.EvalResult.Val = APValue(F);
2367 } else if (E->getType()->isAnyComplexType()) {
2368 ComplexValue C;
2369 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002370 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002371 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002372 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002373 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002374
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002375 return true;
2376}
2377
John McCallcd7a4452010-01-05 23:42:56 +00002378bool Expr::EvaluateAsBooleanCondition(bool &Result, ASTContext &Ctx) const {
2379 EvalResult Scratch;
2380 EvalInfo Info(Ctx, Scratch);
2381
2382 return HandleConversionToBool(this, Result, Info);
2383}
2384
Anders Carlsson1b782762009-04-10 04:54:13 +00002385bool Expr::EvaluateAsLValue(EvalResult &Result, ASTContext &Ctx) const {
2386 EvalInfo Info(Ctx, Result);
2387
John McCallefdb83e2010-05-07 21:00:08 +00002388 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002389 if (EvaluateLValue(this, LV, Info) &&
2390 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002391 IsGlobalLValue(LV.Base)) {
2392 LV.moveInto(Result.Val);
2393 return true;
2394 }
2395 return false;
2396}
2397
2398bool Expr::EvaluateAsAnyLValue(EvalResult &Result, ASTContext &Ctx) const {
2399 EvalInfo Info(Ctx, Result);
2400
2401 LValue LV;
2402 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002403 LV.moveInto(Result.Val);
2404 return true;
2405 }
2406 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002407}
2408
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002409/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002410/// folded, but discard the result.
2411bool Expr::isEvaluatable(ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002412 EvalResult Result;
2413 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002414}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002415
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002416bool Expr::HasSideEffects(ASTContext &Ctx) const {
2417 Expr::EvalResult Result;
2418 EvalInfo Info(Ctx, Result);
2419 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2420}
2421
Anders Carlsson51fe9962008-11-22 21:04:56 +00002422APSInt Expr::EvaluateAsInt(ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002423 EvalResult EvalResult;
2424 bool Result = Evaluate(EvalResult, Ctx);
Daniel Dunbarf1853192009-01-15 18:32:35 +00002425 Result = Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002426 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002427 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002428
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002429 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002430}
John McCalld905f5a2010-05-07 05:32:02 +00002431
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002432 bool Expr::EvalResult::isGlobalLValue() const {
2433 assert(Val.isLValue());
2434 return IsGlobalLValue(Val.getLValueBase());
2435 }
2436
2437
John McCalld905f5a2010-05-07 05:32:02 +00002438/// isIntegerConstantExpr - this recursive routine will test if an expression is
2439/// an integer constant expression.
2440
2441/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2442/// comma, etc
2443///
2444/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2445/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2446/// cast+dereference.
2447
2448// CheckICE - This function does the fundamental ICE checking: the returned
2449// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2450// Note that to reduce code duplication, this helper does no evaluation
2451// itself; the caller checks whether the expression is evaluatable, and
2452// in the rare cases where CheckICE actually cares about the evaluated
2453// value, it calls into Evalute.
2454//
2455// Meanings of Val:
2456// 0: This expression is an ICE if it can be evaluated by Evaluate.
2457// 1: This expression is not an ICE, but if it isn't evaluated, it's
2458// a legal subexpression for an ICE. This return value is used to handle
2459// the comma operator in C99 mode.
2460// 2: This expression is not an ICE, and is not a legal subexpression for one.
2461
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002462namespace {
2463
John McCalld905f5a2010-05-07 05:32:02 +00002464struct ICEDiag {
2465 unsigned Val;
2466 SourceLocation Loc;
2467
2468 public:
2469 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2470 ICEDiag() : Val(0) {}
2471};
2472
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002473}
2474
2475static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002476
2477static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2478 Expr::EvalResult EVResult;
2479 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2480 !EVResult.Val.isInt()) {
2481 return ICEDiag(2, E->getLocStart());
2482 }
2483 return NoDiag();
2484}
2485
2486static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2487 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002488 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002489 return ICEDiag(2, E->getLocStart());
2490 }
2491
2492 switch (E->getStmtClass()) {
2493#define STMT(Node, Base) case Expr::Node##Class:
2494#define EXPR(Node, Base)
2495#include "clang/AST/StmtNodes.inc"
2496 case Expr::PredefinedExprClass:
2497 case Expr::FloatingLiteralClass:
2498 case Expr::ImaginaryLiteralClass:
2499 case Expr::StringLiteralClass:
2500 case Expr::ArraySubscriptExprClass:
2501 case Expr::MemberExprClass:
2502 case Expr::CompoundAssignOperatorClass:
2503 case Expr::CompoundLiteralExprClass:
2504 case Expr::ExtVectorElementExprClass:
2505 case Expr::InitListExprClass:
2506 case Expr::DesignatedInitExprClass:
2507 case Expr::ImplicitValueInitExprClass:
2508 case Expr::ParenListExprClass:
2509 case Expr::VAArgExprClass:
2510 case Expr::AddrLabelExprClass:
2511 case Expr::StmtExprClass:
2512 case Expr::CXXMemberCallExprClass:
2513 case Expr::CXXDynamicCastExprClass:
2514 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002515 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002516 case Expr::CXXNullPtrLiteralExprClass:
2517 case Expr::CXXThisExprClass:
2518 case Expr::CXXThrowExprClass:
2519 case Expr::CXXNewExprClass:
2520 case Expr::CXXDeleteExprClass:
2521 case Expr::CXXPseudoDestructorExprClass:
2522 case Expr::UnresolvedLookupExprClass:
2523 case Expr::DependentScopeDeclRefExprClass:
2524 case Expr::CXXConstructExprClass:
2525 case Expr::CXXBindTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002526 case Expr::CXXExprWithTemporariesClass:
2527 case Expr::CXXTemporaryObjectExprClass:
2528 case Expr::CXXUnresolvedConstructExprClass:
2529 case Expr::CXXDependentScopeMemberExprClass:
2530 case Expr::UnresolvedMemberExprClass:
2531 case Expr::ObjCStringLiteralClass:
2532 case Expr::ObjCEncodeExprClass:
2533 case Expr::ObjCMessageExprClass:
2534 case Expr::ObjCSelectorExprClass:
2535 case Expr::ObjCProtocolExprClass:
2536 case Expr::ObjCIvarRefExprClass:
2537 case Expr::ObjCPropertyRefExprClass:
2538 case Expr::ObjCImplicitSetterGetterRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002539 case Expr::ObjCIsaExprClass:
2540 case Expr::ShuffleVectorExprClass:
2541 case Expr::BlockExprClass:
2542 case Expr::BlockDeclRefExprClass:
2543 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002544 case Expr::OpaqueValueExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002545 return ICEDiag(2, E->getLocStart());
2546
2547 case Expr::GNUNullExprClass:
2548 // GCC considers the GNU __null value to be an integral constant expression.
2549 return NoDiag();
2550
2551 case Expr::ParenExprClass:
2552 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2553 case Expr::IntegerLiteralClass:
2554 case Expr::CharacterLiteralClass:
2555 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002556 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002557 case Expr::TypesCompatibleExprClass:
2558 case Expr::UnaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002559 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002560 return NoDiag();
2561 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002562 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002563 const CallExpr *CE = cast<CallExpr>(E);
2564 if (CE->isBuiltinCall(Ctx))
2565 return CheckEvalInICE(E, Ctx);
2566 return ICEDiag(2, E->getLocStart());
2567 }
2568 case Expr::DeclRefExprClass:
2569 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2570 return NoDiag();
2571 if (Ctx.getLangOptions().CPlusPlus &&
2572 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2573 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2574
2575 // Parameter variables are never constants. Without this check,
2576 // getAnyInitializer() can find a default argument, which leads
2577 // to chaos.
2578 if (isa<ParmVarDecl>(D))
2579 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2580
2581 // C++ 7.1.5.1p2
2582 // A variable of non-volatile const-qualified integral or enumeration
2583 // type initialized by an ICE can be used in ICEs.
2584 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2585 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2586 if (Quals.hasVolatile() || !Quals.hasConst())
2587 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2588
2589 // Look for a declaration of this variable that has an initializer.
2590 const VarDecl *ID = 0;
2591 const Expr *Init = Dcl->getAnyInitializer(ID);
2592 if (Init) {
2593 if (ID->isInitKnownICE()) {
2594 // We have already checked whether this subexpression is an
2595 // integral constant expression.
2596 if (ID->isInitICE())
2597 return NoDiag();
2598 else
2599 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2600 }
2601
2602 // It's an ICE whether or not the definition we found is
2603 // out-of-line. See DR 721 and the discussion in Clang PR
2604 // 6206 for details.
2605
2606 if (Dcl->isCheckingICE()) {
2607 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2608 }
2609
2610 Dcl->setCheckingICE();
2611 ICEDiag Result = CheckICE(Init, Ctx);
2612 // Cache the result of the ICE test.
2613 Dcl->setInitKnownICE(Result.Val == 0);
2614 return Result;
2615 }
2616 }
2617 }
2618 return ICEDiag(2, E->getLocStart());
2619 case Expr::UnaryOperatorClass: {
2620 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2621 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002622 case UO_PostInc:
2623 case UO_PostDec:
2624 case UO_PreInc:
2625 case UO_PreDec:
2626 case UO_AddrOf:
2627 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002628 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002629 case UO_Extension:
2630 case UO_LNot:
2631 case UO_Plus:
2632 case UO_Minus:
2633 case UO_Not:
2634 case UO_Real:
2635 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002636 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002637 }
2638
2639 // OffsetOf falls through here.
2640 }
2641 case Expr::OffsetOfExprClass: {
2642 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2643 // Evaluate matches the proposed gcc behavior for cases like
2644 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2645 // compliance: we should warn earlier for offsetof expressions with
2646 // array subscripts that aren't ICEs, and if the array subscripts
2647 // are ICEs, the value of the offsetof must be an integer constant.
2648 return CheckEvalInICE(E, Ctx);
2649 }
2650 case Expr::SizeOfAlignOfExprClass: {
2651 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2652 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2653 return ICEDiag(2, E->getLocStart());
2654 return NoDiag();
2655 }
2656 case Expr::BinaryOperatorClass: {
2657 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2658 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002659 case BO_PtrMemD:
2660 case BO_PtrMemI:
2661 case BO_Assign:
2662 case BO_MulAssign:
2663 case BO_DivAssign:
2664 case BO_RemAssign:
2665 case BO_AddAssign:
2666 case BO_SubAssign:
2667 case BO_ShlAssign:
2668 case BO_ShrAssign:
2669 case BO_AndAssign:
2670 case BO_XorAssign:
2671 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002672 return ICEDiag(2, E->getLocStart());
2673
John McCall2de56d12010-08-25 11:45:40 +00002674 case BO_Mul:
2675 case BO_Div:
2676 case BO_Rem:
2677 case BO_Add:
2678 case BO_Sub:
2679 case BO_Shl:
2680 case BO_Shr:
2681 case BO_LT:
2682 case BO_GT:
2683 case BO_LE:
2684 case BO_GE:
2685 case BO_EQ:
2686 case BO_NE:
2687 case BO_And:
2688 case BO_Xor:
2689 case BO_Or:
2690 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002691 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2692 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002693 if (Exp->getOpcode() == BO_Div ||
2694 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002695 // Evaluate gives an error for undefined Div/Rem, so make sure
2696 // we don't evaluate one.
2697 if (LHSResult.Val != 2 && RHSResult.Val != 2) {
2698 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2699 if (REval == 0)
2700 return ICEDiag(1, E->getLocStart());
2701 if (REval.isSigned() && REval.isAllOnesValue()) {
2702 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2703 if (LEval.isMinSignedValue())
2704 return ICEDiag(1, E->getLocStart());
2705 }
2706 }
2707 }
John McCall2de56d12010-08-25 11:45:40 +00002708 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002709 if (Ctx.getLangOptions().C99) {
2710 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2711 // if it isn't evaluated.
2712 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2713 return ICEDiag(1, E->getLocStart());
2714 } else {
2715 // In both C89 and C++, commas in ICEs are illegal.
2716 return ICEDiag(2, E->getLocStart());
2717 }
2718 }
2719 if (LHSResult.Val >= RHSResult.Val)
2720 return LHSResult;
2721 return RHSResult;
2722 }
John McCall2de56d12010-08-25 11:45:40 +00002723 case BO_LAnd:
2724 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002725 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2726 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2727 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2728 // Rare case where the RHS has a comma "side-effect"; we need
2729 // to actually check the condition to see whether the side
2730 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00002731 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00002732 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2733 return RHSResult;
2734 return NoDiag();
2735 }
2736
2737 if (LHSResult.Val >= RHSResult.Val)
2738 return LHSResult;
2739 return RHSResult;
2740 }
2741 }
2742 }
2743 case Expr::ImplicitCastExprClass:
2744 case Expr::CStyleCastExprClass:
2745 case Expr::CXXFunctionalCastExprClass:
2746 case Expr::CXXStaticCastExprClass:
2747 case Expr::CXXReinterpretCastExprClass:
2748 case Expr::CXXConstCastExprClass: {
2749 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002750 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00002751 return CheckICE(SubExpr, Ctx);
2752 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2753 return NoDiag();
2754 return ICEDiag(2, E->getLocStart());
2755 }
2756 case Expr::ConditionalOperatorClass: {
2757 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
2758 // If the condition (ignoring parens) is a __builtin_constant_p call,
2759 // then only the true side is actually considered in an integer constant
2760 // expression, and it is fully evaluated. This is an important GNU
2761 // extension. See GCC PR38377 for discussion.
2762 if (const CallExpr *CallCE
2763 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
2764 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
2765 Expr::EvalResult EVResult;
2766 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2767 !EVResult.Val.isInt()) {
2768 return ICEDiag(2, E->getLocStart());
2769 }
2770 return NoDiag();
2771 }
2772 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
2773 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
2774 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2775 if (CondResult.Val == 2)
2776 return CondResult;
2777 if (TrueResult.Val == 2)
2778 return TrueResult;
2779 if (FalseResult.Val == 2)
2780 return FalseResult;
2781 if (CondResult.Val == 1)
2782 return CondResult;
2783 if (TrueResult.Val == 0 && FalseResult.Val == 0)
2784 return NoDiag();
2785 // Rare case where the diagnostics depend on which side is evaluated
2786 // Note that if we get here, CondResult is 0, and at least one of
2787 // TrueResult and FalseResult is non-zero.
2788 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
2789 return FalseResult;
2790 }
2791 return TrueResult;
2792 }
2793 case Expr::CXXDefaultArgExprClass:
2794 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
2795 case Expr::ChooseExprClass: {
2796 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
2797 }
2798 }
2799
2800 // Silence a GCC warning
2801 return ICEDiag(2, E->getLocStart());
2802}
2803
2804bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
2805 SourceLocation *Loc, bool isEvaluated) const {
2806 ICEDiag d = CheckICE(this, Ctx);
2807 if (d.Val != 0) {
2808 if (Loc) *Loc = d.Loc;
2809 return false;
2810 }
2811 EvalResult EvalResult;
2812 if (!Evaluate(EvalResult, Ctx))
2813 llvm_unreachable("ICE cannot be evaluated!");
2814 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
2815 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
2816 Result = EvalResult.Val.getInt();
2817 return true;
2818}