blob: f421671f7feae40773548c7fb817b681b57ddf2f [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
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000956 bool Success(CharUnits Size, const Expr *E) {
957 return Success(Size.getQuantity(), E);
958 }
959
960
Anders Carlsson82206e22008-11-30 18:14:57 +0000961 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000962 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000963 if (Info.EvalResult.Diag == 0) {
964 Info.EvalResult.DiagLoc = L;
965 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000966 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000967 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000968 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000969 }
Mike Stump1eb44332009-09-09 15:08:12 +0000970
Anders Carlssonc754aa62008-07-08 05:13:58 +0000971 //===--------------------------------------------------------------------===//
972 // Visitor Methods
973 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000974
Chris Lattner32fea9d2008-11-12 07:43:42 +0000975 bool VisitStmt(Stmt *) {
976 assert(0 && "This should be called on integers, stmts are not integers");
977 return false;
978 }
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chris Lattner32fea9d2008-11-12 07:43:42 +0000980 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000981 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000982 }
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Chris Lattnerb542afe2008-07-11 19:10:17 +0000984 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlssonc754aa62008-07-08 05:13:58 +0000985
Chris Lattner4c4867e2008-07-12 00:38:25 +0000986 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000987 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000988 }
989 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +0000990 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +0000991 }
Eli Friedman04309752009-11-24 05:28:59 +0000992
John McCall56ca35d2011-02-17 10:25:35 +0000993 bool VisitOpaqueValueExpr(OpaqueValueExpr *e) {
994 const APValue *value = Info.getOpaqueValue(e);
995 if (!value) {
996 if (e->getSourceExpr()) return Visit(e->getSourceExpr());
997 return Error(e->getExprLoc(), diag::note_invalid_subexpr_in_ice, e);
998 }
999 return Success(value->getInt(), e);
1000 }
1001
Eli Friedman04309752009-11-24 05:28:59 +00001002 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1003 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1004 return CheckReferencedDecl(E, E->getDecl());
1005 }
1006 bool VisitMemberExpr(const MemberExpr *E) {
1007 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1008 // Conservatively assume a MemberExpr will have side-effects
1009 Info.EvalResult.HasSideEffects = true;
1010 return true;
1011 }
1012 return false;
1013 }
1014
Eli Friedmanc4a26382010-02-13 00:10:10 +00001015 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001016 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001017 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001018 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001019 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001020 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001021
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001022 bool VisitCastExpr(CastExpr* E);
Sebastian Redl05189992008-11-11 17:56:53 +00001023 bool VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
1024
Anders Carlsson3068d112008-11-16 19:01:22 +00001025 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001026 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001027 }
Mike Stump1eb44332009-09-09 15:08:12 +00001028
Anders Carlsson3f704562008-12-21 22:39:40 +00001029 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001030 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001031 }
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Douglas Gregored8abf12010-07-08 06:14:04 +00001033 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001034 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001035 }
1036
Eli Friedman664a1042009-02-27 04:45:43 +00001037 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1038 return Success(0, E);
1039 }
1040
Sebastian Redl64b45f72009-01-05 20:52:13 +00001041 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001042 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001043 }
1044
Francois Pichet6ad6f282010-12-07 00:08:36 +00001045 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1046 return Success(E->getValue(), E);
1047 }
1048
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001049 bool VisitChooseExpr(const ChooseExpr *E) {
1050 return Visit(E->getChosenSubExpr(Info.Ctx));
1051 }
1052
Eli Friedman722c7172009-02-28 03:59:05 +00001053 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001054 bool VisitUnaryImag(const UnaryOperator *E);
1055
Sebastian Redl295995c2010-09-10 20:55:47 +00001056 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001057 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1058
Chris Lattnerfcee0012008-07-11 21:24:13 +00001059private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001060 CharUnits GetAlignOfExpr(const Expr *E);
1061 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001062 static QualType GetObjectType(const Expr *E);
1063 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001064 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001065};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001066} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001067
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001068static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001069 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001070 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1071}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001072
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001073static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001074 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001075
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001076 APValue Val;
1077 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1078 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001079 Result = Val.getInt();
1080 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001081}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001082
Eli Friedman04309752009-11-24 05:28:59 +00001083bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001084 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001085 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1086 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001087
1088 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001089 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001090 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1091 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001092
1093 if (isa<ParmVarDecl>(D))
1094 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1095
Eli Friedman04309752009-11-24 05:28:59 +00001096 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001097 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001098 if (APValue *V = VD->getEvaluatedValue()) {
1099 if (V->isInt())
1100 return Success(V->getInt(), E);
1101 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1102 }
1103
1104 if (VD->isEvaluatingValue())
1105 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1106
1107 VD->setEvaluatingValue();
1108
Eli Friedmana7dedf72010-09-06 00:10:32 +00001109 Expr::EvalResult EResult;
1110 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1111 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001112 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001113 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001114 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001115 return true;
1116 }
1117
Eli Friedmanc0131182009-12-03 20:31:57 +00001118 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001119 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001120 }
1121 }
1122
Chris Lattner4c4867e2008-07-12 00:38:25 +00001123 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001124 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001125}
1126
Chris Lattnera4d55d82008-10-06 06:40:35 +00001127/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1128/// as GCC.
1129static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1130 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001131 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001132 enum gcc_type_class {
1133 no_type_class = -1,
1134 void_type_class, integer_type_class, char_type_class,
1135 enumeral_type_class, boolean_type_class,
1136 pointer_type_class, reference_type_class, offset_type_class,
1137 real_type_class, complex_type_class,
1138 function_type_class, method_type_class,
1139 record_type_class, union_type_class,
1140 array_type_class, string_type_class,
1141 lang_type_class
1142 };
Mike Stump1eb44332009-09-09 15:08:12 +00001143
1144 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001145 // ideal, however it is what gcc does.
1146 if (E->getNumArgs() == 0)
1147 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Chris Lattnera4d55d82008-10-06 06:40:35 +00001149 QualType ArgTy = E->getArg(0)->getType();
1150 if (ArgTy->isVoidType())
1151 return void_type_class;
1152 else if (ArgTy->isEnumeralType())
1153 return enumeral_type_class;
1154 else if (ArgTy->isBooleanType())
1155 return boolean_type_class;
1156 else if (ArgTy->isCharType())
1157 return string_type_class; // gcc doesn't appear to use char_type_class
1158 else if (ArgTy->isIntegerType())
1159 return integer_type_class;
1160 else if (ArgTy->isPointerType())
1161 return pointer_type_class;
1162 else if (ArgTy->isReferenceType())
1163 return reference_type_class;
1164 else if (ArgTy->isRealType())
1165 return real_type_class;
1166 else if (ArgTy->isComplexType())
1167 return complex_type_class;
1168 else if (ArgTy->isFunctionType())
1169 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001170 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001171 return record_type_class;
1172 else if (ArgTy->isUnionType())
1173 return union_type_class;
1174 else if (ArgTy->isArrayType())
1175 return array_type_class;
1176 else if (ArgTy->isUnionType())
1177 return union_type_class;
1178 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1179 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1180 return -1;
1181}
1182
John McCall42c8f872010-05-10 23:27:23 +00001183/// Retrieves the "underlying object type" of the given expression,
1184/// as used by __builtin_object_size.
1185QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1186 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1187 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1188 return VD->getType();
1189 } else if (isa<CompoundLiteralExpr>(E)) {
1190 return E->getType();
1191 }
1192
1193 return QualType();
1194}
1195
1196bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1197 // TODO: Perhaps we should let LLVM lower this?
1198 LValue Base;
1199 if (!EvaluatePointer(E->getArg(0), Base, Info))
1200 return false;
1201
1202 // If we can prove the base is null, lower to zero now.
1203 const Expr *LVBase = Base.getLValueBase();
1204 if (!LVBase) return Success(0, E);
1205
1206 QualType T = GetObjectType(LVBase);
1207 if (T.isNull() ||
1208 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001209 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001210 T->isVariablyModifiedType() ||
1211 T->isDependentType())
1212 return false;
1213
1214 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1215 CharUnits Offset = Base.getLValueOffset();
1216
1217 if (!Offset.isNegative() && Offset <= Size)
1218 Size -= Offset;
1219 else
1220 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001221 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001222}
1223
Eli Friedmanc4a26382010-02-13 00:10:10 +00001224bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001225 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001226 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001227 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001228
1229 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001230 if (TryEvaluateBuiltinObjectSize(E))
1231 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001232
Eric Christopherb2aaf512010-01-19 22:58:35 +00001233 // If evaluating the argument has side-effects we can't determine
1234 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001235 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001236 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001237 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001238 return Success(0, E);
1239 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001240
Mike Stump64eda9e2009-10-26 18:35:08 +00001241 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1242 }
1243
Chris Lattner019f4e82008-10-06 05:28:25 +00001244 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001245 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001246
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001247 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001248 // __builtin_constant_p always has one operand: it returns true if that
1249 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001250 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001251
1252 case Builtin::BI__builtin_eh_return_data_regno: {
1253 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1254 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1255 return Success(Operand, E);
1256 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001257
1258 case Builtin::BI__builtin_expect:
1259 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001260
1261 case Builtin::BIstrlen:
1262 case Builtin::BI__builtin_strlen:
1263 // As an extension, we support strlen() and __builtin_strlen() as constant
1264 // expressions when the argument is a string literal.
1265 if (StringLiteral *S
1266 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1267 // The string literal may have embedded null characters. Find the first
1268 // one and truncate there.
1269 llvm::StringRef Str = S->getString();
1270 llvm::StringRef::size_type Pos = Str.find(0);
1271 if (Pos != llvm::StringRef::npos)
1272 Str = Str.substr(0, Pos);
1273
1274 return Success(Str.size(), E);
1275 }
1276
1277 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001278 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001279}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001280
Chris Lattnerb542afe2008-07-11 19:10:17 +00001281bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001282 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001283 if (!Visit(E->getRHS()))
1284 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001285
Eli Friedman33ef1452009-02-26 10:19:36 +00001286 // If we can't evaluate the LHS, it might have side effects;
1287 // conservatively mark it.
1288 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1289 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001290
Anders Carlsson027f62e2008-12-01 02:07:06 +00001291 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001292 }
1293
1294 if (E->isLogicalOp()) {
1295 // These need to be handled specially because the operands aren't
1296 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001297 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001298
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001299 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001300 // We were able to evaluate the LHS, see if we can get away with not
1301 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001302 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001303 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001304
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001305 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001306 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001307 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001308 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001309 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001310 }
1311 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001312 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001313 // We can't evaluate the LHS; however, sometimes the result
1314 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001315 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1316 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001317 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001318 // must have had side effects.
1319 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001320
1321 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001322 }
1323 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001324 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001325
Eli Friedmana6afa762008-11-13 06:09:17 +00001326 return false;
1327 }
1328
Anders Carlsson286f85e2008-11-16 07:17:21 +00001329 QualType LHSTy = E->getLHS()->getType();
1330 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001331
1332 if (LHSTy->isAnyComplexType()) {
1333 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001334 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001335
1336 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1337 return false;
1338
1339 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1340 return false;
1341
1342 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001343 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001344 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001345 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001346 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1347
John McCall2de56d12010-08-25 11:45:40 +00001348 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001349 return Success((CR_r == APFloat::cmpEqual &&
1350 CR_i == APFloat::cmpEqual), E);
1351 else {
John McCall2de56d12010-08-25 11:45:40 +00001352 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001353 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001354 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001355 CR_r == APFloat::cmpLessThan ||
1356 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001357 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001358 CR_i == APFloat::cmpLessThan ||
1359 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001360 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001361 } else {
John McCall2de56d12010-08-25 11:45:40 +00001362 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001363 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1364 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1365 else {
John McCall2de56d12010-08-25 11:45:40 +00001366 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001367 "Invalid compex comparison.");
1368 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1369 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1370 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001371 }
1372 }
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Anders Carlsson286f85e2008-11-16 07:17:21 +00001374 if (LHSTy->isRealFloatingType() &&
1375 RHSTy->isRealFloatingType()) {
1376 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001377
Anders Carlsson286f85e2008-11-16 07:17:21 +00001378 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1379 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001380
Anders Carlsson286f85e2008-11-16 07:17:21 +00001381 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1382 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001383
Anders Carlsson286f85e2008-11-16 07:17:21 +00001384 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001385
Anders Carlsson286f85e2008-11-16 07:17:21 +00001386 switch (E->getOpcode()) {
1387 default:
1388 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001389 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001390 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001391 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001392 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001393 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001394 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001395 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001396 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001397 E);
John McCall2de56d12010-08-25 11:45:40 +00001398 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001399 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001400 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001401 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001402 || CR == APFloat::cmpLessThan
1403 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001404 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001407 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001408 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001409 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001410 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1411 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001412
John McCallefdb83e2010-05-07 21:00:08 +00001413 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001414 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1415 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001416
Eli Friedman5bc86102009-06-14 02:17:33 +00001417 // Reject any bases from the normal codepath; we special-case comparisons
1418 // to null.
1419 if (LHSValue.getLValueBase()) {
1420 if (!E->isEqualityOp())
1421 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001422 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001423 return false;
1424 bool bres;
1425 if (!EvalPointerValueAsBool(LHSValue, bres))
1426 return false;
John McCall2de56d12010-08-25 11:45:40 +00001427 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001428 } else if (RHSValue.getLValueBase()) {
1429 if (!E->isEqualityOp())
1430 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001431 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001432 return false;
1433 bool bres;
1434 if (!EvalPointerValueAsBool(RHSValue, bres))
1435 return false;
John McCall2de56d12010-08-25 11:45:40 +00001436 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001437 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001438
John McCall2de56d12010-08-25 11:45:40 +00001439 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001440 QualType Type = E->getLHS()->getType();
1441 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001442
Ken Dycka7305832010-01-15 12:37:54 +00001443 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001444 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001445 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001446
Ken Dycka7305832010-01-15 12:37:54 +00001447 CharUnits Diff = LHSValue.getLValueOffset() -
1448 RHSValue.getLValueOffset();
1449 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001450 }
1451 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001452 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001453 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001454 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001455 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1456 }
1457 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001458 }
1459 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001460 if (!LHSTy->isIntegralOrEnumerationType() ||
1461 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001462 // We can't continue from here for non-integral types, and they
1463 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001464 return false;
1465 }
1466
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001467 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001468 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001469 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001470
Eli Friedman42edd0d2009-03-24 01:14:50 +00001471 APValue RHSVal;
1472 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001473 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001474
1475 // Handle cases like (unsigned long)&a + 4.
1476 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001477 CharUnits Offset = Result.getLValueOffset();
1478 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1479 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001480 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001481 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001482 else
Ken Dycka7305832010-01-15 12:37:54 +00001483 Offset -= AdditionalOffset;
1484 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001485 return true;
1486 }
1487
1488 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001489 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001490 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001491 CharUnits Offset = RHSVal.getLValueOffset();
1492 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1493 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001494 return true;
1495 }
1496
1497 // All the following cases expect both operands to be an integer
1498 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001499 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001500
Eli Friedman42edd0d2009-03-24 01:14:50 +00001501 APSInt& RHS = RHSVal.getInt();
1502
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001503 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001504 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001505 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001506 case BO_Mul: return Success(Result.getInt() * RHS, E);
1507 case BO_Add: return Success(Result.getInt() + RHS, E);
1508 case BO_Sub: return Success(Result.getInt() - RHS, E);
1509 case BO_And: return Success(Result.getInt() & RHS, E);
1510 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1511 case BO_Or: return Success(Result.getInt() | RHS, E);
1512 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001513 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001514 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001515 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001516 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001517 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001518 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001519 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001520 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001521 // During constant-folding, a negative shift is an opposite shift.
1522 if (RHS.isSigned() && RHS.isNegative()) {
1523 RHS = -RHS;
1524 goto shift_right;
1525 }
1526
1527 shift_left:
1528 unsigned SA
1529 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001530 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001531 }
John McCall2de56d12010-08-25 11:45:40 +00001532 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001533 // During constant-folding, a negative shift is an opposite shift.
1534 if (RHS.isSigned() && RHS.isNegative()) {
1535 RHS = -RHS;
1536 goto shift_left;
1537 }
1538
1539 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001540 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001541 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1542 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001543 }
Mike Stump1eb44332009-09-09 15:08:12 +00001544
John McCall2de56d12010-08-25 11:45:40 +00001545 case BO_LT: return Success(Result.getInt() < RHS, E);
1546 case BO_GT: return Success(Result.getInt() > RHS, E);
1547 case BO_LE: return Success(Result.getInt() <= RHS, E);
1548 case BO_GE: return Success(Result.getInt() >= RHS, E);
1549 case BO_EQ: return Success(Result.getInt() == RHS, E);
1550 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001551 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001552}
1553
John McCall56ca35d2011-02-17 10:25:35 +00001554bool IntExprEvaluator::
1555VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
1556 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
1557 if (opaque.hasError()) return false;
1558
1559 bool cond;
1560 if (!HandleConversionToBool(e->getCond(), cond, Info))
1561 return false;
1562
1563 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
1564}
1565
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001566bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001567 bool Cond;
1568 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001569 return false;
1570
Nuno Lopesa25bd552008-11-16 22:06:39 +00001571 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001572}
1573
Ken Dyck8b752f12010-01-27 17:10:57 +00001574CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001575 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1576 // the result is the size of the referenced type."
1577 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1578 // result shall be the alignment of the referenced type."
1579 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1580 T = Ref->getPointeeType();
1581
Eli Friedman2be58612009-05-30 21:09:44 +00001582 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001583 return Info.Ctx.toCharUnitsFromBits(
1584 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001585}
1586
Ken Dyck8b752f12010-01-27 17:10:57 +00001587CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001588 E = E->IgnoreParens();
1589
1590 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001591 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001592 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001593 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1594 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001595
Chris Lattneraf707ab2009-01-24 21:53:27 +00001596 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001597 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1598 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001599
Chris Lattnere9feb472009-01-24 21:09:06 +00001600 return GetAlignOfType(E->getType());
1601}
1602
1603
Sebastian Redl05189992008-11-11 17:56:53 +00001604/// VisitSizeAlignOfExpr - Evaluate a sizeof or alignof with a result as the
1605/// expression's type.
1606bool IntExprEvaluator::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Chris Lattnere9feb472009-01-24 21:09:06 +00001607 // Handle alignof separately.
1608 if (!E->isSizeOf()) {
1609 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001610 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001611 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001612 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001613 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001614
Sebastian Redl05189992008-11-11 17:56:53 +00001615 QualType SrcTy = E->getTypeOfArgument();
Sebastian Redl5d484e82009-11-23 17:18:46 +00001616 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1617 // the result is the size of the referenced type."
1618 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1619 // result shall be the alignment of the referenced type."
1620 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1621 SrcTy = Ref->getPointeeType();
Sebastian Redl05189992008-11-11 17:56:53 +00001622
Daniel Dunbar131eb432009-02-19 09:06:44 +00001623 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1624 // extension.
1625 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1626 return Success(1, E);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001627
Chris Lattnerfcee0012008-07-11 21:24:13 +00001628 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Chris Lattnere9feb472009-01-24 21:09:06 +00001629 if (!SrcTy->isConstantSizeType())
Chris Lattnerfcee0012008-07-11 21:24:13 +00001630 return false;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001631
Chris Lattnere9feb472009-01-24 21:09:06 +00001632 // Get information about the size.
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001633 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
Chris Lattnerfcee0012008-07-11 21:24:13 +00001634}
1635
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001636bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1637 CharUnits Result;
1638 unsigned n = E->getNumComponents();
1639 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1640 if (n == 0)
1641 return false;
1642 QualType CurrentType = E->getTypeSourceInfo()->getType();
1643 for (unsigned i = 0; i != n; ++i) {
1644 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1645 switch (ON.getKind()) {
1646 case OffsetOfExpr::OffsetOfNode::Array: {
1647 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1648 APSInt IdxResult;
1649 if (!EvaluateInteger(Idx, IdxResult, Info))
1650 return false;
1651 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1652 if (!AT)
1653 return false;
1654 CurrentType = AT->getElementType();
1655 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1656 Result += IdxResult.getSExtValue() * ElementSize;
1657 break;
1658 }
1659
1660 case OffsetOfExpr::OffsetOfNode::Field: {
1661 FieldDecl *MemberDecl = ON.getField();
1662 const RecordType *RT = CurrentType->getAs<RecordType>();
1663 if (!RT)
1664 return false;
1665 RecordDecl *RD = RT->getDecl();
1666 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001667 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001668 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001669 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001670 CurrentType = MemberDecl->getType().getNonReferenceType();
1671 break;
1672 }
1673
1674 case OffsetOfExpr::OffsetOfNode::Identifier:
1675 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001676 return false;
1677
1678 case OffsetOfExpr::OffsetOfNode::Base: {
1679 CXXBaseSpecifier *BaseSpec = ON.getBase();
1680 if (BaseSpec->isVirtual())
1681 return false;
1682
1683 // Find the layout of the class whose base we are looking into.
1684 const RecordType *RT = CurrentType->getAs<RecordType>();
1685 if (!RT)
1686 return false;
1687 RecordDecl *RD = RT->getDecl();
1688 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1689
1690 // Find the base class itself.
1691 CurrentType = BaseSpec->getType();
1692 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1693 if (!BaseRT)
1694 return false;
1695
1696 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001697 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001698 break;
1699 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001700 }
1701 }
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001702 return Success(Result, E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001703}
1704
Chris Lattnerb542afe2008-07-11 19:10:17 +00001705bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001706 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001707 // LNot's operand isn't necessarily an integer, so we handle it specially.
1708 bool bres;
1709 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1710 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001711 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001712 }
1713
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001714 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001715 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001716 return false;
1717
Chris Lattner87eae5e2008-07-11 22:52:41 +00001718 // Get the operand value into 'Result'.
1719 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001720 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001721
Chris Lattner75a48812008-07-11 22:15:16 +00001722 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001723 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001724 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1725 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001726 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001727 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001728 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1729 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001730 return true;
John McCall2de56d12010-08-25 11:45:40 +00001731 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001732 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001733 return true;
John McCall2de56d12010-08-25 11:45:40 +00001734 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001735 if (!Result.isInt()) return false;
1736 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001737 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001738 if (!Result.isInt()) return false;
1739 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001740 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001741}
Mike Stump1eb44332009-09-09 15:08:12 +00001742
Chris Lattner732b2232008-07-12 01:15:53 +00001743/// HandleCast - This is used to evaluate implicit or explicit casts where the
1744/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001745bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001746 Expr *SubExpr = E->getSubExpr();
1747 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001748 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001749
Eli Friedman4efaa272008-11-12 09:44:48 +00001750 if (DestType->isBooleanType()) {
1751 bool BoolResult;
1752 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1753 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001754 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001755 }
1756
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001757 // Handle simple integer->integer casts.
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001758 if (SrcType->isIntegralOrEnumerationType()) {
Chris Lattner732b2232008-07-12 01:15:53 +00001759 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001760 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001761
Eli Friedmanbe265702009-02-20 01:15:07 +00001762 if (!Result.isInt()) {
1763 // Only allow casts of lvalues if they are lossless.
1764 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1765 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001766
Daniel Dunbardd211642009-02-19 22:24:01 +00001767 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001768 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001769 }
Mike Stump1eb44332009-09-09 15:08:12 +00001770
Chris Lattner732b2232008-07-12 01:15:53 +00001771 // FIXME: Clean this up!
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001772 if (SrcType->isPointerType()) {
John McCallefdb83e2010-05-07 21:00:08 +00001773 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001774 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001775 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001776
Daniel Dunbardd211642009-02-19 22:24:01 +00001777 if (LV.getLValueBase()) {
1778 // Only allow based lvalue casts if they are lossless.
1779 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1780 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001781
John McCallefdb83e2010-05-07 21:00:08 +00001782 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001783 return true;
1784 }
1785
Ken Dycka7305832010-01-15 12:37:54 +00001786 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1787 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001788 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001789 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001790
Eli Friedmanbe265702009-02-20 01:15:07 +00001791 if (SrcType->isArrayType() || SrcType->isFunctionType()) {
1792 // This handles double-conversion cases, where there's both
1793 // an l-value promotion and an implicit conversion to int.
John McCallefdb83e2010-05-07 21:00:08 +00001794 LValue LV;
Eli Friedmanbe265702009-02-20 01:15:07 +00001795 if (!EvaluateLValue(SubExpr, LV, Info))
1796 return false;
1797
1798 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(Info.Ctx.VoidPtrTy))
1799 return false;
1800
John McCallefdb83e2010-05-07 21:00:08 +00001801 LV.moveInto(Result);
Eli Friedmanbe265702009-02-20 01:15:07 +00001802 return true;
1803 }
1804
Eli Friedman1725f682009-04-22 19:23:09 +00001805 if (SrcType->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001806 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001807 if (!EvaluateComplex(SubExpr, C, Info))
1808 return false;
1809 if (C.isComplexFloat())
1810 return Success(HandleFloatToIntCast(DestType, SrcType,
1811 C.getComplexFloatReal(), Info.Ctx),
1812 E);
1813 else
1814 return Success(HandleIntToIntCast(DestType, SrcType,
1815 C.getComplexIntReal(), Info.Ctx), E);
1816 }
Eli Friedman2217c872009-02-22 11:46:18 +00001817 // FIXME: Handle vectors
1818
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001819 if (!SrcType->isRealFloatingType())
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001820 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner732b2232008-07-12 01:15:53 +00001821
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001822 APFloat F(0.0);
1823 if (!EvaluateFloat(SubExpr, F, Info))
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001824 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001826 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001827}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001828
Eli Friedman722c7172009-02-28 03:59:05 +00001829bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1830 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001831 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001832 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1833 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1834 return Success(LV.getComplexIntReal(), E);
1835 }
1836
1837 return Visit(E->getSubExpr());
1838}
1839
Eli Friedman664a1042009-02-27 04:45:43 +00001840bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001841 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001842 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001843 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1844 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1845 return Success(LV.getComplexIntImag(), E);
1846 }
1847
Eli Friedman664a1042009-02-27 04:45:43 +00001848 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1849 Info.EvalResult.HasSideEffects = true;
1850 return Success(0, E);
1851}
1852
Douglas Gregoree8aff02011-01-04 17:33:58 +00001853bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1854 return Success(E->getPackLength(), E);
1855}
1856
Sebastian Redl295995c2010-09-10 20:55:47 +00001857bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1858 return Success(E->getValue(), E);
1859}
1860
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001861//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001862// Float Evaluation
1863//===----------------------------------------------------------------------===//
1864
1865namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001866class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001867 : public StmtVisitor<FloatExprEvaluator, bool> {
1868 EvalInfo &Info;
1869 APFloat &Result;
1870public:
1871 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1872 : Info(info), Result(result) {}
1873
1874 bool VisitStmt(Stmt *S) {
1875 return false;
1876 }
1877
1878 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Chris Lattner019f4e82008-10-06 05:28:25 +00001879 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001880
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001881 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001882 bool VisitBinaryOperator(const BinaryOperator *E);
1883 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001884 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001885 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001886 bool VisitConditionalOperator(ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001887 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001888
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001889 bool VisitChooseExpr(const ChooseExpr *E)
1890 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1891 bool VisitUnaryExtension(const UnaryOperator *E)
1892 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001893 bool VisitUnaryReal(const UnaryOperator *E);
1894 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001895
John McCall189d6ef2010-10-09 01:34:31 +00001896 bool VisitDeclRefExpr(const DeclRefExpr *E);
1897
John McCall56ca35d2011-02-17 10:25:35 +00001898 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
1899 const APValue *value = Info.getOpaqueValue(e);
1900 if (!value)
1901 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
1902 Result = value->getFloat();
1903 return true;
1904 }
1905
John McCallabd3a852010-05-07 22:08:54 +00001906 // FIXME: Missing: array subscript of vector, member of vector,
1907 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001908};
1909} // end anonymous namespace
1910
1911static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001912 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001913 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1914}
1915
Jay Foad4ba2a172011-01-12 09:06:06 +00001916static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001917 QualType ResultTy,
1918 const Expr *Arg,
1919 bool SNaN,
1920 llvm::APFloat &Result) {
1921 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1922 if (!S) return false;
1923
1924 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1925
1926 llvm::APInt fill;
1927
1928 // Treat empty strings as if they were zero.
1929 if (S->getString().empty())
1930 fill = llvm::APInt(32, 0);
1931 else if (S->getString().getAsInteger(0, fill))
1932 return false;
1933
1934 if (SNaN)
1935 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1936 else
1937 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1938 return true;
1939}
1940
Chris Lattner019f4e82008-10-06 05:28:25 +00001941bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001942 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00001943 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00001944 case Builtin::BI__builtin_huge_val:
1945 case Builtin::BI__builtin_huge_valf:
1946 case Builtin::BI__builtin_huge_vall:
1947 case Builtin::BI__builtin_inf:
1948 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001949 case Builtin::BI__builtin_infl: {
1950 const llvm::fltSemantics &Sem =
1951 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00001952 Result = llvm::APFloat::getInf(Sem);
1953 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00001954 }
Mike Stump1eb44332009-09-09 15:08:12 +00001955
John McCalldb7b72a2010-02-28 13:00:19 +00001956 case Builtin::BI__builtin_nans:
1957 case Builtin::BI__builtin_nansf:
1958 case Builtin::BI__builtin_nansl:
1959 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1960 true, Result);
1961
Chris Lattner9e621712008-10-06 06:31:58 +00001962 case Builtin::BI__builtin_nan:
1963 case Builtin::BI__builtin_nanf:
1964 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00001965 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00001966 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00001967 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
1968 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001969
1970 case Builtin::BI__builtin_fabs:
1971 case Builtin::BI__builtin_fabsf:
1972 case Builtin::BI__builtin_fabsl:
1973 if (!EvaluateFloat(E->getArg(0), Result, Info))
1974 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001975
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001976 if (Result.isNegative())
1977 Result.changeSign();
1978 return true;
1979
Mike Stump1eb44332009-09-09 15:08:12 +00001980 case Builtin::BI__builtin_copysign:
1981 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001982 case Builtin::BI__builtin_copysignl: {
1983 APFloat RHS(0.);
1984 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
1985 !EvaluateFloat(E->getArg(1), RHS, Info))
1986 return false;
1987 Result.copySign(RHS);
1988 return true;
1989 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001990 }
1991}
1992
John McCall189d6ef2010-10-09 01:34:31 +00001993bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
1994 const Decl *D = E->getDecl();
1995 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
1996 const VarDecl *VD = cast<VarDecl>(D);
1997
1998 // Require the qualifiers to be const and not volatile.
1999 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2000 if (!T.isConstQualified() || T.isVolatileQualified())
2001 return false;
2002
2003 const Expr *Init = VD->getAnyInitializer();
2004 if (!Init) return false;
2005
2006 if (APValue *V = VD->getEvaluatedValue()) {
2007 if (V->isFloat()) {
2008 Result = V->getFloat();
2009 return true;
2010 }
2011 return false;
2012 }
2013
2014 if (VD->isEvaluatingValue())
2015 return false;
2016
2017 VD->setEvaluatingValue();
2018
2019 Expr::EvalResult InitResult;
2020 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2021 InitResult.Val.isFloat()) {
2022 // Cache the evaluated value in the variable declaration.
2023 Result = InitResult.Val.getFloat();
2024 VD->setEvaluatedValue(InitResult.Val);
2025 return true;
2026 }
2027
2028 VD->setEvaluatedValue(APValue());
2029 return false;
2030}
2031
John McCallabd3a852010-05-07 22:08:54 +00002032bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002033 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2034 ComplexValue CV;
2035 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2036 return false;
2037 Result = CV.FloatReal;
2038 return true;
2039 }
2040
2041 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002042}
2043
2044bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002045 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2046 ComplexValue CV;
2047 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2048 return false;
2049 Result = CV.FloatImag;
2050 return true;
2051 }
2052
2053 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2054 Info.EvalResult.HasSideEffects = true;
2055 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2056 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002057 return true;
2058}
2059
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002060bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002061 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002062 return false;
2063
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002064 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2065 return false;
2066
2067 switch (E->getOpcode()) {
2068 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002069 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002070 return true;
John McCall2de56d12010-08-25 11:45:40 +00002071 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002072 Result.changeSign();
2073 return true;
2074 }
2075}
Chris Lattner019f4e82008-10-06 05:28:25 +00002076
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002077bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002078 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002079 if (!EvaluateFloat(E->getRHS(), Result, Info))
2080 return false;
2081
2082 // If we can't evaluate the LHS, it might have side effects;
2083 // conservatively mark it.
2084 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2085 Info.EvalResult.HasSideEffects = true;
2086
2087 return true;
2088 }
2089
Anders Carlsson96e93662010-10-31 01:21:47 +00002090 // We can't evaluate pointer-to-member operations.
2091 if (E->isPtrMemOp())
2092 return false;
2093
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002094 // FIXME: Diagnostics? I really don't understand how the warnings
2095 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002096 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002097 if (!EvaluateFloat(E->getLHS(), Result, Info))
2098 return false;
2099 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2100 return false;
2101
2102 switch (E->getOpcode()) {
2103 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002104 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002105 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2106 return true;
John McCall2de56d12010-08-25 11:45:40 +00002107 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002108 Result.add(RHS, APFloat::rmNearestTiesToEven);
2109 return true;
John McCall2de56d12010-08-25 11:45:40 +00002110 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002111 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2112 return true;
John McCall2de56d12010-08-25 11:45:40 +00002113 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002114 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2115 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002116 }
2117}
2118
2119bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2120 Result = E->getValue();
2121 return true;
2122}
2123
Eli Friedman4efaa272008-11-12 09:44:48 +00002124bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2125 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002126
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002127 if (SubExpr->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002128 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002129 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002130 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002131 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002132 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002133 return true;
2134 }
2135 if (SubExpr->getType()->isRealFloatingType()) {
2136 if (!Visit(SubExpr))
2137 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002138 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2139 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002140 return true;
2141 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002142
2143 if (E->getCastKind() == CK_FloatingComplexToReal) {
2144 ComplexValue V;
2145 if (!EvaluateComplex(SubExpr, V, Info))
2146 return false;
2147 Result = V.getComplexFloatReal();
2148 return true;
2149 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002150
2151 return false;
2152}
2153
Douglas Gregored8abf12010-07-08 06:14:04 +00002154bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002155 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2156 return true;
2157}
2158
John McCall56ca35d2011-02-17 10:25:35 +00002159bool FloatExprEvaluator::
2160VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
2161 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2162 if (opaque.hasError()) return false;
2163
2164 bool cond;
2165 if (!HandleConversionToBool(e->getCond(), cond, Info))
2166 return false;
2167
2168 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2169}
2170
Eli Friedman67f85fc2009-12-04 02:12:53 +00002171bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2172 bool Cond;
2173 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2174 return false;
2175
2176 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2177}
2178
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002179//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002180// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002181//===----------------------------------------------------------------------===//
2182
2183namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002184class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002185 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002186 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002187 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002188
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002189public:
John McCallf4cf1a12010-05-07 17:22:02 +00002190 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2191 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002192
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002193 //===--------------------------------------------------------------------===//
2194 // Visitor Methods
2195 //===--------------------------------------------------------------------===//
2196
John McCallf4cf1a12010-05-07 17:22:02 +00002197 bool VisitStmt(Stmt *S) {
2198 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002199 }
Mike Stump1eb44332009-09-09 15:08:12 +00002200
John McCallf4cf1a12010-05-07 17:22:02 +00002201 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002202
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002203 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002204
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002205 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
John McCallf4cf1a12010-05-07 17:22:02 +00002207 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002208 bool VisitUnaryOperator(const UnaryOperator *E);
2209 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00002210 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002211 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002212 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002213 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002214 { return Visit(E->getSubExpr()); }
John McCall56ca35d2011-02-17 10:25:35 +00002215 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
2216 const APValue *value = Info.getOpaqueValue(e);
2217 if (!value)
2218 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
2219 Result.setFrom(*value);
2220 return true;
2221 }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002222 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002223};
2224} // end anonymous namespace
2225
John McCallf4cf1a12010-05-07 17:22:02 +00002226static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2227 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002228 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002229 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002230}
2231
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002232bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2233 Expr* SubExpr = E->getSubExpr();
2234
2235 if (SubExpr->getType()->isRealFloatingType()) {
2236 Result.makeComplexFloat();
2237 APFloat &Imag = Result.FloatImag;
2238 if (!EvaluateFloat(SubExpr, Imag, Info))
2239 return false;
2240
2241 Result.FloatReal = APFloat(Imag.getSemantics());
2242 return true;
2243 } else {
2244 assert(SubExpr->getType()->isIntegerType() &&
2245 "Unexpected imaginary literal.");
2246
2247 Result.makeComplexInt();
2248 APSInt &Imag = Result.IntImag;
2249 if (!EvaluateInteger(SubExpr, Imag, Info))
2250 return false;
2251
2252 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2253 return true;
2254 }
2255}
2256
2257bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002258
John McCall8786da72010-12-14 17:51:41 +00002259 switch (E->getCastKind()) {
2260 case CK_BitCast:
2261 case CK_LValueBitCast:
2262 case CK_BaseToDerived:
2263 case CK_DerivedToBase:
2264 case CK_UncheckedDerivedToBase:
2265 case CK_Dynamic:
2266 case CK_ToUnion:
2267 case CK_ArrayToPointerDecay:
2268 case CK_FunctionToPointerDecay:
2269 case CK_NullToPointer:
2270 case CK_NullToMemberPointer:
2271 case CK_BaseToDerivedMemberPointer:
2272 case CK_DerivedToBaseMemberPointer:
2273 case CK_MemberPointerToBoolean:
2274 case CK_ConstructorConversion:
2275 case CK_IntegralToPointer:
2276 case CK_PointerToIntegral:
2277 case CK_PointerToBoolean:
2278 case CK_ToVoid:
2279 case CK_VectorSplat:
2280 case CK_IntegralCast:
2281 case CK_IntegralToBoolean:
2282 case CK_IntegralToFloating:
2283 case CK_FloatingToIntegral:
2284 case CK_FloatingToBoolean:
2285 case CK_FloatingCast:
2286 case CK_AnyPointerToObjCPointerCast:
2287 case CK_AnyPointerToBlockPointerCast:
2288 case CK_ObjCObjectLValueCast:
2289 case CK_FloatingComplexToReal:
2290 case CK_FloatingComplexToBoolean:
2291 case CK_IntegralComplexToReal:
2292 case CK_IntegralComplexToBoolean:
2293 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002294
John McCall8786da72010-12-14 17:51:41 +00002295 case CK_LValueToRValue:
2296 case CK_NoOp:
2297 return Visit(E->getSubExpr());
2298
2299 case CK_Dependent:
2300 case CK_GetObjCProperty:
2301 case CK_UserDefinedConversion:
2302 return false;
2303
2304 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002305 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002306 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002307 return false;
2308
John McCall8786da72010-12-14 17:51:41 +00002309 Result.makeComplexFloat();
2310 Result.FloatImag = APFloat(Real.getSemantics());
2311 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002312 }
2313
John McCall8786da72010-12-14 17:51:41 +00002314 case CK_FloatingComplexCast: {
2315 if (!Visit(E->getSubExpr()))
2316 return false;
2317
2318 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2319 QualType From
2320 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2321
2322 Result.FloatReal
2323 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2324 Result.FloatImag
2325 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2326 return true;
2327 }
2328
2329 case CK_FloatingComplexToIntegralComplex: {
2330 if (!Visit(E->getSubExpr()))
2331 return false;
2332
2333 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2334 QualType From
2335 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2336 Result.makeComplexInt();
2337 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2338 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2339 return true;
2340 }
2341
2342 case CK_IntegralRealToComplex: {
2343 APSInt &Real = Result.IntReal;
2344 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2345 return false;
2346
2347 Result.makeComplexInt();
2348 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2349 return true;
2350 }
2351
2352 case CK_IntegralComplexCast: {
2353 if (!Visit(E->getSubExpr()))
2354 return false;
2355
2356 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2357 QualType From
2358 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2359
2360 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2361 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2362 return true;
2363 }
2364
2365 case CK_IntegralComplexToFloatingComplex: {
2366 if (!Visit(E->getSubExpr()))
2367 return false;
2368
2369 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2370 QualType From
2371 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2372 Result.makeComplexFloat();
2373 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2374 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2375 return true;
2376 }
2377 }
2378
2379 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002380 return false;
2381}
2382
John McCallf4cf1a12010-05-07 17:22:02 +00002383bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002384 if (E->getOpcode() == BO_Comma) {
2385 if (!Visit(E->getRHS()))
2386 return false;
2387
2388 // If we can't evaluate the LHS, it might have side effects;
2389 // conservatively mark it.
2390 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2391 Info.EvalResult.HasSideEffects = true;
2392
2393 return true;
2394 }
John McCallf4cf1a12010-05-07 17:22:02 +00002395 if (!Visit(E->getLHS()))
2396 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002397
John McCallf4cf1a12010-05-07 17:22:02 +00002398 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002399 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002400 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002401
Daniel Dunbar3f279872009-01-29 01:32:56 +00002402 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2403 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002404 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002405 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002406 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002407 if (Result.isComplexFloat()) {
2408 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2409 APFloat::rmNearestTiesToEven);
2410 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2411 APFloat::rmNearestTiesToEven);
2412 } else {
2413 Result.getComplexIntReal() += RHS.getComplexIntReal();
2414 Result.getComplexIntImag() += RHS.getComplexIntImag();
2415 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002416 break;
John McCall2de56d12010-08-25 11:45:40 +00002417 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002418 if (Result.isComplexFloat()) {
2419 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2420 APFloat::rmNearestTiesToEven);
2421 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2422 APFloat::rmNearestTiesToEven);
2423 } else {
2424 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2425 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2426 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002427 break;
John McCall2de56d12010-08-25 11:45:40 +00002428 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002429 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002430 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002431 APFloat &LHS_r = LHS.getComplexFloatReal();
2432 APFloat &LHS_i = LHS.getComplexFloatImag();
2433 APFloat &RHS_r = RHS.getComplexFloatReal();
2434 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002435
Daniel Dunbar3f279872009-01-29 01:32:56 +00002436 APFloat Tmp = LHS_r;
2437 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2438 Result.getComplexFloatReal() = Tmp;
2439 Tmp = LHS_i;
2440 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2441 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2442
2443 Tmp = LHS_r;
2444 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2445 Result.getComplexFloatImag() = Tmp;
2446 Tmp = LHS_i;
2447 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2448 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2449 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002450 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002451 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002452 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2453 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002454 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002455 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2456 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2457 }
2458 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002459 case BO_Div:
2460 if (Result.isComplexFloat()) {
2461 ComplexValue LHS = Result;
2462 APFloat &LHS_r = LHS.getComplexFloatReal();
2463 APFloat &LHS_i = LHS.getComplexFloatImag();
2464 APFloat &RHS_r = RHS.getComplexFloatReal();
2465 APFloat &RHS_i = RHS.getComplexFloatImag();
2466 APFloat &Res_r = Result.getComplexFloatReal();
2467 APFloat &Res_i = Result.getComplexFloatImag();
2468
2469 APFloat Den = RHS_r;
2470 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2471 APFloat Tmp = RHS_i;
2472 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2473 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2474
2475 Res_r = LHS_r;
2476 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2477 Tmp = LHS_i;
2478 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2479 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2480 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2481
2482 Res_i = LHS_i;
2483 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2484 Tmp = LHS_r;
2485 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2486 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2487 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2488 } else {
2489 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2490 // FIXME: what about diagnostics?
2491 return false;
2492 }
2493 ComplexValue LHS = Result;
2494 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2495 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2496 Result.getComplexIntReal() =
2497 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2498 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2499 Result.getComplexIntImag() =
2500 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2501 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2502 }
2503 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002504 }
2505
John McCallf4cf1a12010-05-07 17:22:02 +00002506 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002507}
2508
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002509bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2510 // Get the operand value into 'Result'.
2511 if (!Visit(E->getSubExpr()))
2512 return false;
2513
2514 switch (E->getOpcode()) {
2515 default:
2516 // FIXME: what about diagnostics?
2517 return false;
2518 case UO_Extension:
2519 return true;
2520 case UO_Plus:
2521 // The result is always just the subexpr.
2522 return true;
2523 case UO_Minus:
2524 if (Result.isComplexFloat()) {
2525 Result.getComplexFloatReal().changeSign();
2526 Result.getComplexFloatImag().changeSign();
2527 }
2528 else {
2529 Result.getComplexIntReal() = -Result.getComplexIntReal();
2530 Result.getComplexIntImag() = -Result.getComplexIntImag();
2531 }
2532 return true;
2533 case UO_Not:
2534 if (Result.isComplexFloat())
2535 Result.getComplexFloatImag().changeSign();
2536 else
2537 Result.getComplexIntImag() = -Result.getComplexIntImag();
2538 return true;
2539 }
2540}
2541
John McCall56ca35d2011-02-17 10:25:35 +00002542bool ComplexExprEvaluator::
2543VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
2544 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2545 if (opaque.hasError()) return false;
2546
2547 bool cond;
2548 if (!HandleConversionToBool(e->getCond(), cond, Info))
2549 return false;
2550
2551 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2552}
2553
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002554bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2555 bool Cond;
2556 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2557 return false;
2558
2559 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2560}
2561
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002562//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002563// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002564//===----------------------------------------------------------------------===//
2565
John McCall56ca35d2011-02-17 10:25:35 +00002566static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002567 if (E->getType()->isVectorType()) {
2568 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002569 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002570 } else if (E->getType()->isIntegerType()) {
2571 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002572 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002573 if (Info.EvalResult.Val.isLValue() &&
2574 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002575 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002576 } else if (E->getType()->hasPointerRepresentation()) {
2577 LValue LV;
2578 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002579 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002580 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002581 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002582 LV.moveInto(Info.EvalResult.Val);
2583 } else if (E->getType()->isRealFloatingType()) {
2584 llvm::APFloat F(0.0);
2585 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002586 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002587
John McCallefdb83e2010-05-07 21:00:08 +00002588 Info.EvalResult.Val = APValue(F);
2589 } else if (E->getType()->isAnyComplexType()) {
2590 ComplexValue C;
2591 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002592 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002593 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002594 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002595 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002596
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002597 return true;
2598}
2599
John McCall56ca35d2011-02-17 10:25:35 +00002600/// Evaluate - Return true if this is a constant which we can fold using
2601/// any crazy technique (that has nothing to do with language standards) that
2602/// we want to. If this function returns true, it returns the folded constant
2603/// in Result.
2604bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2605 EvalInfo Info(Ctx, Result);
2606 return ::Evaluate(Info, this);
2607}
2608
Jay Foad4ba2a172011-01-12 09:06:06 +00002609bool Expr::EvaluateAsBooleanCondition(bool &Result,
2610 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002611 EvalResult Scratch;
2612 EvalInfo Info(Ctx, Scratch);
2613
2614 return HandleConversionToBool(this, Result, Info);
2615}
2616
Jay Foad4ba2a172011-01-12 09:06:06 +00002617bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002618 EvalInfo Info(Ctx, Result);
2619
John McCallefdb83e2010-05-07 21:00:08 +00002620 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002621 if (EvaluateLValue(this, LV, Info) &&
2622 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002623 IsGlobalLValue(LV.Base)) {
2624 LV.moveInto(Result.Val);
2625 return true;
2626 }
2627 return false;
2628}
2629
Jay Foad4ba2a172011-01-12 09:06:06 +00002630bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2631 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002632 EvalInfo Info(Ctx, Result);
2633
2634 LValue LV;
2635 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002636 LV.moveInto(Result.Val);
2637 return true;
2638 }
2639 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002640}
2641
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002642/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002643/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002644bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002645 EvalResult Result;
2646 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002647}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002648
Jay Foad4ba2a172011-01-12 09:06:06 +00002649bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002650 Expr::EvalResult Result;
2651 EvalInfo Info(Ctx, Result);
2652 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2653}
2654
Jay Foad4ba2a172011-01-12 09:06:06 +00002655APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002656 EvalResult EvalResult;
2657 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002658 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002659 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002660 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002661
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002662 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002663}
John McCalld905f5a2010-05-07 05:32:02 +00002664
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002665 bool Expr::EvalResult::isGlobalLValue() const {
2666 assert(Val.isLValue());
2667 return IsGlobalLValue(Val.getLValueBase());
2668 }
2669
2670
John McCalld905f5a2010-05-07 05:32:02 +00002671/// isIntegerConstantExpr - this recursive routine will test if an expression is
2672/// an integer constant expression.
2673
2674/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2675/// comma, etc
2676///
2677/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2678/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2679/// cast+dereference.
2680
2681// CheckICE - This function does the fundamental ICE checking: the returned
2682// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2683// Note that to reduce code duplication, this helper does no evaluation
2684// itself; the caller checks whether the expression is evaluatable, and
2685// in the rare cases where CheckICE actually cares about the evaluated
2686// value, it calls into Evalute.
2687//
2688// Meanings of Val:
2689// 0: This expression is an ICE if it can be evaluated by Evaluate.
2690// 1: This expression is not an ICE, but if it isn't evaluated, it's
2691// a legal subexpression for an ICE. This return value is used to handle
2692// the comma operator in C99 mode.
2693// 2: This expression is not an ICE, and is not a legal subexpression for one.
2694
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002695namespace {
2696
John McCalld905f5a2010-05-07 05:32:02 +00002697struct ICEDiag {
2698 unsigned Val;
2699 SourceLocation Loc;
2700
2701 public:
2702 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2703 ICEDiag() : Val(0) {}
2704};
2705
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002706}
2707
2708static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002709
2710static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2711 Expr::EvalResult EVResult;
2712 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2713 !EVResult.Val.isInt()) {
2714 return ICEDiag(2, E->getLocStart());
2715 }
2716 return NoDiag();
2717}
2718
2719static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2720 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002721 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002722 return ICEDiag(2, E->getLocStart());
2723 }
2724
2725 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002726#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002727#define STMT(Node, Base) case Expr::Node##Class:
2728#define EXPR(Node, Base)
2729#include "clang/AST/StmtNodes.inc"
2730 case Expr::PredefinedExprClass:
2731 case Expr::FloatingLiteralClass:
2732 case Expr::ImaginaryLiteralClass:
2733 case Expr::StringLiteralClass:
2734 case Expr::ArraySubscriptExprClass:
2735 case Expr::MemberExprClass:
2736 case Expr::CompoundAssignOperatorClass:
2737 case Expr::CompoundLiteralExprClass:
2738 case Expr::ExtVectorElementExprClass:
2739 case Expr::InitListExprClass:
2740 case Expr::DesignatedInitExprClass:
2741 case Expr::ImplicitValueInitExprClass:
2742 case Expr::ParenListExprClass:
2743 case Expr::VAArgExprClass:
2744 case Expr::AddrLabelExprClass:
2745 case Expr::StmtExprClass:
2746 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002747 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002748 case Expr::CXXDynamicCastExprClass:
2749 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002750 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002751 case Expr::CXXNullPtrLiteralExprClass:
2752 case Expr::CXXThisExprClass:
2753 case Expr::CXXThrowExprClass:
2754 case Expr::CXXNewExprClass:
2755 case Expr::CXXDeleteExprClass:
2756 case Expr::CXXPseudoDestructorExprClass:
2757 case Expr::UnresolvedLookupExprClass:
2758 case Expr::DependentScopeDeclRefExprClass:
2759 case Expr::CXXConstructExprClass:
2760 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002761 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002762 case Expr::CXXTemporaryObjectExprClass:
2763 case Expr::CXXUnresolvedConstructExprClass:
2764 case Expr::CXXDependentScopeMemberExprClass:
2765 case Expr::UnresolvedMemberExprClass:
2766 case Expr::ObjCStringLiteralClass:
2767 case Expr::ObjCEncodeExprClass:
2768 case Expr::ObjCMessageExprClass:
2769 case Expr::ObjCSelectorExprClass:
2770 case Expr::ObjCProtocolExprClass:
2771 case Expr::ObjCIvarRefExprClass:
2772 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002773 case Expr::ObjCIsaExprClass:
2774 case Expr::ShuffleVectorExprClass:
2775 case Expr::BlockExprClass:
2776 case Expr::BlockDeclRefExprClass:
2777 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002778 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002779 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002780 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002781 return ICEDiag(2, E->getLocStart());
2782
Douglas Gregoree8aff02011-01-04 17:33:58 +00002783 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002784 case Expr::GNUNullExprClass:
2785 // GCC considers the GNU __null value to be an integral constant expression.
2786 return NoDiag();
2787
2788 case Expr::ParenExprClass:
2789 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
2790 case Expr::IntegerLiteralClass:
2791 case Expr::CharacterLiteralClass:
2792 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002793 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002794 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002795 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002796 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002797 return NoDiag();
2798 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002799 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002800 const CallExpr *CE = cast<CallExpr>(E);
2801 if (CE->isBuiltinCall(Ctx))
2802 return CheckEvalInICE(E, Ctx);
2803 return ICEDiag(2, E->getLocStart());
2804 }
2805 case Expr::DeclRefExprClass:
2806 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2807 return NoDiag();
2808 if (Ctx.getLangOptions().CPlusPlus &&
2809 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2810 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2811
2812 // Parameter variables are never constants. Without this check,
2813 // getAnyInitializer() can find a default argument, which leads
2814 // to chaos.
2815 if (isa<ParmVarDecl>(D))
2816 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2817
2818 // C++ 7.1.5.1p2
2819 // A variable of non-volatile const-qualified integral or enumeration
2820 // type initialized by an ICE can be used in ICEs.
2821 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2822 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2823 if (Quals.hasVolatile() || !Quals.hasConst())
2824 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2825
2826 // Look for a declaration of this variable that has an initializer.
2827 const VarDecl *ID = 0;
2828 const Expr *Init = Dcl->getAnyInitializer(ID);
2829 if (Init) {
2830 if (ID->isInitKnownICE()) {
2831 // We have already checked whether this subexpression is an
2832 // integral constant expression.
2833 if (ID->isInitICE())
2834 return NoDiag();
2835 else
2836 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2837 }
2838
2839 // It's an ICE whether or not the definition we found is
2840 // out-of-line. See DR 721 and the discussion in Clang PR
2841 // 6206 for details.
2842
2843 if (Dcl->isCheckingICE()) {
2844 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2845 }
2846
2847 Dcl->setCheckingICE();
2848 ICEDiag Result = CheckICE(Init, Ctx);
2849 // Cache the result of the ICE test.
2850 Dcl->setInitKnownICE(Result.Val == 0);
2851 return Result;
2852 }
2853 }
2854 }
2855 return ICEDiag(2, E->getLocStart());
2856 case Expr::UnaryOperatorClass: {
2857 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2858 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002859 case UO_PostInc:
2860 case UO_PostDec:
2861 case UO_PreInc:
2862 case UO_PreDec:
2863 case UO_AddrOf:
2864 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002865 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002866 case UO_Extension:
2867 case UO_LNot:
2868 case UO_Plus:
2869 case UO_Minus:
2870 case UO_Not:
2871 case UO_Real:
2872 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002873 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002874 }
2875
2876 // OffsetOf falls through here.
2877 }
2878 case Expr::OffsetOfExprClass: {
2879 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2880 // Evaluate matches the proposed gcc behavior for cases like
2881 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2882 // compliance: we should warn earlier for offsetof expressions with
2883 // array subscripts that aren't ICEs, and if the array subscripts
2884 // are ICEs, the value of the offsetof must be an integer constant.
2885 return CheckEvalInICE(E, Ctx);
2886 }
2887 case Expr::SizeOfAlignOfExprClass: {
2888 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(E);
2889 if (Exp->isSizeOf() && Exp->getTypeOfArgument()->isVariableArrayType())
2890 return ICEDiag(2, E->getLocStart());
2891 return NoDiag();
2892 }
2893 case Expr::BinaryOperatorClass: {
2894 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2895 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002896 case BO_PtrMemD:
2897 case BO_PtrMemI:
2898 case BO_Assign:
2899 case BO_MulAssign:
2900 case BO_DivAssign:
2901 case BO_RemAssign:
2902 case BO_AddAssign:
2903 case BO_SubAssign:
2904 case BO_ShlAssign:
2905 case BO_ShrAssign:
2906 case BO_AndAssign:
2907 case BO_XorAssign:
2908 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002909 return ICEDiag(2, E->getLocStart());
2910
John McCall2de56d12010-08-25 11:45:40 +00002911 case BO_Mul:
2912 case BO_Div:
2913 case BO_Rem:
2914 case BO_Add:
2915 case BO_Sub:
2916 case BO_Shl:
2917 case BO_Shr:
2918 case BO_LT:
2919 case BO_GT:
2920 case BO_LE:
2921 case BO_GE:
2922 case BO_EQ:
2923 case BO_NE:
2924 case BO_And:
2925 case BO_Xor:
2926 case BO_Or:
2927 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002928 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2929 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002930 if (Exp->getOpcode() == BO_Div ||
2931 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002932 // Evaluate gives an error for undefined Div/Rem, so make sure
2933 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00002934 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00002935 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2936 if (REval == 0)
2937 return ICEDiag(1, E->getLocStart());
2938 if (REval.isSigned() && REval.isAllOnesValue()) {
2939 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2940 if (LEval.isMinSignedValue())
2941 return ICEDiag(1, E->getLocStart());
2942 }
2943 }
2944 }
John McCall2de56d12010-08-25 11:45:40 +00002945 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002946 if (Ctx.getLangOptions().C99) {
2947 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2948 // if it isn't evaluated.
2949 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2950 return ICEDiag(1, E->getLocStart());
2951 } else {
2952 // In both C89 and C++, commas in ICEs are illegal.
2953 return ICEDiag(2, E->getLocStart());
2954 }
2955 }
2956 if (LHSResult.Val >= RHSResult.Val)
2957 return LHSResult;
2958 return RHSResult;
2959 }
John McCall2de56d12010-08-25 11:45:40 +00002960 case BO_LAnd:
2961 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002962 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2963 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
2964 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
2965 // Rare case where the RHS has a comma "side-effect"; we need
2966 // to actually check the condition to see whether the side
2967 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00002968 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00002969 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
2970 return RHSResult;
2971 return NoDiag();
2972 }
2973
2974 if (LHSResult.Val >= RHSResult.Val)
2975 return LHSResult;
2976 return RHSResult;
2977 }
2978 }
2979 }
2980 case Expr::ImplicitCastExprClass:
2981 case Expr::CStyleCastExprClass:
2982 case Expr::CXXFunctionalCastExprClass:
2983 case Expr::CXXStaticCastExprClass:
2984 case Expr::CXXReinterpretCastExprClass:
2985 case Expr::CXXConstCastExprClass: {
2986 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002987 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00002988 return CheckICE(SubExpr, Ctx);
2989 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
2990 return NoDiag();
2991 return ICEDiag(2, E->getLocStart());
2992 }
John McCall56ca35d2011-02-17 10:25:35 +00002993 case Expr::BinaryConditionalOperatorClass: {
2994 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
2995 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
2996 if (CommonResult.Val == 2) return CommonResult;
2997 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
2998 if (FalseResult.Val == 2) return FalseResult;
2999 if (CommonResult.Val == 1) return CommonResult;
3000 if (FalseResult.Val == 1 &&
3001 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3002 return FalseResult;
3003 }
John McCalld905f5a2010-05-07 05:32:02 +00003004 case Expr::ConditionalOperatorClass: {
3005 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3006 // If the condition (ignoring parens) is a __builtin_constant_p call,
3007 // then only the true side is actually considered in an integer constant
3008 // expression, and it is fully evaluated. This is an important GNU
3009 // extension. See GCC PR38377 for discussion.
3010 if (const CallExpr *CallCE
3011 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3012 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3013 Expr::EvalResult EVResult;
3014 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3015 !EVResult.Val.isInt()) {
3016 return ICEDiag(2, E->getLocStart());
3017 }
3018 return NoDiag();
3019 }
3020 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
3021 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3022 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3023 if (CondResult.Val == 2)
3024 return CondResult;
3025 if (TrueResult.Val == 2)
3026 return TrueResult;
3027 if (FalseResult.Val == 2)
3028 return FalseResult;
3029 if (CondResult.Val == 1)
3030 return CondResult;
3031 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3032 return NoDiag();
3033 // Rare case where the diagnostics depend on which side is evaluated
3034 // Note that if we get here, CondResult is 0, and at least one of
3035 // TrueResult and FalseResult is non-zero.
3036 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3037 return FalseResult;
3038 }
3039 return TrueResult;
3040 }
3041 case Expr::CXXDefaultArgExprClass:
3042 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3043 case Expr::ChooseExprClass: {
3044 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3045 }
3046 }
3047
3048 // Silence a GCC warning
3049 return ICEDiag(2, E->getLocStart());
3050}
3051
3052bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3053 SourceLocation *Loc, bool isEvaluated) const {
3054 ICEDiag d = CheckICE(this, Ctx);
3055 if (d.Val != 0) {
3056 if (Loc) *Loc = d.Loc;
3057 return false;
3058 }
3059 EvalResult EvalResult;
3060 if (!Evaluate(EvalResult, Ctx))
3061 llvm_unreachable("ICE cannot be evaluated!");
3062 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3063 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3064 Result = EvalResult.Val.getInt();
3065 return true;
3066}