blob: c8f470376a77c9ea03e6c61e7c7530b97cf8e7bd [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.
John McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCallf4cf1a12010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
105 Expr *Base;
106 CharUnits Offset;
107
108 Expr *getLValueBase() { return Base; }
109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
178 Decl->hasAttr<WeakImportAttr>())
179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
224 bool DestSigned = DestType->isSignedIntegerType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
227 uint64_t Space[4];
228 bool ignored;
229 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
230 llvm::APFloat::rmTowardZero, &ignored);
231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
232}
233
Mike Stump1eb44332009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump1eb44332009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000245 unsigned DestWidth = Ctx.getIntWidth(DestType);
246 APSInt Result = Value;
247 // Figure out if this is a truncate, extend or noop cast.
248 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerType());
251 return Result;
252}
253
Mike Stump1eb44332009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000256
257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
258 Result.convertFromAPInt(Value, Value.isSigned(),
259 APFloat::rmNearestTiesToEven);
260 return Result;
261}
262
Mike Stumpc4c90452009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000264class HasSideEffect
Mike Stumpc4c90452009-10-27 22:09:17 +0000265 : public StmtVisitor<HasSideEffect, bool> {
266 EvalInfo &Info;
267public:
268
269 HasSideEffect(EvalInfo &info) : Info(info) {}
270
271 // Unhandled nodes conservatively default to having side effects.
272 bool VisitStmt(Stmt *S) {
273 return true;
274 }
275
276 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
277 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000278 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000279 return true;
280 return false;
281 }
282 // We don't want to evaluate BlockExprs multiple times, as they generate
283 // a ton of code.
284 bool VisitBlockExpr(BlockExpr *E) { return true; }
285 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
286 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
287 { return Visit(E->getInitializer()); }
288 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
289 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
290 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
291 bool VisitStringLiteral(StringLiteral *E) { return false; }
292 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
293 bool VisitSizeOfAlignOfExpr(SizeOfAlignOfExpr *E) { return false; }
294 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000295 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000296 bool VisitChooseExpr(ChooseExpr *E)
297 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
298 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
299 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000300 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000301 bool VisitBinaryOperator(BinaryOperator *E)
302 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000303 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
304 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
305 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
306 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
307 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000308 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000309 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000310 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000311 }
312 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000313
314 // Has side effects if any element does.
315 bool VisitInitListExpr(InitListExpr *E) {
316 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
317 if (Visit(E->getInit(i))) return true;
318 return false;
319 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000320
321 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000322};
323
John McCall56ca35d2011-02-17 10:25:35 +0000324class OpaqueValueEvaluation {
325 EvalInfo &info;
326 OpaqueValueExpr *opaqueValue;
327
328public:
329 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
330 Expr *value)
331 : info(info), opaqueValue(opaqueValue) {
332
333 // If evaluation fails, fail immediately.
334 if (!Evaluate(info, value)) {
335 this->opaqueValue = 0;
336 return;
337 }
338 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
339 }
340
341 bool hasError() const { return opaqueValue == 0; }
342
343 ~OpaqueValueEvaluation() {
344 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
345 }
346};
347
Mike Stumpc4c90452009-10-27 22:09:17 +0000348} // end anonymous namespace
349
Eli Friedman4efaa272008-11-12 09:44:48 +0000350//===----------------------------------------------------------------------===//
351// LValue Evaluation
352//===----------------------------------------------------------------------===//
353namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000354class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000355 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000356 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000357 LValue &Result;
358
359 bool Success(Expr *E) {
360 Result.Base = E;
361 Result.Offset = CharUnits::Zero();
362 return true;
363 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000364public:
Mike Stump1eb44332009-09-09 15:08:12 +0000365
John McCallefdb83e2010-05-07 21:00:08 +0000366 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
367 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000368
John McCallefdb83e2010-05-07 21:00:08 +0000369 bool VisitStmt(Stmt *S) {
370 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000371 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000372
John McCallefdb83e2010-05-07 21:00:08 +0000373 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
374 bool VisitDeclRefExpr(DeclRefExpr *E);
375 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
376 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
377 bool VisitMemberExpr(MemberExpr *E);
378 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
379 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
380 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
381 bool VisitUnaryDeref(UnaryOperator *E);
382 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000383 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000384 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000385 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000386
John McCallefdb83e2010-05-07 21:00:08 +0000387 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000388 switch (E->getCastKind()) {
389 default:
John McCallefdb83e2010-05-07 21:00:08 +0000390 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000391
John McCall2de56d12010-08-25 11:45:40 +0000392 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000393 return Visit(E->getSubExpr());
394 }
395 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000396 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000397};
398} // end anonymous namespace
399
John McCallefdb83e2010-05-07 21:00:08 +0000400static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
401 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000402}
403
John McCallefdb83e2010-05-07 21:00:08 +0000404bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000405 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000406 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000407 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
408 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000409 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000410 // Reference parameters can refer to anything even if they have an
411 // "initializer" in the form of a default argument.
412 if (isa<ParmVarDecl>(VD))
413 return false;
Eli Friedmand933a012009-08-29 19:09:59 +0000414 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000415 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000416 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000417 }
418
John McCallefdb83e2010-05-07 21:00:08 +0000419 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000420}
421
John McCallefdb83e2010-05-07 21:00:08 +0000422bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000423 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000424}
425
John McCallefdb83e2010-05-07 21:00:08 +0000426bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000427 QualType Ty;
428 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000429 if (!EvaluatePointer(E->getBase(), Result, Info))
430 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000431 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000432 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000433 if (!Visit(E->getBase()))
434 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000435 Ty = E->getBase()->getType();
436 }
437
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000439 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000440
441 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
442 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000443 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000444
445 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000446 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000447
Eli Friedman4efaa272008-11-12 09:44:48 +0000448 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000449 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000450 for (RecordDecl::field_iterator Field = RD->field_begin(),
451 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000452 Field != FieldEnd; (void)++Field, ++i) {
453 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000454 break;
455 }
456
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000457 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000458 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000459}
460
John McCallefdb83e2010-05-07 21:00:08 +0000461bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000462 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000463 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Anders Carlsson3068d112008-11-16 19:01:22 +0000465 APSInt Index;
466 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000467 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000468
Ken Dyck199c3d62010-01-11 17:06:35 +0000469 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000470 Result.Offset += Index.getSExtValue() * ElementSize;
471 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000472}
Eli Friedman4efaa272008-11-12 09:44:48 +0000473
John McCallefdb83e2010-05-07 21:00:08 +0000474bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
475 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000476}
477
Eli Friedman4efaa272008-11-12 09:44:48 +0000478//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000479// Pointer Evaluation
480//===----------------------------------------------------------------------===//
481
Anders Carlssonc754aa62008-07-08 05:13:58 +0000482namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000483class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000484 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000485 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000486 LValue &Result;
487
488 bool Success(Expr *E) {
489 Result.Base = E;
490 Result.Offset = CharUnits::Zero();
491 return true;
492 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000493public:
Mike Stump1eb44332009-09-09 15:08:12 +0000494
John McCallefdb83e2010-05-07 21:00:08 +0000495 PointerExprEvaluator(EvalInfo &info, LValue &Result)
496 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000497
John McCallefdb83e2010-05-07 21:00:08 +0000498 bool VisitStmt(Stmt *S) {
499 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000500 }
501
John McCallefdb83e2010-05-07 21:00:08 +0000502 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000503
John McCallefdb83e2010-05-07 21:00:08 +0000504 bool VisitBinaryOperator(const BinaryOperator *E);
505 bool VisitCastExpr(CastExpr* E);
506 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000507 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000508 bool VisitUnaryAddrOf(const UnaryOperator *E);
509 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
510 { return Success(E); }
511 bool VisitAddrLabelExpr(AddrLabelExpr *E)
512 { return Success(E); }
513 bool VisitCallExpr(CallExpr *E);
514 bool VisitBlockExpr(BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000515 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000516 return Success(E);
517 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000518 }
John McCallefdb83e2010-05-07 21:00:08 +0000519 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
520 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000521 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
John McCallefdb83e2010-05-07 21:00:08 +0000522 bool VisitConditionalOperator(ConditionalOperator *E);
523 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000524 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000525 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
526 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000527
528 bool VisitOpaqueValueExpr(OpaqueValueExpr *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000529 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000530};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000531} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000532
John McCallefdb83e2010-05-07 21:00:08 +0000533static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000534 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000535 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000536}
537
John McCallefdb83e2010-05-07 21:00:08 +0000538bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000539 if (E->getOpcode() != BO_Add &&
540 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000541 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000542
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000543 const Expr *PExp = E->getLHS();
544 const Expr *IExp = E->getRHS();
545 if (IExp->getType()->isPointerType())
546 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000547
John McCallefdb83e2010-05-07 21:00:08 +0000548 if (!EvaluatePointer(PExp, Result, Info))
549 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000550
John McCallefdb83e2010-05-07 21:00:08 +0000551 llvm::APSInt Offset;
552 if (!EvaluateInteger(IExp, Offset, Info))
553 return false;
554 int64_t AdditionalOffset
555 = Offset.isSigned() ? Offset.getSExtValue()
556 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000557
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000558 // Compute the new offset in the appropriate width.
559
560 QualType PointeeType =
561 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000562 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000563
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000564 // Explicitly handle GNU void* and function pointer arithmetic extensions.
565 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000566 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000567 else
John McCallefdb83e2010-05-07 21:00:08 +0000568 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000569
John McCall2de56d12010-08-25 11:45:40 +0000570 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000571 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000572 else
John McCallefdb83e2010-05-07 21:00:08 +0000573 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000574
John McCallefdb83e2010-05-07 21:00:08 +0000575 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000576}
Eli Friedman4efaa272008-11-12 09:44:48 +0000577
John McCallefdb83e2010-05-07 21:00:08 +0000578bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
579 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000580}
Mike Stump1eb44332009-09-09 15:08:12 +0000581
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000582
John McCallefdb83e2010-05-07 21:00:08 +0000583bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000584 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000585
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000586 switch (E->getCastKind()) {
587 default:
588 break;
589
John McCall2de56d12010-08-25 11:45:40 +0000590 case CK_NoOp:
591 case CK_BitCast:
592 case CK_LValueBitCast:
593 case CK_AnyPointerToObjCPointerCast:
594 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000595 return Visit(SubExpr);
596
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000597 case CK_DerivedToBase:
598 case CK_UncheckedDerivedToBase: {
599 LValue BaseLV;
600 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
601 return false;
602
603 // Now figure out the necessary offset to add to the baseLV to get from
604 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000605 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000606
607 QualType Ty = E->getSubExpr()->getType();
608 const CXXRecordDecl *DerivedDecl =
609 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
610
611 for (CastExpr::path_const_iterator PathI = E->path_begin(),
612 PathE = E->path_end(); PathI != PathE; ++PathI) {
613 const CXXBaseSpecifier *Base = *PathI;
614
615 // FIXME: If the base is virtual, we'd need to determine the type of the
616 // most derived class and we don't support that right now.
617 if (Base->isVirtual())
618 return false;
619
620 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
621 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
622
Ken Dyck7c7f8202011-01-26 02:17:08 +0000623 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000624 DerivedDecl = BaseDecl;
625 }
626
627 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000628 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000629 return true;
630 }
631
John McCall404cd162010-11-13 01:35:44 +0000632 case CK_NullToPointer: {
633 Result.Base = 0;
634 Result.Offset = CharUnits::Zero();
635 return true;
636 }
637
John McCall2de56d12010-08-25 11:45:40 +0000638 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000639 APValue Value;
640 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000641 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000642
John McCallefdb83e2010-05-07 21:00:08 +0000643 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000644 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000645 Result.Base = 0;
646 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
647 return true;
648 } else {
649 // Cast is of an lvalue, no need to change value.
650 Result.Base = Value.getLValueBase();
651 Result.Offset = Value.getLValueOffset();
652 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000653 }
654 }
John McCall2de56d12010-08-25 11:45:40 +0000655 case CK_ArrayToPointerDecay:
656 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000657 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000658 }
659
John McCallefdb83e2010-05-07 21:00:08 +0000660 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000661}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000662
John McCallefdb83e2010-05-07 21:00:08 +0000663bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000664 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000665 Builtin::BI__builtin___CFStringMakeConstantString ||
666 E->isBuiltinCall(Info.Ctx) ==
667 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000668 return Success(E);
669 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000670}
671
John McCall56ca35d2011-02-17 10:25:35 +0000672bool PointerExprEvaluator::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
673 const APValue *value = Info.getOpaqueValue(e);
674 if (!value)
675 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
676 Result.setFrom(*value);
677 return true;
678}
679
680bool PointerExprEvaluator::
681VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
682 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
683 if (opaque.hasError()) return false;
684
685 bool cond;
686 if (!HandleConversionToBool(e->getCond(), cond, Info))
687 return false;
688
689 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
690}
691
John McCallefdb83e2010-05-07 21:00:08 +0000692bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000693 bool BoolResult;
694 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000695 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000696
697 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000698 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000699}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000700
701//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000702// Vector Evaluation
703//===----------------------------------------------------------------------===//
704
705namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000706 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000707 : public StmtVisitor<VectorExprEvaluator, APValue> {
708 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000709 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000710 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Nate Begeman59b5da62009-01-18 03:20:47 +0000712 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000713
Nate Begeman59b5da62009-01-18 03:20:47 +0000714 APValue VisitStmt(Stmt *S) {
715 return APValue();
716 }
Mike Stump1eb44332009-09-09 15:08:12 +0000717
Eli Friedman91110ee2009-02-23 04:23:56 +0000718 APValue VisitParenExpr(ParenExpr *E)
719 { return Visit(E->getSubExpr()); }
720 APValue VisitUnaryExtension(const UnaryOperator *E)
721 { return Visit(E->getSubExpr()); }
722 APValue VisitUnaryPlus(const UnaryOperator *E)
723 { return Visit(E->getSubExpr()); }
724 APValue VisitUnaryReal(const UnaryOperator *E)
725 { return Visit(E->getSubExpr()); }
726 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
727 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000728 APValue VisitCastExpr(const CastExpr* E);
729 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
730 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000731 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000732 APValue VisitChooseExpr(const ChooseExpr *E)
733 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000734 APValue VisitUnaryImag(const UnaryOperator *E);
735 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000736 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000737 // shufflevector, ExtVectorElementExpr
738 // (Note that these require implementing conversions
739 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000740 };
741} // end anonymous namespace
742
743static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
744 if (!E->getType()->isVectorType())
745 return false;
746 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
747 return !Result.isUninit();
748}
749
750APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000751 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000752 QualType EltTy = VTy->getElementType();
753 unsigned NElts = VTy->getNumElements();
754 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000755
Nate Begeman59b5da62009-01-18 03:20:47 +0000756 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000757 QualType SETy = SE->getType();
758 APValue Result = APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000759
Nate Begemane8c9e922009-06-26 18:22:18 +0000760 // Check for vector->vector bitcast and scalar->vector splat.
761 if (SETy->isVectorType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +0000762 return this->Visit(const_cast<Expr*>(SE));
Nate Begemane8c9e922009-06-26 18:22:18 +0000763 } else if (SETy->isIntegerType()) {
764 APSInt IntResult;
Daniel Dunbard906dc72009-07-01 20:37:45 +0000765 if (!EvaluateInteger(SE, IntResult, Info))
766 return APValue();
767 Result = APValue(IntResult);
Nate Begemane8c9e922009-06-26 18:22:18 +0000768 } else if (SETy->isRealFloatingType()) {
769 APFloat F(0.0);
Daniel Dunbard906dc72009-07-01 20:37:45 +0000770 if (!EvaluateFloat(SE, F, Info))
771 return APValue();
772 Result = APValue(F);
773 } else
Nate Begemanc0b8b192009-07-01 07:50:47 +0000774 return APValue();
Nate Begeman59b5da62009-01-18 03:20:47 +0000775
Nate Begemanc0b8b192009-07-01 07:50:47 +0000776 // For casts of a scalar to ExtVector, convert the scalar to the element type
777 // and splat it to all elements.
778 if (E->getType()->isExtVectorType()) {
779 if (EltTy->isIntegerType() && Result.isInt())
780 Result = APValue(HandleIntToIntCast(EltTy, SETy, Result.getInt(),
781 Info.Ctx));
782 else if (EltTy->isIntegerType())
783 Result = APValue(HandleFloatToIntCast(EltTy, SETy, Result.getFloat(),
784 Info.Ctx));
785 else if (EltTy->isRealFloatingType() && Result.isInt())
786 Result = APValue(HandleIntToFloatCast(EltTy, SETy, Result.getInt(),
787 Info.Ctx));
788 else if (EltTy->isRealFloatingType())
789 Result = APValue(HandleFloatToFloatCast(EltTy, SETy, Result.getFloat(),
790 Info.Ctx));
791 else
792 return APValue();
793
794 // Splat and create vector APValue.
795 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
796 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000797 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000798
799 // For casts of a scalar to regular gcc-style vector type, bitcast the scalar
800 // to the vector. To construct the APValue vector initializer, bitcast the
801 // initializing value to an APInt, and shift out the bits pertaining to each
802 // element.
803 APSInt Init;
804 Init = Result.isInt() ? Result.getInt() : Result.getFloat().bitcastToAPInt();
Mike Stump1eb44332009-09-09 15:08:12 +0000805
Nate Begemanc0b8b192009-07-01 07:50:47 +0000806 llvm::SmallVector<APValue, 4> Elts;
807 for (unsigned i = 0; i != NElts; ++i) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000808 APSInt Tmp = Init.extOrTrunc(EltWidth);
Mike Stump1eb44332009-09-09 15:08:12 +0000809
Nate Begemanc0b8b192009-07-01 07:50:47 +0000810 if (EltTy->isIntegerType())
811 Elts.push_back(APValue(Tmp));
812 else if (EltTy->isRealFloatingType())
813 Elts.push_back(APValue(APFloat(Tmp)));
814 else
815 return APValue();
816
817 Init >>= EltWidth;
818 }
819 return APValue(&Elts[0], Elts.size());
Nate Begeman59b5da62009-01-18 03:20:47 +0000820}
821
Mike Stump1eb44332009-09-09 15:08:12 +0000822APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000823VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
824 return this->Visit(const_cast<Expr*>(E->getInitializer()));
825}
826
Mike Stump1eb44332009-09-09 15:08:12 +0000827APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000828VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000829 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000830 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000831 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000832
Nate Begeman59b5da62009-01-18 03:20:47 +0000833 QualType EltTy = VT->getElementType();
834 llvm::SmallVector<APValue, 4> Elements;
835
John McCalla7d6c222010-06-11 17:54:15 +0000836 // If a vector is initialized with a single element, that value
837 // becomes every element of the vector, not just the first.
838 // This is the behavior described in the IBM AltiVec documentation.
839 if (NumInits == 1) {
840 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000841 if (EltTy->isIntegerType()) {
842 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000843 if (!EvaluateInteger(E->getInit(0), sInt, Info))
844 return APValue();
845 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000846 } else {
847 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000848 if (!EvaluateFloat(E->getInit(0), f, Info))
849 return APValue();
850 InitValue = APValue(f);
851 }
852 for (unsigned i = 0; i < NumElements; i++) {
853 Elements.push_back(InitValue);
854 }
855 } else {
856 for (unsigned i = 0; i < NumElements; i++) {
857 if (EltTy->isIntegerType()) {
858 llvm::APSInt sInt(32);
859 if (i < NumInits) {
860 if (!EvaluateInteger(E->getInit(i), sInt, Info))
861 return APValue();
862 } else {
863 sInt = Info.Ctx.MakeIntValue(0, EltTy);
864 }
865 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000866 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000867 llvm::APFloat f(0.0);
868 if (i < NumInits) {
869 if (!EvaluateFloat(E->getInit(i), f, Info))
870 return APValue();
871 } else {
872 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
873 }
874 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000875 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000876 }
877 }
878 return APValue(&Elements[0], Elements.size());
879}
880
Mike Stump1eb44332009-09-09 15:08:12 +0000881APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000882VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000883 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000884 QualType EltTy = VT->getElementType();
885 APValue ZeroElement;
886 if (EltTy->isIntegerType())
887 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
888 else
889 ZeroElement =
890 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
891
892 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
893 return APValue(&Elements[0], Elements.size());
894}
895
896APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
897 bool BoolResult;
898 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
899 return APValue();
900
901 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
902
903 APValue Result;
904 if (EvaluateVector(EvalExpr, Result, Info))
905 return Result;
906 return APValue();
907}
908
Eli Friedman91110ee2009-02-23 04:23:56 +0000909APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
910 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
911 Info.EvalResult.HasSideEffects = true;
912 return GetZeroVector(E->getType());
913}
914
Nate Begeman59b5da62009-01-18 03:20:47 +0000915//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000916// Integer Evaluation
917//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000918
919namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000920class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000921 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000922 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000923 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000924public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000925 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000926 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000927
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000928 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000929 assert(E->getType()->isIntegralOrEnumerationType() &&
930 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000931 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000932 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000933 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000934 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000935 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000936 return true;
937 }
938
Daniel Dunbar131eb432009-02-19 09:06:44 +0000939 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000940 assert(E->getType()->isIntegralOrEnumerationType() &&
941 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000942 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000943 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000944 Result = APValue(APSInt(I));
945 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000946 return true;
947 }
948
949 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000950 assert(E->getType()->isIntegralOrEnumerationType() &&
951 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000952 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000953 return true;
954 }
955
Anders Carlsson82206e22008-11-30 18:14:57 +0000956 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000957 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000958 if (Info.EvalResult.Diag == 0) {
959 Info.EvalResult.DiagLoc = L;
960 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000961 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000962 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000963 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000964 }
Mike Stump1eb44332009-09-09 15:08:12 +0000965
Anders Carlssonc754aa62008-07-08 05:13:58 +0000966 //===--------------------------------------------------------------------===//
967 // Visitor Methods
968 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000969
Chris Lattner32fea9d2008-11-12 07:43:42 +0000970 bool VisitStmt(Stmt *) {
971 assert(0 && "This should be called on integers, stmts are not integers");
972 return false;
973 }
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Chris Lattner32fea9d2008-11-12 07:43:42 +0000975 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000976 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000977 }
Mike Stump1eb44332009-09-09 15:08:12 +0000978
Chris Lattnerb542afe2008-07-11 19:10:17 +0000979 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000980
Chris Lattner4c4867e2008-07-12 00:38:25 +0000981 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000982 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000983 }
984 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000985 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000986 }
Eli Friedman04309752009-11-24 05:28:59 +0000987
John McCall56ca35d2011-02-17 10:25:35 +0000988 bool VisitOpaqueValueExpr(OpaqueValueExpr *e) {
989 const APValue *value = Info.getOpaqueValue(e);
990 if (!value) {
991 if (e->getSourceExpr()) return Visit(e->getSourceExpr());
992 return Error(e->getExprLoc(), diag::note_invalid_subexpr_in_ice, e);
993 }
994 return Success(value->getInt(), e);
995 }
996
Eli Friedman04309752009-11-24 05:28:59 +0000997 bool CheckReferencedDecl(const Expr *E, const Decl *D);
998 bool VisitDeclRefExpr(const DeclRefExpr *E) {
999 return CheckReferencedDecl(E, E->getDecl());
1000 }
1001 bool VisitMemberExpr(const MemberExpr *E) {
1002 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1003 // Conservatively assume a MemberExpr will have side-effects
1004 Info.EvalResult.HasSideEffects = true;
1005 return true;
1006 }
1007 return false;
1008 }
1009
Eli Friedmanc4a26382010-02-13 00:10:10 +00001010 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001011 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001012 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001013 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001014 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001015 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001016
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001017 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +00001018 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
1019
Anders Carlsson3068d112008-11-16 19:01:22 +00001020 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001021 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001022 }
Mike Stump1eb44332009-09-09 15:08:12 +00001023
Anders Carlsson3f704562008-12-21 22:39:40 +00001024 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001025 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001026 }
Mike Stump1eb44332009-09-09 15:08:12 +00001027
Douglas Gregored8abf12010-07-08 06:14:04 +00001028 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001029 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001030 }
1031
Eli Friedman664a1042009-02-27 04:45:43 +00001032 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1033 return Success(0, E);
1034 }
1035
Sebastian Redl64b45f72009-01-05 20:52:13 +00001036 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001037 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001038 }
1039
Francois Pichet6ad6f282010-12-07 00:08:36 +00001040 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1041 return Success(E->getValue(), E);
1042 }
1043
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001044 bool VisitChooseExpr(const ChooseExpr *E) {
1045 return Visit(E->getChosenSubExpr(Info.Ctx));
1046 }
1047
Eli Friedman722c7172009-02-28 03:59:05 +00001048 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001049 bool VisitUnaryImag(const UnaryOperator *E);
1050
Sebastian Redl295995c2010-09-10 20:55:47 +00001051 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001052 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1053
Chris Lattnerfcee0012008-07-11 21:24:13 +00001054private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001055 CharUnits GetAlignOfExpr(const Expr *E);
1056 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001057 static QualType GetObjectType(const Expr *E);
1058 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001059 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001060};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001061} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001062
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001063static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001064 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001065 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1066}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001067
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001068static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001069 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001070
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001071 APValue Val;
1072 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1073 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001074 Result = Val.getInt();
1075 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001076}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001077
Eli Friedman04309752009-11-24 05:28:59 +00001078bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001079 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001080 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1081 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001082
1083 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001084 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001085 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1086 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001087
1088 if (isa<ParmVarDecl>(D))
1089 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1090
Eli Friedman04309752009-11-24 05:28:59 +00001091 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001092 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001093 if (APValue *V = VD->getEvaluatedValue()) {
1094 if (V->isInt())
1095 return Success(V->getInt(), E);
1096 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1097 }
1098
1099 if (VD->isEvaluatingValue())
1100 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1101
1102 VD->setEvaluatingValue();
1103
Eli Friedmana7dedf72010-09-06 00:10:32 +00001104 Expr::EvalResult EResult;
1105 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1106 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001107 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001108 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001109 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001110 return true;
1111 }
1112
Eli Friedmanc0131182009-12-03 20:31:57 +00001113 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001114 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001115 }
1116 }
1117
Chris Lattner4c4867e2008-07-12 00:38:25 +00001118 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001119 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001120}
1121
Chris Lattnera4d55d82008-10-06 06:40:35 +00001122/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1123/// as GCC.
1124static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1125 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001126 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001127 enum gcc_type_class {
1128 no_type_class = -1,
1129 void_type_class, integer_type_class, char_type_class,
1130 enumeral_type_class, boolean_type_class,
1131 pointer_type_class, reference_type_class, offset_type_class,
1132 real_type_class, complex_type_class,
1133 function_type_class, method_type_class,
1134 record_type_class, union_type_class,
1135 array_type_class, string_type_class,
1136 lang_type_class
1137 };
Mike Stump1eb44332009-09-09 15:08:12 +00001138
1139 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001140 // ideal, however it is what gcc does.
1141 if (E->getNumArgs() == 0)
1142 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001143
Chris Lattnera4d55d82008-10-06 06:40:35 +00001144 QualType ArgTy = E->getArg(0)->getType();
1145 if (ArgTy->isVoidType())
1146 return void_type_class;
1147 else if (ArgTy->isEnumeralType())
1148 return enumeral_type_class;
1149 else if (ArgTy->isBooleanType())
1150 return boolean_type_class;
1151 else if (ArgTy->isCharType())
1152 return string_type_class; // gcc doesn't appear to use char_type_class
1153 else if (ArgTy->isIntegerType())
1154 return integer_type_class;
1155 else if (ArgTy->isPointerType())
1156 return pointer_type_class;
1157 else if (ArgTy->isReferenceType())
1158 return reference_type_class;
1159 else if (ArgTy->isRealType())
1160 return real_type_class;
1161 else if (ArgTy->isComplexType())
1162 return complex_type_class;
1163 else if (ArgTy->isFunctionType())
1164 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001165 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001166 return record_type_class;
1167 else if (ArgTy->isUnionType())
1168 return union_type_class;
1169 else if (ArgTy->isArrayType())
1170 return array_type_class;
1171 else if (ArgTy->isUnionType())
1172 return union_type_class;
1173 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1174 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1175 return -1;
1176}
1177
John McCall42c8f872010-05-10 23:27:23 +00001178/// Retrieves the "underlying object type" of the given expression,
1179/// as used by __builtin_object_size.
1180QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1181 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1182 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1183 return VD->getType();
1184 } else if (isa<CompoundLiteralExpr>(E)) {
1185 return E->getType();
1186 }
1187
1188 return QualType();
1189}
1190
1191bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1192 // TODO: Perhaps we should let LLVM lower this?
1193 LValue Base;
1194 if (!EvaluatePointer(E->getArg(0), Base, Info))
1195 return false;
1196
1197 // If we can prove the base is null, lower to zero now.
1198 const Expr *LVBase = Base.getLValueBase();
1199 if (!LVBase) return Success(0, E);
1200
1201 QualType T = GetObjectType(LVBase);
1202 if (T.isNull() ||
1203 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001204 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001205 T->isVariablyModifiedType() ||
1206 T->isDependentType())
1207 return false;
1208
1209 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1210 CharUnits Offset = Base.getLValueOffset();
1211
1212 if (!Offset.isNegative() && Offset <= Size)
1213 Size -= Offset;
1214 else
1215 Size = CharUnits::Zero();
1216 return Success(Size.getQuantity(), E);
1217}
1218
Eli Friedmanc4a26382010-02-13 00:10:10 +00001219bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001220 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001221 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001222 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001223
1224 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001225 if (TryEvaluateBuiltinObjectSize(E))
1226 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001227
Eric Christopherb2aaf512010-01-19 22:58:35 +00001228 // If evaluating the argument has side-effects we can't determine
1229 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001230 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001231 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001232 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001233 return Success(0, E);
1234 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001235
Mike Stump64eda9e2009-10-26 18:35:08 +00001236 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1237 }
1238
Chris Lattner019f4e82008-10-06 05:28:25 +00001239 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001240 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001241
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001242 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001243 // __builtin_constant_p always has one operand: it returns true if that
1244 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001245 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001246
1247 case Builtin::BI__builtin_eh_return_data_regno: {
1248 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1249 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1250 return Success(Operand, E);
1251 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001252
1253 case Builtin::BI__builtin_expect:
1254 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001255
1256 case Builtin::BIstrlen:
1257 case Builtin::BI__builtin_strlen:
1258 // As an extension, we support strlen() and __builtin_strlen() as constant
1259 // expressions when the argument is a string literal.
1260 if (StringLiteral *S
1261 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1262 // The string literal may have embedded null characters. Find the first
1263 // one and truncate there.
1264 llvm::StringRef Str = S->getString();
1265 llvm::StringRef::size_type Pos = Str.find(0);
1266 if (Pos != llvm::StringRef::npos)
1267 Str = Str.substr(0, Pos);
1268
1269 return Success(Str.size(), E);
1270 }
1271
1272 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001273 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001274}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001275
Chris Lattnerb542afe2008-07-11 19:10:17 +00001276bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001277 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001278 if (!Visit(E->getRHS()))
1279 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001280
Eli Friedman33ef1452009-02-26 10:19:36 +00001281 // If we can't evaluate the LHS, it might have side effects;
1282 // conservatively mark it.
1283 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1284 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001285
Anders Carlsson027f62e2008-12-01 02:07:06 +00001286 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001287 }
1288
1289 if (E->isLogicalOp()) {
1290 // These need to be handled specially because the operands aren't
1291 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001292 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001293
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001294 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001295 // We were able to evaluate the LHS, see if we can get away with not
1296 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001297 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001298 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001299
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001300 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001301 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001302 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001303 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001304 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001305 }
1306 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001307 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001308 // We can't evaluate the LHS; however, sometimes the result
1309 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001310 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1311 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001312 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001313 // must have had side effects.
1314 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001315
1316 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001317 }
1318 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001319 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001320
Eli Friedmana6afa762008-11-13 06:09:17 +00001321 return false;
1322 }
1323
Anders Carlsson286f85e2008-11-16 07:17:21 +00001324 QualType LHSTy = E->getLHS()->getType();
1325 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001326
1327 if (LHSTy->isAnyComplexType()) {
1328 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001329 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001330
1331 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1332 return false;
1333
1334 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1335 return false;
1336
1337 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001338 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001339 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001340 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001341 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1342
John McCall2de56d12010-08-25 11:45:40 +00001343 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001344 return Success((CR_r == APFloat::cmpEqual &&
1345 CR_i == APFloat::cmpEqual), E);
1346 else {
John McCall2de56d12010-08-25 11:45:40 +00001347 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001348 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001349 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001350 CR_r == APFloat::cmpLessThan ||
1351 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001352 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001353 CR_i == APFloat::cmpLessThan ||
1354 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001355 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001356 } else {
John McCall2de56d12010-08-25 11:45:40 +00001357 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001358 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1359 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1360 else {
John McCall2de56d12010-08-25 11:45:40 +00001361 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001362 "Invalid compex comparison.");
1363 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1364 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1365 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001366 }
1367 }
Mike Stump1eb44332009-09-09 15:08:12 +00001368
Anders Carlsson286f85e2008-11-16 07:17:21 +00001369 if (LHSTy->isRealFloatingType() &&
1370 RHSTy->isRealFloatingType()) {
1371 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001372
Anders Carlsson286f85e2008-11-16 07:17:21 +00001373 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1374 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001375
Anders Carlsson286f85e2008-11-16 07:17:21 +00001376 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1377 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Anders Carlsson286f85e2008-11-16 07:17:21 +00001379 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001380
Anders Carlsson286f85e2008-11-16 07:17:21 +00001381 switch (E->getOpcode()) {
1382 default:
1383 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001384 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001385 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001386 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001387 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001388 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001389 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001390 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001391 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001392 E);
John McCall2de56d12010-08-25 11:45:40 +00001393 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001394 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001395 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001396 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001397 || CR == APFloat::cmpLessThan
1398 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001399 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001400 }
Mike Stump1eb44332009-09-09 15:08:12 +00001401
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001402 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001403 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001404 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001405 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1406 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001407
John McCallefdb83e2010-05-07 21:00:08 +00001408 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001409 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1410 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001411
Eli Friedman5bc86102009-06-14 02:17:33 +00001412 // Reject any bases from the normal codepath; we special-case comparisons
1413 // to null.
1414 if (LHSValue.getLValueBase()) {
1415 if (!E->isEqualityOp())
1416 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001417 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001418 return false;
1419 bool bres;
1420 if (!EvalPointerValueAsBool(LHSValue, bres))
1421 return false;
John McCall2de56d12010-08-25 11:45:40 +00001422 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001423 } else if (RHSValue.getLValueBase()) {
1424 if (!E->isEqualityOp())
1425 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001426 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001427 return false;
1428 bool bres;
1429 if (!EvalPointerValueAsBool(RHSValue, bres))
1430 return false;
John McCall2de56d12010-08-25 11:45:40 +00001431 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001432 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001433
John McCall2de56d12010-08-25 11:45:40 +00001434 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001435 QualType Type = E->getLHS()->getType();
1436 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001437
Ken Dycka7305832010-01-15 12:37:54 +00001438 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001439 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001440 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001441
Ken Dycka7305832010-01-15 12:37:54 +00001442 CharUnits Diff = LHSValue.getLValueOffset() -
1443 RHSValue.getLValueOffset();
1444 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001445 }
1446 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001447 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001448 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001449 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001450 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1451 }
1452 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001453 }
1454 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001455 if (!LHSTy->isIntegralOrEnumerationType() ||
1456 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001457 // We can't continue from here for non-integral types, and they
1458 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001459 return false;
1460 }
1461
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001462 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001463 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001464 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001465
Eli Friedman42edd0d2009-03-24 01:14:50 +00001466 APValue RHSVal;
1467 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001468 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001469
1470 // Handle cases like (unsigned long)&a + 4.
1471 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001472 CharUnits Offset = Result.getLValueOffset();
1473 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1474 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001475 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001476 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001477 else
Ken Dycka7305832010-01-15 12:37:54 +00001478 Offset -= AdditionalOffset;
1479 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001480 return true;
1481 }
1482
1483 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001484 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001485 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001486 CharUnits Offset = RHSVal.getLValueOffset();
1487 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1488 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001489 return true;
1490 }
1491
1492 // All the following cases expect both operands to be an integer
1493 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001494 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001495
Eli Friedman42edd0d2009-03-24 01:14:50 +00001496 APSInt& RHS = RHSVal.getInt();
1497
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001498 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001499 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001500 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001501 case BO_Mul: return Success(Result.getInt() * RHS, E);
1502 case BO_Add: return Success(Result.getInt() + RHS, E);
1503 case BO_Sub: return Success(Result.getInt() - RHS, E);
1504 case BO_And: return Success(Result.getInt() & RHS, E);
1505 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1506 case BO_Or: return Success(Result.getInt() | RHS, E);
1507 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001508 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001509 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001510 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001511 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001512 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001513 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001514 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001515 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001516 // During constant-folding, a negative shift is an opposite shift.
1517 if (RHS.isSigned() && RHS.isNegative()) {
1518 RHS = -RHS;
1519 goto shift_right;
1520 }
1521
1522 shift_left:
1523 unsigned SA
1524 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001525 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001526 }
John McCall2de56d12010-08-25 11:45:40 +00001527 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001528 // During constant-folding, a negative shift is an opposite shift.
1529 if (RHS.isSigned() && RHS.isNegative()) {
1530 RHS = -RHS;
1531 goto shift_left;
1532 }
1533
1534 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001535 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001536 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1537 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001538 }
Mike Stump1eb44332009-09-09 15:08:12 +00001539
John McCall2de56d12010-08-25 11:45:40 +00001540 case BO_LT: return Success(Result.getInt() < RHS, E);
1541 case BO_GT: return Success(Result.getInt() > RHS, E);
1542 case BO_LE: return Success(Result.getInt() <= RHS, E);
1543 case BO_GE: return Success(Result.getInt() >= RHS, E);
1544 case BO_EQ: return Success(Result.getInt() == RHS, E);
1545 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001546 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001547}
1548
John McCall56ca35d2011-02-17 10:25:35 +00001549bool IntExprEvaluator::
1550VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
1551 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
1552 if (opaque.hasError()) return false;
1553
1554 bool cond;
1555 if (!HandleConversionToBool(e->getCond(), cond, Info))
1556 return false;
1557
1558 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
1559}
1560
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001561bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001562 bool Cond;
1563 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001564 return false;
1565
Nuno Lopesa25bd552008-11-16 22:06:39 +00001566 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001567}
1568
Ken Dyck8b752f12010-01-27 17:10:57 +00001569CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001570 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1571 // the result is the size of the referenced type."
1572 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1573 // result shall be the alignment of the referenced type."
1574 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1575 T = Ref->getPointeeType();
1576
Eli Friedman2be58612009-05-30 21:09:44 +00001577 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001578 return Info.Ctx.toCharUnitsFromBits(
1579 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001580}
1581
Ken Dyck8b752f12010-01-27 17:10:57 +00001582CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001583 E = E->IgnoreParens();
1584
1585 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001586 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001587 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001588 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1589 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001590
Chris Lattneraf707ab2009-01-24 21:53:27 +00001591 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001592 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1593 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001594
Chris Lattnere9feb472009-01-24 21:09:06 +00001595 return GetAlignOfType(E->getType());
1596}
1597
1598
Sebastian Redl05189992008-11-11 17:56:53 +00001599/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1600/// expression's type.
1601bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001602 // Handle alignof separately.
1603 if (!E->isSizeOf()) {
1604 if (E->isArgumentType())
Ken Dyck8b752f12010-01-27 17:10:57 +00001605 return Success(GetAlignOfType(E->getArgumentType()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001606 else
Ken Dyck8b752f12010-01-27 17:10:57 +00001607 return Success(GetAlignOfExpr(E->getArgumentExpr()).getQuantity(), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001608 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001609
Sebastian Redl05189992008-11-11 17:56:53 +00001610 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001611 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1612 // the result is the size of the referenced type."
1613 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1614 // result shall be the alignment of the referenced type."
1615 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1616 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001617
Daniel Dunbar131eb432009-02-19 09:06:44 +00001618 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1619 // extension.
1620 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1621 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001622
Chris Lattnerfcee0012008-07-11 21:24:13 +00001623 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001624 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001625 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001626
Chris Lattnere9feb472009-01-24 21:09:06 +00001627 // Get information about the size.
Ken Dyck199c3d62010-01-11 17:06:35 +00001628 return Success(Info.Ctx.getTypeSizeInChars(SrcTy).getQuantity(), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001629}
1630
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001631bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1632 CharUnits Result;
1633 unsigned n = E->getNumComponents();
1634 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1635 if (n == 0)
1636 return false;
1637 QualType CurrentType = E->getTypeSourceInfo()->getType();
1638 for (unsigned i = 0; i != n; ++i) {
1639 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1640 switch (ON.getKind()) {
1641 case OffsetOfExpr::OffsetOfNode::Array: {
1642 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1643 APSInt IdxResult;
1644 if (!EvaluateInteger(Idx, IdxResult, Info))
1645 return false;
1646 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1647 if (!AT)
1648 return false;
1649 CurrentType = AT->getElementType();
1650 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1651 Result += IdxResult.getSExtValue() * ElementSize;
1652 break;
1653 }
1654
1655 case OffsetOfExpr::OffsetOfNode::Field: {
1656 FieldDecl *MemberDecl = ON.getField();
1657 const RecordType *RT = CurrentType->getAs<RecordType>();
1658 if (!RT)
1659 return false;
1660 RecordDecl *RD = RT->getDecl();
1661 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001662 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001663 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001664 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001665 CurrentType = MemberDecl->getType().getNonReferenceType();
1666 break;
1667 }
1668
1669 case OffsetOfExpr::OffsetOfNode::Identifier:
1670 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001671 return false;
1672
1673 case OffsetOfExpr::OffsetOfNode::Base: {
1674 CXXBaseSpecifier *BaseSpec = ON.getBase();
1675 if (BaseSpec->isVirtual())
1676 return false;
1677
1678 // Find the layout of the class whose base we are looking into.
1679 const RecordType *RT = CurrentType->getAs<RecordType>();
1680 if (!RT)
1681 return false;
1682 RecordDecl *RD = RT->getDecl();
1683 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1684
1685 // Find the base class itself.
1686 CurrentType = BaseSpec->getType();
1687 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1688 if (!BaseRT)
1689 return false;
1690
1691 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001692 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001693 break;
1694 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001695 }
1696 }
1697 return Success(Result.getQuantity(), E);
1698}
1699
Chris Lattnerb542afe2008-07-11 19:10:17 +00001700bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001701 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001702 // LNot's operand isn't necessarily an integer, so we handle it specially.
1703 bool bres;
1704 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1705 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001706 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001707 }
1708
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001709 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001710 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001711 return false;
1712
Chris Lattner87eae5e2008-07-11 22:52:41 +00001713 // Get the operand value into 'Result'.
1714 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001715 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001716
Chris Lattner75a48812008-07-11 22:15:16 +00001717 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001718 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001719 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1720 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001721 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001722 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001723 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1724 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001725 return true;
John McCall2de56d12010-08-25 11:45:40 +00001726 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001727 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001728 return true;
John McCall2de56d12010-08-25 11:45:40 +00001729 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001730 if (!Result.isInt()) return false;
1731 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001732 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001733 if (!Result.isInt()) return false;
1734 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001735 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001736}
Mike Stump1eb44332009-09-09 15:08:12 +00001737
Chris Lattner732b2232008-07-12 01:15:53 +00001738/// HandleCast - This is used to evaluate implicit or explicit casts where the
1739/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001740bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001741 Expr *SubExpr = E->getSubExpr();
1742 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001743 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001744
Eli Friedman4efaa272008-11-12 09:44:48 +00001745 if (DestType->isBooleanType()) {
1746 bool BoolResult;
1747 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1748 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001749 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001750 }
1751
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001752 // Handle simple integer->integer casts.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001753 if (SrcType->isIntegralOrEnumerationType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001754 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001755 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001756
Eli Friedmanbe265702009-02-20 01:15:07 +00001757 if (!Result.isInt()) {
1758 // Only allow casts of lvalues if they are lossless.
1759 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1760 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001761
Daniel Dunbardd211642009-02-19 22:24:01 +00001762 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001763 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001764 }
Mike Stump1eb44332009-09-09 15:08:12 +00001765
Chris Lattner732b2232008-07-12 01:15:53 +00001766 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001767 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001768 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001769 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001770 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001771
Daniel Dunbardd211642009-02-19 22:24:01 +00001772 if (LV.getLValueBase()) {
1773 // Only allow based lvalue casts if they are lossless.
1774 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1775 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001776
John McCallefdb83e2010-05-07 21:00:08 +00001777 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001778 return true;
1779 }
1780
Ken Dycka7305832010-01-15 12:37:54 +00001781 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1782 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001783 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001784 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001785
Eli Friedmanbe265702009-02-20 01:15:07 +00001786 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1787 // This handles double-conversion cases, where there's both
1788 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001789 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001790 if (!EvaluateLValue(SubExpr, LV, Info))
1791 return false;
1792
1793 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1794 return false;
1795
John McCallefdb83e2010-05-07 21:00:08 +00001796 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001797 return true;
1798 }
1799
Eli Friedman1725f682009-04-22 19:23:09 +00001800 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001801 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001802 if (!EvaluateComplex(SubExpr, C, Info))
1803 return false;
1804 if (C.isComplexFloat())
1805 return Success(HandleFloatToIntCast(DestType, SrcType,
1806 C.getComplexFloatReal(), Info.Ctx),
1807 E);
1808 else
1809 return Success(HandleIntToIntCast(DestType, SrcType,
1810 C.getComplexIntReal(), Info.Ctx), E);
1811 }
Eli Friedman2217c872009-02-22 11:46:18 +00001812 // FIXME: Handle vectors
1813
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001814 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001815 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001816
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001817 APFloat F(0.0);
1818 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001819 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001821 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001822}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001823
Eli Friedman722c7172009-02-28 03:59:05 +00001824bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1825 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001826 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001827 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1828 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1829 return Success(LV.getComplexIntReal(), E);
1830 }
1831
1832 return Visit(E->getSubExpr());
1833}
1834
Eli Friedman664a1042009-02-27 04:45:43 +00001835bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001836 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001837 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001838 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1839 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1840 return Success(LV.getComplexIntImag(), E);
1841 }
1842
Eli Friedman664a1042009-02-27 04:45:43 +00001843 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1844 Info.EvalResult.HasSideEffects = true;
1845 return Success(0, E);
1846}
1847
Douglas Gregoree8aff02011-01-04 17:33:58 +00001848bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1849 return Success(E->getPackLength(), E);
1850}
1851
Sebastian Redl295995c2010-09-10 20:55:47 +00001852bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1853 return Success(E->getValue(), E);
1854}
1855
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001856//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001857// Float Evaluation
1858//===----------------------------------------------------------------------===//
1859
1860namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001861class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001862 : public StmtVisitor<FloatExprEvaluator, bool> {
1863 EvalInfo &Info;
1864 APFloat &Result;
1865public:
1866 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1867 : Info(info), Result(result) {}
1868
1869 bool VisitStmt(Stmt *S) {
1870 return false;
1871 }
1872
1873 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001874 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001875
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001876 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001877 bool VisitBinaryOperator(const BinaryOperator *E);
1878 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001879 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001880 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001881 bool VisitConditionalOperator(ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001882 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001883
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001884 bool VisitChooseExpr(const ChooseExpr *E)
1885 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1886 bool VisitUnaryExtension(const UnaryOperator *E)
1887 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001888 bool VisitUnaryReal(const UnaryOperator *E);
1889 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001890
John McCall189d6ef2010-10-09 01:34:31 +00001891 bool VisitDeclRefExpr(const DeclRefExpr *E);
1892
John McCall56ca35d2011-02-17 10:25:35 +00001893 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
1894 const APValue *value = Info.getOpaqueValue(e);
1895 if (!value)
1896 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
1897 Result = value->getFloat();
1898 return true;
1899 }
1900
John McCallabd3a852010-05-07 22:08:54 +00001901 // FIXME: Missing: array subscript of vector, member of vector,
1902 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001903};
1904} // end anonymous namespace
1905
1906static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001907 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001908 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1909}
1910
Jay Foad4ba2a172011-01-12 09:06:06 +00001911static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001912 QualType ResultTy,
1913 const Expr *Arg,
1914 bool SNaN,
1915 llvm::APFloat &Result) {
1916 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1917 if (!S) return false;
1918
1919 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1920
1921 llvm::APInt fill;
1922
1923 // Treat empty strings as if they were zero.
1924 if (S->getString().empty())
1925 fill = llvm::APInt(32, 0);
1926 else if (S->getString().getAsInteger(0, fill))
1927 return false;
1928
1929 if (SNaN)
1930 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1931 else
1932 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1933 return true;
1934}
1935
Chris Lattner019f4e82008-10-06 05:28:25 +00001936bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001937 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001938 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001939 case Builtin::BI__builtin_huge_val:
1940 case Builtin::BI__builtin_huge_valf:
1941 case Builtin::BI__builtin_huge_vall:
1942 case Builtin::BI__builtin_inf:
1943 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001944 case Builtin::BI__builtin_infl: {
1945 const llvm::fltSemantics &Sem =
1946 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001947 Result = llvm::APFloat::getInf(Sem);
1948 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001949 }
Mike Stump1eb44332009-09-09 15:08:12 +00001950
John McCalldb7b72a2010-02-28 13:00:19 +00001951 case Builtin::BI__builtin_nans:
1952 case Builtin::BI__builtin_nansf:
1953 case Builtin::BI__builtin_nansl:
1954 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1955 true, Result);
1956
Chris Lattner9e621712008-10-06 06:31:58 +00001957 case Builtin::BI__builtin_nan:
1958 case Builtin::BI__builtin_nanf:
1959 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001960 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001961 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001962 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1963 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001964
1965 case Builtin::BI__builtin_fabs:
1966 case Builtin::BI__builtin_fabsf:
1967 case Builtin::BI__builtin_fabsl:
1968 if (!EvaluateFloat(E->getArg(0), Result, Info))
1969 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001970
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001971 if (Result.isNegative())
1972 Result.changeSign();
1973 return true;
1974
Mike Stump1eb44332009-09-09 15:08:12 +00001975 case Builtin::BI__builtin_copysign:
1976 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001977 case Builtin::BI__builtin_copysignl: {
1978 APFloat RHS(0.);
1979 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1980 !EvaluateFloat(E->getArg(1), RHS, Info))
1981 return false;
1982 Result.copySign(RHS);
1983 return true;
1984 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001985 }
1986}
1987
John McCall189d6ef2010-10-09 01:34:31 +00001988bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1989 const Decl *D = E->getDecl();
1990 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
1991 const VarDecl *VD = cast<VarDecl>(D);
1992
1993 // Require the qualifiers to be const and not volatile.
1994 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
1995 if (!T.isConstQualified() || T.isVolatileQualified())
1996 return false;
1997
1998 const Expr *Init = VD->getAnyInitializer();
1999 if (!Init) return false;
2000
2001 if (APValue *V = VD->getEvaluatedValue()) {
2002 if (V->isFloat()) {
2003 Result = V->getFloat();
2004 return true;
2005 }
2006 return false;
2007 }
2008
2009 if (VD->isEvaluatingValue())
2010 return false;
2011
2012 VD->setEvaluatingValue();
2013
2014 Expr::EvalResult InitResult;
2015 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2016 InitResult.Val.isFloat()) {
2017 // Cache the evaluated value in the variable declaration.
2018 Result = InitResult.Val.getFloat();
2019 VD->setEvaluatedValue(InitResult.Val);
2020 return true;
2021 }
2022
2023 VD->setEvaluatedValue(APValue());
2024 return false;
2025}
2026
John McCallabd3a852010-05-07 22:08:54 +00002027bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002028 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2029 ComplexValue CV;
2030 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2031 return false;
2032 Result = CV.FloatReal;
2033 return true;
2034 }
2035
2036 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002037}
2038
2039bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002040 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2041 ComplexValue CV;
2042 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2043 return false;
2044 Result = CV.FloatImag;
2045 return true;
2046 }
2047
2048 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2049 Info.EvalResult.HasSideEffects = true;
2050 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2051 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002052 return true;
2053}
2054
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002055bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002056 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002057 return false;
2058
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002059 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2060 return false;
2061
2062 switch (E->getOpcode()) {
2063 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002064 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002065 return true;
John McCall2de56d12010-08-25 11:45:40 +00002066 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002067 Result.changeSign();
2068 return true;
2069 }
2070}
Chris Lattner019f4e82008-10-06 05:28:25 +00002071
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002072bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002073 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002074 if (!EvaluateFloat(E->getRHS(), Result, Info))
2075 return false;
2076
2077 // If we can't evaluate the LHS, it might have side effects;
2078 // conservatively mark it.
2079 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2080 Info.EvalResult.HasSideEffects = true;
2081
2082 return true;
2083 }
2084
Anders Carlsson96e93662010-10-31 01:21:47 +00002085 // We can't evaluate pointer-to-member operations.
2086 if (E->isPtrMemOp())
2087 return false;
2088
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002089 // FIXME: Diagnostics? I really don't understand how the warnings
2090 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002091 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002092 if (!EvaluateFloat(E->getLHS(), Result, Info))
2093 return false;
2094 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2095 return false;
2096
2097 switch (E->getOpcode()) {
2098 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002099 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002100 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2101 return true;
John McCall2de56d12010-08-25 11:45:40 +00002102 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002103 Result.add(RHS, APFloat::rmNearestTiesToEven);
2104 return true;
John McCall2de56d12010-08-25 11:45:40 +00002105 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002106 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2107 return true;
John McCall2de56d12010-08-25 11:45:40 +00002108 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002109 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2110 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002111 }
2112}
2113
2114bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2115 Result = E->getValue();
2116 return true;
2117}
2118
Eli Friedman4efaa272008-11-12 09:44:48 +00002119bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2120 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002121
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002122 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002123 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002124 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002125 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002126 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002127 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002128 return true;
2129 }
2130 if (SubExpr->getType()->isRealFloatingType()) {
2131 if (!Visit(SubExpr))
2132 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002133 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2134 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002135 return true;
2136 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002137
2138 if (E->getCastKind() == CK_FloatingComplexToReal) {
2139 ComplexValue V;
2140 if (!EvaluateComplex(SubExpr, V, Info))
2141 return false;
2142 Result = V.getComplexFloatReal();
2143 return true;
2144 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002145
2146 return false;
2147}
2148
Douglas Gregored8abf12010-07-08 06:14:04 +00002149bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002150 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2151 return true;
2152}
2153
John McCall56ca35d2011-02-17 10:25:35 +00002154bool FloatExprEvaluator::
2155VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
2156 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2157 if (opaque.hasError()) return false;
2158
2159 bool cond;
2160 if (!HandleConversionToBool(e->getCond(), cond, Info))
2161 return false;
2162
2163 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2164}
2165
Eli Friedman67f85fc2009-12-04 02:12:53 +00002166bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2167 bool Cond;
2168 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2169 return false;
2170
2171 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2172}
2173
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002174//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002175// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002176//===----------------------------------------------------------------------===//
2177
2178namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002179class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002180 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002181 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002182 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002184public:
John McCallf4cf1a12010-05-07 17:22:02 +00002185 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2186 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002187
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002188 //===--------------------------------------------------------------------===//
2189 // Visitor Methods
2190 //===--------------------------------------------------------------------===//
2191
John McCallf4cf1a12010-05-07 17:22:02 +00002192 bool VisitStmt(Stmt *S) {
2193 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002194 }
Mike Stump1eb44332009-09-09 15:08:12 +00002195
John McCallf4cf1a12010-05-07 17:22:02 +00002196 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002197
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002198 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002199
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002200 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002201
John McCallf4cf1a12010-05-07 17:22:02 +00002202 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002203 bool VisitUnaryOperator(const UnaryOperator *E);
2204 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00002205 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002206 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002207 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002208 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002209 { return Visit(E->getSubExpr()); }
John McCall56ca35d2011-02-17 10:25:35 +00002210 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
2211 const APValue *value = Info.getOpaqueValue(e);
2212 if (!value)
2213 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
2214 Result.setFrom(*value);
2215 return true;
2216 }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002217 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002218};
2219} // end anonymous namespace
2220
John McCallf4cf1a12010-05-07 17:22:02 +00002221static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2222 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002223 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002224 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002225}
2226
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002227bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2228 Expr* SubExpr = E->getSubExpr();
2229
2230 if (SubExpr->getType()->isRealFloatingType()) {
2231 Result.makeComplexFloat();
2232 APFloat &Imag = Result.FloatImag;
2233 if (!EvaluateFloat(SubExpr, Imag, Info))
2234 return false;
2235
2236 Result.FloatReal = APFloat(Imag.getSemantics());
2237 return true;
2238 } else {
2239 assert(SubExpr->getType()->isIntegerType() &&
2240 "Unexpected imaginary literal.");
2241
2242 Result.makeComplexInt();
2243 APSInt &Imag = Result.IntImag;
2244 if (!EvaluateInteger(SubExpr, Imag, Info))
2245 return false;
2246
2247 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2248 return true;
2249 }
2250}
2251
2252bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002253
John McCall8786da72010-12-14 17:51:41 +00002254 switch (E->getCastKind()) {
2255 case CK_BitCast:
2256 case CK_LValueBitCast:
2257 case CK_BaseToDerived:
2258 case CK_DerivedToBase:
2259 case CK_UncheckedDerivedToBase:
2260 case CK_Dynamic:
2261 case CK_ToUnion:
2262 case CK_ArrayToPointerDecay:
2263 case CK_FunctionToPointerDecay:
2264 case CK_NullToPointer:
2265 case CK_NullToMemberPointer:
2266 case CK_BaseToDerivedMemberPointer:
2267 case CK_DerivedToBaseMemberPointer:
2268 case CK_MemberPointerToBoolean:
2269 case CK_ConstructorConversion:
2270 case CK_IntegralToPointer:
2271 case CK_PointerToIntegral:
2272 case CK_PointerToBoolean:
2273 case CK_ToVoid:
2274 case CK_VectorSplat:
2275 case CK_IntegralCast:
2276 case CK_IntegralToBoolean:
2277 case CK_IntegralToFloating:
2278 case CK_FloatingToIntegral:
2279 case CK_FloatingToBoolean:
2280 case CK_FloatingCast:
2281 case CK_AnyPointerToObjCPointerCast:
2282 case CK_AnyPointerToBlockPointerCast:
2283 case CK_ObjCObjectLValueCast:
2284 case CK_FloatingComplexToReal:
2285 case CK_FloatingComplexToBoolean:
2286 case CK_IntegralComplexToReal:
2287 case CK_IntegralComplexToBoolean:
2288 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002289
John McCall8786da72010-12-14 17:51:41 +00002290 case CK_LValueToRValue:
2291 case CK_NoOp:
2292 return Visit(E->getSubExpr());
2293
2294 case CK_Dependent:
2295 case CK_GetObjCProperty:
2296 case CK_UserDefinedConversion:
2297 return false;
2298
2299 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002300 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002301 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002302 return false;
2303
John McCall8786da72010-12-14 17:51:41 +00002304 Result.makeComplexFloat();
2305 Result.FloatImag = APFloat(Real.getSemantics());
2306 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002307 }
2308
John McCall8786da72010-12-14 17:51:41 +00002309 case CK_FloatingComplexCast: {
2310 if (!Visit(E->getSubExpr()))
2311 return false;
2312
2313 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2314 QualType From
2315 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2316
2317 Result.FloatReal
2318 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2319 Result.FloatImag
2320 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2321 return true;
2322 }
2323
2324 case CK_FloatingComplexToIntegralComplex: {
2325 if (!Visit(E->getSubExpr()))
2326 return false;
2327
2328 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2329 QualType From
2330 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2331 Result.makeComplexInt();
2332 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2333 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2334 return true;
2335 }
2336
2337 case CK_IntegralRealToComplex: {
2338 APSInt &Real = Result.IntReal;
2339 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2340 return false;
2341
2342 Result.makeComplexInt();
2343 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2344 return true;
2345 }
2346
2347 case CK_IntegralComplexCast: {
2348 if (!Visit(E->getSubExpr()))
2349 return false;
2350
2351 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2352 QualType From
2353 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2354
2355 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2356 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2357 return true;
2358 }
2359
2360 case CK_IntegralComplexToFloatingComplex: {
2361 if (!Visit(E->getSubExpr()))
2362 return false;
2363
2364 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2365 QualType From
2366 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2367 Result.makeComplexFloat();
2368 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2369 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2370 return true;
2371 }
2372 }
2373
2374 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002375 return false;
2376}
2377
John McCallf4cf1a12010-05-07 17:22:02 +00002378bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002379 if (E->getOpcode() == BO_Comma) {
2380 if (!Visit(E->getRHS()))
2381 return false;
2382
2383 // If we can't evaluate the LHS, it might have side effects;
2384 // conservatively mark it.
2385 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2386 Info.EvalResult.HasSideEffects = true;
2387
2388 return true;
2389 }
John McCallf4cf1a12010-05-07 17:22:02 +00002390 if (!Visit(E->getLHS()))
2391 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002392
John McCallf4cf1a12010-05-07 17:22:02 +00002393 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002394 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002395 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002396
Daniel Dunbar3f279872009-01-29 01:32:56 +00002397 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2398 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002399 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002400 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002401 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002402 if (Result.isComplexFloat()) {
2403 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2404 APFloat::rmNearestTiesToEven);
2405 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2406 APFloat::rmNearestTiesToEven);
2407 } else {
2408 Result.getComplexIntReal() += RHS.getComplexIntReal();
2409 Result.getComplexIntImag() += RHS.getComplexIntImag();
2410 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002411 break;
John McCall2de56d12010-08-25 11:45:40 +00002412 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002413 if (Result.isComplexFloat()) {
2414 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2415 APFloat::rmNearestTiesToEven);
2416 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2417 APFloat::rmNearestTiesToEven);
2418 } else {
2419 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2420 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2421 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002422 break;
John McCall2de56d12010-08-25 11:45:40 +00002423 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002424 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002425 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002426 APFloat &LHS_r = LHS.getComplexFloatReal();
2427 APFloat &LHS_i = LHS.getComplexFloatImag();
2428 APFloat &RHS_r = RHS.getComplexFloatReal();
2429 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002430
Daniel Dunbar3f279872009-01-29 01:32:56 +00002431 APFloat Tmp = LHS_r;
2432 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2433 Result.getComplexFloatReal() = Tmp;
2434 Tmp = LHS_i;
2435 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2436 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2437
2438 Tmp = LHS_r;
2439 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2440 Result.getComplexFloatImag() = Tmp;
2441 Tmp = LHS_i;
2442 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2443 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2444 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002445 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002446 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002447 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2448 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002449 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002450 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2451 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2452 }
2453 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002454 case BO_Div:
2455 if (Result.isComplexFloat()) {
2456 ComplexValue LHS = Result;
2457 APFloat &LHS_r = LHS.getComplexFloatReal();
2458 APFloat &LHS_i = LHS.getComplexFloatImag();
2459 APFloat &RHS_r = RHS.getComplexFloatReal();
2460 APFloat &RHS_i = RHS.getComplexFloatImag();
2461 APFloat &Res_r = Result.getComplexFloatReal();
2462 APFloat &Res_i = Result.getComplexFloatImag();
2463
2464 APFloat Den = RHS_r;
2465 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2466 APFloat Tmp = RHS_i;
2467 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2468 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2469
2470 Res_r = LHS_r;
2471 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2472 Tmp = LHS_i;
2473 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2474 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2475 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2476
2477 Res_i = LHS_i;
2478 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2479 Tmp = LHS_r;
2480 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2481 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2482 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2483 } else {
2484 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2485 // FIXME: what about diagnostics?
2486 return false;
2487 }
2488 ComplexValue LHS = Result;
2489 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2490 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2491 Result.getComplexIntReal() =
2492 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2493 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2494 Result.getComplexIntImag() =
2495 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2496 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2497 }
2498 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002499 }
2500
John McCallf4cf1a12010-05-07 17:22:02 +00002501 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002502}
2503
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002504bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2505 // Get the operand value into 'Result'.
2506 if (!Visit(E->getSubExpr()))
2507 return false;
2508
2509 switch (E->getOpcode()) {
2510 default:
2511 // FIXME: what about diagnostics?
2512 return false;
2513 case UO_Extension:
2514 return true;
2515 case UO_Plus:
2516 // The result is always just the subexpr.
2517 return true;
2518 case UO_Minus:
2519 if (Result.isComplexFloat()) {
2520 Result.getComplexFloatReal().changeSign();
2521 Result.getComplexFloatImag().changeSign();
2522 }
2523 else {
2524 Result.getComplexIntReal() = -Result.getComplexIntReal();
2525 Result.getComplexIntImag() = -Result.getComplexIntImag();
2526 }
2527 return true;
2528 case UO_Not:
2529 if (Result.isComplexFloat())
2530 Result.getComplexFloatImag().changeSign();
2531 else
2532 Result.getComplexIntImag() = -Result.getComplexIntImag();
2533 return true;
2534 }
2535}
2536
John McCall56ca35d2011-02-17 10:25:35 +00002537bool ComplexExprEvaluator::
2538VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
2539 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2540 if (opaque.hasError()) return false;
2541
2542 bool cond;
2543 if (!HandleConversionToBool(e->getCond(), cond, Info))
2544 return false;
2545
2546 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2547}
2548
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002549bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2550 bool Cond;
2551 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2552 return false;
2553
2554 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2555}
2556
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002557//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002558// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002559//===----------------------------------------------------------------------===//
2560
John McCall56ca35d2011-02-17 10:25:35 +00002561static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002562 if (E->getType()->isVectorType()) {
2563 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002564 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002565 } else if (E->getType()->isIntegerType()) {
2566 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002567 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002568 if (Info.EvalResult.Val.isLValue() &&
2569 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002570 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002571 } else if (E->getType()->hasPointerRepresentation()) {
2572 LValue LV;
2573 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002574 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002575 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002576 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002577 LV.moveInto(Info.EvalResult.Val);
2578 } else if (E->getType()->isRealFloatingType()) {
2579 llvm::APFloat F(0.0);
2580 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002581 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002582
John McCallefdb83e2010-05-07 21:00:08 +00002583 Info.EvalResult.Val = APValue(F);
2584 } else if (E->getType()->isAnyComplexType()) {
2585 ComplexValue C;
2586 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002587 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002588 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002589 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002590 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002591
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002592 return true;
2593}
2594
John McCall56ca35d2011-02-17 10:25:35 +00002595/// Evaluate - Return true if this is a constant which we can fold using
2596/// any crazy technique (that has nothing to do with language standards) that
2597/// we want to. If this function returns true, it returns the folded constant
2598/// in Result.
2599bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2600 EvalInfo Info(Ctx, Result);
2601 return ::Evaluate(Info, this);
2602}
2603
Jay Foad4ba2a172011-01-12 09:06:06 +00002604bool Expr::EvaluateAsBooleanCondition(bool &Result,
2605 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002606 EvalResult Scratch;
2607 EvalInfo Info(Ctx, Scratch);
2608
2609 return HandleConversionToBool(this, Result, Info);
2610}
2611
Jay Foad4ba2a172011-01-12 09:06:06 +00002612bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002613 EvalInfo Info(Ctx, Result);
2614
John McCallefdb83e2010-05-07 21:00:08 +00002615 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002616 if (EvaluateLValue(this, LV, Info) &&
2617 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002618 IsGlobalLValue(LV.Base)) {
2619 LV.moveInto(Result.Val);
2620 return true;
2621 }
2622 return false;
2623}
2624
Jay Foad4ba2a172011-01-12 09:06:06 +00002625bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2626 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002627 EvalInfo Info(Ctx, Result);
2628
2629 LValue LV;
2630 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002631 LV.moveInto(Result.Val);
2632 return true;
2633 }
2634 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002635}
2636
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002637/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002638/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002639bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002640 EvalResult Result;
2641 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002642}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002643
Jay Foad4ba2a172011-01-12 09:06:06 +00002644bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002645 Expr::EvalResult Result;
2646 EvalInfo Info(Ctx, Result);
2647 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2648}
2649
Jay Foad4ba2a172011-01-12 09:06:06 +00002650APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002651 EvalResult EvalResult;
2652 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002653 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002654 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002655 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002656
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002657 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002658}
John McCalld905f5a2010-05-07 05:32:02 +00002659
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002660 bool Expr::EvalResult::isGlobalLValue() const {
2661 assert(Val.isLValue());
2662 return IsGlobalLValue(Val.getLValueBase());
2663 }
2664
2665
John McCalld905f5a2010-05-07 05:32:02 +00002666/// isIntegerConstantExpr - this recursive routine will test if an expression is
2667/// an integer constant expression.
2668
2669/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2670/// comma, etc
2671///
2672/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2673/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2674/// cast+dereference.
2675
2676// CheckICE - This function does the fundamental ICE checking: the returned
2677// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2678// Note that to reduce code duplication, this helper does no evaluation
2679// itself; the caller checks whether the expression is evaluatable, and
2680// in the rare cases where CheckICE actually cares about the evaluated
2681// value, it calls into Evalute.
2682//
2683// Meanings of Val:
2684// 0: This expression is an ICE if it can be evaluated by Evaluate.
2685// 1: This expression is not an ICE, but if it isn't evaluated, it's
2686// a legal subexpression for an ICE. This return value is used to handle
2687// the comma operator in C99 mode.
2688// 2: This expression is not an ICE, and is not a legal subexpression for one.
2689
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002690namespace {
2691
John McCalld905f5a2010-05-07 05:32:02 +00002692struct ICEDiag {
2693 unsigned Val;
2694 SourceLocation Loc;
2695
2696 public:
2697 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2698 ICEDiag() : Val(0) {}
2699};
2700
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002701}
2702
2703static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002704
2705static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2706 Expr::EvalResult EVResult;
2707 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2708 !EVResult.Val.isInt()) {
2709 return ICEDiag(2, E->getLocStart());
2710 }
2711 return NoDiag();
2712}
2713
2714static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2715 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002716 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002717 return ICEDiag(2, E->getLocStart());
2718 }
2719
2720 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002721#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002722#define STMT(Node, Base) case Expr::Node##Class:
2723#define EXPR(Node, Base)
2724#include "clang/AST/StmtNodes.inc"
2725 case Expr::PredefinedExprClass:
2726 case Expr::FloatingLiteralClass:
2727 case Expr::ImaginaryLiteralClass:
2728 case Expr::StringLiteralClass:
2729 case Expr::ArraySubscriptExprClass:
2730 case Expr::MemberExprClass:
2731 case Expr::CompoundAssignOperatorClass:
2732 case Expr::CompoundLiteralExprClass:
2733 case Expr::ExtVectorElementExprClass:
2734 case Expr::InitListExprClass:
2735 case Expr::DesignatedInitExprClass:
2736 case Expr::ImplicitValueInitExprClass:
2737 case Expr::ParenListExprClass:
2738 case Expr::VAArgExprClass:
2739 case Expr::AddrLabelExprClass:
2740 case Expr::StmtExprClass:
2741 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002742 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002743 case Expr::CXXDynamicCastExprClass:
2744 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002745 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002746 case Expr::CXXNullPtrLiteralExprClass:
2747 case Expr::CXXThisExprClass:
2748 case Expr::CXXThrowExprClass:
2749 case Expr::CXXNewExprClass:
2750 case Expr::CXXDeleteExprClass:
2751 case Expr::CXXPseudoDestructorExprClass:
2752 case Expr::UnresolvedLookupExprClass:
2753 case Expr::DependentScopeDeclRefExprClass:
2754 case Expr::CXXConstructExprClass:
2755 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002756 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002757 case Expr::CXXTemporaryObjectExprClass:
2758 case Expr::CXXUnresolvedConstructExprClass:
2759 case Expr::CXXDependentScopeMemberExprClass:
2760 case Expr::UnresolvedMemberExprClass:
2761 case Expr::ObjCStringLiteralClass:
2762 case Expr::ObjCEncodeExprClass:
2763 case Expr::ObjCMessageExprClass:
2764 case Expr::ObjCSelectorExprClass:
2765 case Expr::ObjCProtocolExprClass:
2766 case Expr::ObjCIvarRefExprClass:
2767 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002768 case Expr::ObjCIsaExprClass:
2769 case Expr::ShuffleVectorExprClass:
2770 case Expr::BlockExprClass:
2771 case Expr::BlockDeclRefExprClass:
2772 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002773 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002774 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002775 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002776 return ICEDiag(2, E->getLocStart());
2777
Douglas Gregoree8aff02011-01-04 17:33:58 +00002778 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002779 case Expr::GNUNullExprClass:
2780 // GCC considers the GNU __null value to be an integral constant expression.
2781 return NoDiag();
2782
2783 case Expr::ParenExprClass:
2784 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2785 case Expr::IntegerLiteralClass:
2786 case Expr::CharacterLiteralClass:
2787 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002788 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002789 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002790 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002791 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002792 return NoDiag();
2793 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002794 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002795 const CallExpr *CE = cast<CallExpr>(E);
2796 if (CE->isBuiltinCall(Ctx))
2797 return CheckEvalInICE(E, Ctx);
2798 return ICEDiag(2, E->getLocStart());
2799 }
2800 case Expr::DeclRefExprClass:
2801 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2802 return NoDiag();
2803 if (Ctx.getLangOptions().CPlusPlus &&
2804 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2805 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2806
2807 // Parameter variables are never constants. Without this check,
2808 // getAnyInitializer() can find a default argument, which leads
2809 // to chaos.
2810 if (isa<ParmVarDecl>(D))
2811 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2812
2813 // C++ 7.1.5.1p2
2814 // A variable of non-volatile const-qualified integral or enumeration
2815 // type initialized by an ICE can be used in ICEs.
2816 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2817 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2818 if (Quals.hasVolatile() || !Quals.hasConst())
2819 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2820
2821 // Look for a declaration of this variable that has an initializer.
2822 const VarDecl *ID = 0;
2823 const Expr *Init = Dcl->getAnyInitializer(ID);
2824 if (Init) {
2825 if (ID->isInitKnownICE()) {
2826 // We have already checked whether this subexpression is an
2827 // integral constant expression.
2828 if (ID->isInitICE())
2829 return NoDiag();
2830 else
2831 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2832 }
2833
2834 // It's an ICE whether or not the definition we found is
2835 // out-of-line. See DR 721 and the discussion in Clang PR
2836 // 6206 for details.
2837
2838 if (Dcl->isCheckingICE()) {
2839 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2840 }
2841
2842 Dcl->setCheckingICE();
2843 ICEDiag Result = CheckICE(Init, Ctx);
2844 // Cache the result of the ICE test.
2845 Dcl->setInitKnownICE(Result.Val == 0);
2846 return Result;
2847 }
2848 }
2849 }
2850 return ICEDiag(2, E->getLocStart());
2851 case Expr::UnaryOperatorClass: {
2852 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2853 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002854 case UO_PostInc:
2855 case UO_PostDec:
2856 case UO_PreInc:
2857 case UO_PreDec:
2858 case UO_AddrOf:
2859 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002860 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002861 case UO_Extension:
2862 case UO_LNot:
2863 case UO_Plus:
2864 case UO_Minus:
2865 case UO_Not:
2866 case UO_Real:
2867 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002868 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002869 }
2870
2871 // OffsetOf falls through here.
2872 }
2873 case Expr::OffsetOfExprClass: {
2874 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2875 // Evaluate matches the proposed gcc behavior for cases like
2876 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2877 // compliance: we should warn earlier for offsetof expressions with
2878 // array subscripts that aren't ICEs, and if the array subscripts
2879 // are ICEs, the value of the offsetof must be an integer constant.
2880 return CheckEvalInICE(E, Ctx);
2881 }
2882 case Expr::SizeOfAlignOfExprClass: {
2883 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2884 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2885 return ICEDiag(2, E->getLocStart());
2886 return NoDiag();
2887 }
2888 case Expr::BinaryOperatorClass: {
2889 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2890 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002891 case BO_PtrMemD:
2892 case BO_PtrMemI:
2893 case BO_Assign:
2894 case BO_MulAssign:
2895 case BO_DivAssign:
2896 case BO_RemAssign:
2897 case BO_AddAssign:
2898 case BO_SubAssign:
2899 case BO_ShlAssign:
2900 case BO_ShrAssign:
2901 case BO_AndAssign:
2902 case BO_XorAssign:
2903 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002904 return ICEDiag(2, E->getLocStart());
2905
John McCall2de56d12010-08-25 11:45:40 +00002906 case BO_Mul:
2907 case BO_Div:
2908 case BO_Rem:
2909 case BO_Add:
2910 case BO_Sub:
2911 case BO_Shl:
2912 case BO_Shr:
2913 case BO_LT:
2914 case BO_GT:
2915 case BO_LE:
2916 case BO_GE:
2917 case BO_EQ:
2918 case BO_NE:
2919 case BO_And:
2920 case BO_Xor:
2921 case BO_Or:
2922 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002923 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2924 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002925 if (Exp->getOpcode() == BO_Div ||
2926 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002927 // Evaluate gives an error for undefined Div/Rem, so make sure
2928 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00002929 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00002930 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2931 if (REval == 0)
2932 return ICEDiag(1, E->getLocStart());
2933 if (REval.isSigned() && REval.isAllOnesValue()) {
2934 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2935 if (LEval.isMinSignedValue())
2936 return ICEDiag(1, E->getLocStart());
2937 }
2938 }
2939 }
John McCall2de56d12010-08-25 11:45:40 +00002940 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002941 if (Ctx.getLangOptions().C99) {
2942 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2943 // if it isn't evaluated.
2944 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2945 return ICEDiag(1, E->getLocStart());
2946 } else {
2947 // In both C89 and C++, commas in ICEs are illegal.
2948 return ICEDiag(2, E->getLocStart());
2949 }
2950 }
2951 if (LHSResult.Val >= RHSResult.Val)
2952 return LHSResult;
2953 return RHSResult;
2954 }
John McCall2de56d12010-08-25 11:45:40 +00002955 case BO_LAnd:
2956 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002957 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2958 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2959 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2960 // Rare case where the RHS has a comma "side-effect"; we need
2961 // to actually check the condition to see whether the side
2962 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00002963 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00002964 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2965 return RHSResult;
2966 return NoDiag();
2967 }
2968
2969 if (LHSResult.Val >= RHSResult.Val)
2970 return LHSResult;
2971 return RHSResult;
2972 }
2973 }
2974 }
2975 case Expr::ImplicitCastExprClass:
2976 case Expr::CStyleCastExprClass:
2977 case Expr::CXXFunctionalCastExprClass:
2978 case Expr::CXXStaticCastExprClass:
2979 case Expr::CXXReinterpretCastExprClass:
2980 case Expr::CXXConstCastExprClass: {
2981 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002982 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00002983 return CheckICE(SubExpr, Ctx);
2984 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2985 return NoDiag();
2986 return ICEDiag(2, E->getLocStart());
2987 }
John McCall56ca35d2011-02-17 10:25:35 +00002988 case Expr::BinaryConditionalOperatorClass: {
2989 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
2990 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
2991 if (CommonResult.Val == 2) return CommonResult;
2992 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2993 if (FalseResult.Val == 2) return FalseResult;
2994 if (CommonResult.Val == 1) return CommonResult;
2995 if (FalseResult.Val == 1 &&
2996 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
2997 return FalseResult;
2998 }
John McCalld905f5a2010-05-07 05:32:02 +00002999 case Expr::ConditionalOperatorClass: {
3000 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3001 // If the condition (ignoring parens) is a __builtin_constant_p call,
3002 // then only the true side is actually considered in an integer constant
3003 // expression, and it is fully evaluated. This is an important GNU
3004 // extension. See GCC PR38377 for discussion.
3005 if (const CallExpr *CallCE
3006 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3007 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3008 Expr::EvalResult EVResult;
3009 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3010 !EVResult.Val.isInt()) {
3011 return ICEDiag(2, E->getLocStart());
3012 }
3013 return NoDiag();
3014 }
3015 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
3016 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3017 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3018 if (CondResult.Val == 2)
3019 return CondResult;
3020 if (TrueResult.Val == 2)
3021 return TrueResult;
3022 if (FalseResult.Val == 2)
3023 return FalseResult;
3024 if (CondResult.Val == 1)
3025 return CondResult;
3026 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3027 return NoDiag();
3028 // Rare case where the diagnostics depend on which side is evaluated
3029 // Note that if we get here, CondResult is 0, and at least one of
3030 // TrueResult and FalseResult is non-zero.
3031 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3032 return FalseResult;
3033 }
3034 return TrueResult;
3035 }
3036 case Expr::CXXDefaultArgExprClass:
3037 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3038 case Expr::ChooseExprClass: {
3039 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3040 }
3041 }
3042
3043 // Silence a GCC warning
3044 return ICEDiag(2, E->getLocStart());
3045}
3046
3047bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3048 SourceLocation *Loc, bool isEvaluated) const {
3049 ICEDiag d = CheckICE(this, Ctx);
3050 if (d.Val != 0) {
3051 if (Loc) *Loc = d.Loc;
3052 return false;
3053 }
3054 EvalResult EvalResult;
3055 if (!Evaluate(EvalResult, Ctx))
3056 llvm_unreachable("ICE cannot be evaluated!");
3057 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3058 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3059 Result = EvalResult.Val.getInt();
3060 return true;
3061}