blob: e738f0dc908c75c61c9ddb51644cf36c30a80209 [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>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 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()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000277 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
278 return Visit(E->getResultExpr());
279 }
Mike Stumpc4c90452009-10-27 22:09:17 +0000280 bool VisitDeclRefExpr(DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
285 // We don't want to evaluate BlockExprs multiple times, as they generate
286 // a ton of code.
287 bool VisitBlockExpr(BlockExpr *E) { return true; }
288 bool VisitPredefinedExpr(PredefinedExpr *E) { return false; }
289 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E)
290 { return Visit(E->getInitializer()); }
291 bool VisitMemberExpr(MemberExpr *E) { return Visit(E->getBase()); }
292 bool VisitIntegerLiteral(IntegerLiteral *E) { return false; }
293 bool VisitFloatingLiteral(FloatingLiteral *E) { return false; }
294 bool VisitStringLiteral(StringLiteral *E) { return false; }
295 bool VisitCharacterLiteral(CharacterLiteral *E) { return false; }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000296 bool VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E)
297 { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000298 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000299 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000300 bool VisitChooseExpr(ChooseExpr *E)
301 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
302 bool VisitCastExpr(CastExpr *E) { return Visit(E->getSubExpr()); }
303 bool VisitBinAssign(BinaryOperator *E) { return true; }
Mike Stump3f0147e2009-10-29 23:34:20 +0000304 bool VisitCompoundAssignOperator(BinaryOperator *E) { return true; }
Mike Stump980ca222009-10-29 20:48:09 +0000305 bool VisitBinaryOperator(BinaryOperator *E)
306 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Mike Stumpc4c90452009-10-27 22:09:17 +0000307 bool VisitUnaryPreInc(UnaryOperator *E) { return true; }
308 bool VisitUnaryPostInc(UnaryOperator *E) { return true; }
309 bool VisitUnaryPreDec(UnaryOperator *E) { return true; }
310 bool VisitUnaryPostDec(UnaryOperator *E) { return true; }
311 bool VisitUnaryDeref(UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000312 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000313 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000314 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000315 }
316 bool VisitUnaryOperator(UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000317
318 // Has side effects if any element does.
319 bool VisitInitListExpr(InitListExpr *E) {
320 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
321 if (Visit(E->getInit(i))) return true;
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000322 if (Expr *filler = E->getArrayFiller())
323 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000324 return false;
325 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000326
327 bool VisitSizeOfPackExpr(SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000328};
329
John McCall56ca35d2011-02-17 10:25:35 +0000330class OpaqueValueEvaluation {
331 EvalInfo &info;
332 OpaqueValueExpr *opaqueValue;
333
334public:
335 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
336 Expr *value)
337 : info(info), opaqueValue(opaqueValue) {
338
339 // If evaluation fails, fail immediately.
340 if (!Evaluate(info, value)) {
341 this->opaqueValue = 0;
342 return;
343 }
344 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
345 }
346
347 bool hasError() const { return opaqueValue == 0; }
348
349 ~OpaqueValueEvaluation() {
350 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
351 }
352};
353
Mike Stumpc4c90452009-10-27 22:09:17 +0000354} // end anonymous namespace
355
Eli Friedman4efaa272008-11-12 09:44:48 +0000356//===----------------------------------------------------------------------===//
357// LValue Evaluation
358//===----------------------------------------------------------------------===//
359namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000360class LValueExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000361 : public StmtVisitor<LValueExprEvaluator, bool> {
Eli Friedman4efaa272008-11-12 09:44:48 +0000362 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000363 LValue &Result;
364
365 bool Success(Expr *E) {
366 Result.Base = E;
367 Result.Offset = CharUnits::Zero();
368 return true;
369 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000370public:
Mike Stump1eb44332009-09-09 15:08:12 +0000371
John McCallefdb83e2010-05-07 21:00:08 +0000372 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
373 Info(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000374
John McCallefdb83e2010-05-07 21:00:08 +0000375 bool VisitStmt(Stmt *S) {
376 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000377 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000378
John McCallefdb83e2010-05-07 21:00:08 +0000379 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000380 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
381 return Visit(E->getResultExpr());
382 }
John McCallefdb83e2010-05-07 21:00:08 +0000383 bool VisitDeclRefExpr(DeclRefExpr *E);
384 bool VisitPredefinedExpr(PredefinedExpr *E) { return Success(E); }
385 bool VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
386 bool VisitMemberExpr(MemberExpr *E);
387 bool VisitStringLiteral(StringLiteral *E) { return Success(E); }
388 bool VisitObjCEncodeExpr(ObjCEncodeExpr *E) { return Success(E); }
389 bool VisitArraySubscriptExpr(ArraySubscriptExpr *E);
390 bool VisitUnaryDeref(UnaryOperator *E);
391 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000392 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000393 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000394 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Anders Carlsson26bc2202009-10-03 16:30:22 +0000395
John McCallefdb83e2010-05-07 21:00:08 +0000396 bool VisitCastExpr(CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000397 switch (E->getCastKind()) {
398 default:
John McCallefdb83e2010-05-07 21:00:08 +0000399 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000400
John McCall2de56d12010-08-25 11:45:40 +0000401 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000402 return Visit(E->getSubExpr());
403 }
404 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000405 // FIXME: Missing: __real__, __imag__
Eli Friedman4efaa272008-11-12 09:44:48 +0000406};
407} // end anonymous namespace
408
John McCallefdb83e2010-05-07 21:00:08 +0000409static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
410 return LValueExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Eli Friedman4efaa272008-11-12 09:44:48 +0000411}
412
John McCallefdb83e2010-05-07 21:00:08 +0000413bool LValueExprEvaluator::VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000414 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000415 return Success(E);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000416 } else if (VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
417 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000418 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000419 // Reference parameters can refer to anything even if they have an
420 // "initializer" in the form of a default argument.
421 if (isa<ParmVarDecl>(VD))
422 return false;
Eli Friedmand933a012009-08-29 19:09:59 +0000423 // FIXME: Check whether VD might be overridden!
Sebastian Redl31310a22010-02-01 20:16:42 +0000424 if (const Expr *Init = VD->getAnyInitializer())
Douglas Gregorcf3293e2009-11-01 20:32:48 +0000425 return Visit(const_cast<Expr *>(Init));
Eli Friedman50c39ea2009-05-27 06:04:58 +0000426 }
427
John McCallefdb83e2010-05-07 21:00:08 +0000428 return false;
Anders Carlsson35873c42008-11-24 04:41:22 +0000429}
430
John McCallefdb83e2010-05-07 21:00:08 +0000431bool LValueExprEvaluator::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000432 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000433}
434
John McCallefdb83e2010-05-07 21:00:08 +0000435bool LValueExprEvaluator::VisitMemberExpr(MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000436 QualType Ty;
437 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000438 if (!EvaluatePointer(E->getBase(), Result, Info))
439 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000440 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000441 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000442 if (!Visit(E->getBase()))
443 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000444 Ty = E->getBase()->getType();
445 }
446
Ted Kremenek6217b802009-07-29 21:53:49 +0000447 RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000448 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000449
450 FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
451 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000452 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000453
454 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000455 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000456
Eli Friedman4efaa272008-11-12 09:44:48 +0000457 // FIXME: This is linear time.
Douglas Gregor44b43212008-12-11 16:49:14 +0000458 unsigned i = 0;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000459 for (RecordDecl::field_iterator Field = RD->field_begin(),
460 FieldEnd = RD->field_end();
Douglas Gregor44b43212008-12-11 16:49:14 +0000461 Field != FieldEnd; (void)++Field, ++i) {
462 if (*Field == FD)
Eli Friedman4efaa272008-11-12 09:44:48 +0000463 break;
464 }
465
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000466 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000467 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000468}
469
John McCallefdb83e2010-05-07 21:00:08 +0000470bool LValueExprEvaluator::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000471 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000472 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000473
Anders Carlsson3068d112008-11-16 19:01:22 +0000474 APSInt Index;
475 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000476 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000477
Ken Dyck199c3d62010-01-11 17:06:35 +0000478 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000479 Result.Offset += Index.getSExtValue() * ElementSize;
480 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000481}
Eli Friedman4efaa272008-11-12 09:44:48 +0000482
John McCallefdb83e2010-05-07 21:00:08 +0000483bool LValueExprEvaluator::VisitUnaryDeref(UnaryOperator *E) {
484 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000485}
486
Eli Friedman4efaa272008-11-12 09:44:48 +0000487//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000488// Pointer Evaluation
489//===----------------------------------------------------------------------===//
490
Anders Carlssonc754aa62008-07-08 05:13:58 +0000491namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000492class PointerExprEvaluator
John McCallefdb83e2010-05-07 21:00:08 +0000493 : public StmtVisitor<PointerExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000494 EvalInfo &Info;
John McCallefdb83e2010-05-07 21:00:08 +0000495 LValue &Result;
496
497 bool Success(Expr *E) {
498 Result.Base = E;
499 Result.Offset = CharUnits::Zero();
500 return true;
501 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000502public:
Mike Stump1eb44332009-09-09 15:08:12 +0000503
John McCallefdb83e2010-05-07 21:00:08 +0000504 PointerExprEvaluator(EvalInfo &info, LValue &Result)
505 : Info(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000506
John McCallefdb83e2010-05-07 21:00:08 +0000507 bool VisitStmt(Stmt *S) {
508 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000509 }
510
John McCallefdb83e2010-05-07 21:00:08 +0000511 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000512 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
513 return Visit(E->getResultExpr());
514 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000515
John McCallefdb83e2010-05-07 21:00:08 +0000516 bool VisitBinaryOperator(const BinaryOperator *E);
517 bool VisitCastExpr(CastExpr* E);
518 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedman2217c872009-02-22 11:46:18 +0000519 { return Visit(E->getSubExpr()); }
John McCallefdb83e2010-05-07 21:00:08 +0000520 bool VisitUnaryAddrOf(const UnaryOperator *E);
521 bool VisitObjCStringLiteral(ObjCStringLiteral *E)
522 { return Success(E); }
523 bool VisitAddrLabelExpr(AddrLabelExpr *E)
524 { return Success(E); }
525 bool VisitCallExpr(CallExpr *E);
526 bool VisitBlockExpr(BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000527 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000528 return Success(E);
529 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000530 }
John McCallefdb83e2010-05-07 21:00:08 +0000531 bool VisitImplicitValueInitExpr(ImplicitValueInitExpr *E)
532 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000533 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
John McCallefdb83e2010-05-07 21:00:08 +0000534 bool VisitConditionalOperator(ConditionalOperator *E);
535 bool VisitChooseExpr(ChooseExpr *E)
Sebastian Redl6e8ed162009-05-10 18:38:11 +0000536 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallefdb83e2010-05-07 21:00:08 +0000537 bool VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E)
538 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000539
540 bool VisitOpaqueValueExpr(OpaqueValueExpr *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000541 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000542};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000543} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000544
John McCallefdb83e2010-05-07 21:00:08 +0000545static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000546 assert(E->getType()->hasPointerRepresentation());
John McCallefdb83e2010-05-07 21:00:08 +0000547 return PointerExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000548}
549
John McCallefdb83e2010-05-07 21:00:08 +0000550bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000551 if (E->getOpcode() != BO_Add &&
552 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000553 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000554
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000555 const Expr *PExp = E->getLHS();
556 const Expr *IExp = E->getRHS();
557 if (IExp->getType()->isPointerType())
558 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000559
John McCallefdb83e2010-05-07 21:00:08 +0000560 if (!EvaluatePointer(PExp, Result, Info))
561 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000562
John McCallefdb83e2010-05-07 21:00:08 +0000563 llvm::APSInt Offset;
564 if (!EvaluateInteger(IExp, Offset, Info))
565 return false;
566 int64_t AdditionalOffset
567 = Offset.isSigned() ? Offset.getSExtValue()
568 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000569
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000570 // Compute the new offset in the appropriate width.
571
572 QualType PointeeType =
573 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000574 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000575
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000576 // Explicitly handle GNU void* and function pointer arithmetic extensions.
577 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000578 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000579 else
John McCallefdb83e2010-05-07 21:00:08 +0000580 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000581
John McCall2de56d12010-08-25 11:45:40 +0000582 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000583 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000584 else
John McCallefdb83e2010-05-07 21:00:08 +0000585 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000586
John McCallefdb83e2010-05-07 21:00:08 +0000587 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000588}
Eli Friedman4efaa272008-11-12 09:44:48 +0000589
John McCallefdb83e2010-05-07 21:00:08 +0000590bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
591 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000592}
Mike Stump1eb44332009-09-09 15:08:12 +0000593
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000594
John McCallefdb83e2010-05-07 21:00:08 +0000595bool PointerExprEvaluator::VisitCastExpr(CastExpr* E) {
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000596 Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000597
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000598 switch (E->getCastKind()) {
599 default:
600 break;
601
John McCall2de56d12010-08-25 11:45:40 +0000602 case CK_NoOp:
603 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000604 case CK_AnyPointerToObjCPointerCast:
605 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000606 return Visit(SubExpr);
607
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000608 case CK_DerivedToBase:
609 case CK_UncheckedDerivedToBase: {
610 LValue BaseLV;
611 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
612 return false;
613
614 // Now figure out the necessary offset to add to the baseLV to get from
615 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000616 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000617
618 QualType Ty = E->getSubExpr()->getType();
619 const CXXRecordDecl *DerivedDecl =
620 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
621
622 for (CastExpr::path_const_iterator PathI = E->path_begin(),
623 PathE = E->path_end(); PathI != PathE; ++PathI) {
624 const CXXBaseSpecifier *Base = *PathI;
625
626 // FIXME: If the base is virtual, we'd need to determine the type of the
627 // most derived class and we don't support that right now.
628 if (Base->isVirtual())
629 return false;
630
631 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
632 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
633
Ken Dyck7c7f8202011-01-26 02:17:08 +0000634 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000635 DerivedDecl = BaseDecl;
636 }
637
638 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000639 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000640 return true;
641 }
642
John McCall404cd162010-11-13 01:35:44 +0000643 case CK_NullToPointer: {
644 Result.Base = 0;
645 Result.Offset = CharUnits::Zero();
646 return true;
647 }
648
John McCall2de56d12010-08-25 11:45:40 +0000649 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000650 APValue Value;
651 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000652 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000653
John McCallefdb83e2010-05-07 21:00:08 +0000654 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000655 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000656 Result.Base = 0;
657 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
658 return true;
659 } else {
660 // Cast is of an lvalue, no need to change value.
661 Result.Base = Value.getLValueBase();
662 Result.Offset = Value.getLValueOffset();
663 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000664 }
665 }
John McCall2de56d12010-08-25 11:45:40 +0000666 case CK_ArrayToPointerDecay:
667 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000668 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000669 }
670
John McCallefdb83e2010-05-07 21:00:08 +0000671 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000672}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000673
John McCallefdb83e2010-05-07 21:00:08 +0000674bool PointerExprEvaluator::VisitCallExpr(CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000675 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000676 Builtin::BI__builtin___CFStringMakeConstantString ||
677 E->isBuiltinCall(Info.Ctx) ==
678 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000679 return Success(E);
680 return false;
Eli Friedman3941b182009-01-25 01:54:01 +0000681}
682
John McCall56ca35d2011-02-17 10:25:35 +0000683bool PointerExprEvaluator::VisitOpaqueValueExpr(OpaqueValueExpr *e) {
684 const APValue *value = Info.getOpaqueValue(e);
685 if (!value)
686 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
687 Result.setFrom(*value);
688 return true;
689}
690
691bool PointerExprEvaluator::
692VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
693 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
694 if (opaque.hasError()) return false;
695
696 bool cond;
697 if (!HandleConversionToBool(e->getCond(), cond, Info))
698 return false;
699
700 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
701}
702
John McCallefdb83e2010-05-07 21:00:08 +0000703bool PointerExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000704 bool BoolResult;
705 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000706 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000707
708 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
John McCallefdb83e2010-05-07 21:00:08 +0000709 return Visit(EvalExpr);
Eli Friedman4efaa272008-11-12 09:44:48 +0000710}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000711
712//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000713// Vector Evaluation
714//===----------------------------------------------------------------------===//
715
716namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000717 class VectorExprEvaluator
Nate Begeman59b5da62009-01-18 03:20:47 +0000718 : public StmtVisitor<VectorExprEvaluator, APValue> {
719 EvalInfo &Info;
Eli Friedman91110ee2009-02-23 04:23:56 +0000720 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000721 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Nate Begeman59b5da62009-01-18 03:20:47 +0000723 VectorExprEvaluator(EvalInfo &info) : Info(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000724
Nate Begeman59b5da62009-01-18 03:20:47 +0000725 APValue VisitStmt(Stmt *S) {
726 return APValue();
727 }
Mike Stump1eb44332009-09-09 15:08:12 +0000728
Eli Friedman91110ee2009-02-23 04:23:56 +0000729 APValue VisitParenExpr(ParenExpr *E)
730 { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000731 APValue VisitGenericSelectionExpr(GenericSelectionExpr *E)
732 { return Visit(E->getResultExpr()); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000733 APValue VisitUnaryExtension(const UnaryOperator *E)
734 { return Visit(E->getSubExpr()); }
735 APValue VisitUnaryPlus(const UnaryOperator *E)
736 { return Visit(E->getSubExpr()); }
737 APValue VisitUnaryReal(const UnaryOperator *E)
738 { return Visit(E->getSubExpr()); }
739 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
740 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000741 APValue VisitCastExpr(const CastExpr* E);
742 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
743 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000744 APValue VisitConditionalOperator(const ConditionalOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000745 APValue VisitChooseExpr(const ChooseExpr *E)
746 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Eli Friedman91110ee2009-02-23 04:23:56 +0000747 APValue VisitUnaryImag(const UnaryOperator *E);
748 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000749 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000750 // shufflevector, ExtVectorElementExpr
751 // (Note that these require implementing conversions
752 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000753 };
754} // end anonymous namespace
755
756static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
757 if (!E->getType()->isVectorType())
758 return false;
759 Result = VectorExprEvaluator(Info).Visit(const_cast<Expr*>(E));
760 return !Result.isUninit();
761}
762
763APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000764 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000765 QualType EltTy = VTy->getElementType();
766 unsigned NElts = VTy->getNumElements();
767 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000768
Nate Begeman59b5da62009-01-18 03:20:47 +0000769 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000770 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000771
Eli Friedman46a52322011-03-25 00:43:55 +0000772 switch (E->getCastKind()) {
773 case CK_VectorSplat: {
774 APValue Result = APValue();
775 if (SETy->isIntegerType()) {
776 APSInt IntResult;
777 if (!EvaluateInteger(SE, IntResult, Info))
778 return APValue();
779 Result = APValue(IntResult);
780 } else if (SETy->isRealFloatingType()) {
781 APFloat F(0.0);
782 if (!EvaluateFloat(SE, F, Info))
783 return APValue();
784 Result = APValue(F);
785 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000786 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000787 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000788
789 // Splat and create vector APValue.
790 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
791 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000792 }
Eli Friedman46a52322011-03-25 00:43:55 +0000793 case CK_BitCast: {
794 if (SETy->isVectorType())
795 return Visit(const_cast<Expr*>(SE));
Nate Begemanc0b8b192009-07-01 07:50:47 +0000796
Eli Friedman46a52322011-03-25 00:43:55 +0000797 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000798 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000799
Eli Friedman46a52322011-03-25 00:43:55 +0000800 APSInt Init;
801 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000802 return APValue();
803
Eli Friedman46a52322011-03-25 00:43:55 +0000804 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
805 "Vectors must be composed of ints or floats");
806
807 llvm::SmallVector<APValue, 4> Elts;
808 for (unsigned i = 0; i != NElts; ++i) {
809 APSInt Tmp = Init.extOrTrunc(EltWidth);
810
811 if (EltTy->isIntegerType())
812 Elts.push_back(APValue(Tmp));
813 else
814 Elts.push_back(APValue(APFloat(Tmp)));
815
816 Init >>= EltWidth;
817 }
818 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000819 }
Eli Friedman46a52322011-03-25 00:43:55 +0000820 case CK_LValueToRValue:
821 case CK_NoOp:
822 return Visit(const_cast<Expr*>(SE));
823 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000824 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000825 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000826}
827
Mike Stump1eb44332009-09-09 15:08:12 +0000828APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000829VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
830 return this->Visit(const_cast<Expr*>(E->getInitializer()));
831}
832
Mike Stump1eb44332009-09-09 15:08:12 +0000833APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000834VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000835 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000836 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000837 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000838
Nate Begeman59b5da62009-01-18 03:20:47 +0000839 QualType EltTy = VT->getElementType();
840 llvm::SmallVector<APValue, 4> Elements;
841
John McCalla7d6c222010-06-11 17:54:15 +0000842 // If a vector is initialized with a single element, that value
843 // becomes every element of the vector, not just the first.
844 // This is the behavior described in the IBM AltiVec documentation.
845 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000846
847 // Handle the case where the vector is initialized by a another
848 // vector (OpenCL 6.1.6).
849 if (E->getInit(0)->getType()->isVectorType())
850 return this->Visit(const_cast<Expr*>(E->getInit(0)));
851
John McCalla7d6c222010-06-11 17:54:15 +0000852 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000853 if (EltTy->isIntegerType()) {
854 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000855 if (!EvaluateInteger(E->getInit(0), sInt, Info))
856 return APValue();
857 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000858 } else {
859 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000860 if (!EvaluateFloat(E->getInit(0), f, Info))
861 return APValue();
862 InitValue = APValue(f);
863 }
864 for (unsigned i = 0; i < NumElements; i++) {
865 Elements.push_back(InitValue);
866 }
867 } else {
868 for (unsigned i = 0; i < NumElements; i++) {
869 if (EltTy->isIntegerType()) {
870 llvm::APSInt sInt(32);
871 if (i < NumInits) {
872 if (!EvaluateInteger(E->getInit(i), sInt, Info))
873 return APValue();
874 } else {
875 sInt = Info.Ctx.MakeIntValue(0, EltTy);
876 }
877 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000878 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000879 llvm::APFloat f(0.0);
880 if (i < NumInits) {
881 if (!EvaluateFloat(E->getInit(i), f, Info))
882 return APValue();
883 } else {
884 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
885 }
886 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000887 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000888 }
889 }
890 return APValue(&Elements[0], Elements.size());
891}
892
Mike Stump1eb44332009-09-09 15:08:12 +0000893APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000894VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000895 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000896 QualType EltTy = VT->getElementType();
897 APValue ZeroElement;
898 if (EltTy->isIntegerType())
899 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
900 else
901 ZeroElement =
902 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
903
904 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
905 return APValue(&Elements[0], Elements.size());
906}
907
908APValue VectorExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
909 bool BoolResult;
910 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
911 return APValue();
912
913 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
914
915 APValue Result;
916 if (EvaluateVector(EvalExpr, Result, Info))
917 return Result;
918 return APValue();
919}
920
Eli Friedman91110ee2009-02-23 04:23:56 +0000921APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
922 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
923 Info.EvalResult.HasSideEffects = true;
924 return GetZeroVector(E->getType());
925}
926
Nate Begeman59b5da62009-01-18 03:20:47 +0000927//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000928// Integer Evaluation
929//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000930
931namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000932class IntExprEvaluator
Chris Lattnerb542afe2008-07-11 19:10:17 +0000933 : public StmtVisitor<IntExprEvaluator, bool> {
Chris Lattner87eae5e2008-07-11 22:52:41 +0000934 EvalInfo &Info;
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000935 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000936public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000937 IntExprEvaluator(EvalInfo &info, APValue &result)
Chris Lattner87eae5e2008-07-11 22:52:41 +0000938 : Info(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000939
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000940 bool Success(const llvm::APSInt &SI, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000941 assert(E->getType()->isIntegralOrEnumerationType() &&
942 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000943 assert(SI.isSigned() == E->getType()->isSignedIntegerType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000944 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000945 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000946 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000947 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000948 return true;
949 }
950
Daniel Dunbar131eb432009-02-19 09:06:44 +0000951 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000952 assert(E->getType()->isIntegralOrEnumerationType() &&
953 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000954 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000955 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000956 Result = APValue(APSInt(I));
957 Result.getInt().setIsUnsigned(E->getType()->isUnsignedIntegerType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000958 return true;
959 }
960
961 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000962 assert(E->getType()->isIntegralOrEnumerationType() &&
963 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000964 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000965 return true;
966 }
967
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000968 bool Success(CharUnits Size, const Expr *E) {
969 return Success(Size.getQuantity(), E);
970 }
971
972
Anders Carlsson82206e22008-11-30 18:14:57 +0000973 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000974 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000975 if (Info.EvalResult.Diag == 0) {
976 Info.EvalResult.DiagLoc = L;
977 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000978 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000979 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000980 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000981 }
Mike Stump1eb44332009-09-09 15:08:12 +0000982
Anders Carlssonc754aa62008-07-08 05:13:58 +0000983 //===--------------------------------------------------------------------===//
984 // Visitor Methods
985 //===--------------------------------------------------------------------===//
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chris Lattner32fea9d2008-11-12 07:43:42 +0000987 bool VisitStmt(Stmt *) {
988 assert(0 && "This should be called on integers, stmts are not integers");
989 return false;
990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Chris Lattner32fea9d2008-11-12 07:43:42 +0000992 bool VisitExpr(Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000993 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000994 }
Mike Stump1eb44332009-09-09 15:08:12 +0000995
Chris Lattnerb542afe2008-07-11 19:10:17 +0000996 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +0000997 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
998 return Visit(E->getResultExpr());
999 }
Anders Carlssonc754aa62008-07-08 05:13:58 +00001000
Chris Lattner4c4867e2008-07-12 00:38:25 +00001001 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001002 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001003 }
1004 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001005 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001006 }
Eli Friedman04309752009-11-24 05:28:59 +00001007
John McCall56ca35d2011-02-17 10:25:35 +00001008 bool VisitOpaqueValueExpr(OpaqueValueExpr *e) {
1009 const APValue *value = Info.getOpaqueValue(e);
1010 if (!value) {
1011 if (e->getSourceExpr()) return Visit(e->getSourceExpr());
1012 return Error(e->getExprLoc(), diag::note_invalid_subexpr_in_ice, e);
1013 }
1014 return Success(value->getInt(), e);
1015 }
1016
Eli Friedman04309752009-11-24 05:28:59 +00001017 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1018 bool VisitDeclRefExpr(const DeclRefExpr *E) {
1019 return CheckReferencedDecl(E, E->getDecl());
1020 }
1021 bool VisitMemberExpr(const MemberExpr *E) {
1022 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1023 // Conservatively assume a MemberExpr will have side-effects
1024 Info.EvalResult.HasSideEffects = true;
1025 return true;
1026 }
1027 return false;
1028 }
1029
Eli Friedmanc4a26382010-02-13 00:10:10 +00001030 bool VisitCallExpr(CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001031 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001032 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001033 bool VisitUnaryOperator(const UnaryOperator *E);
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001034 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001035 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001036
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001037 bool VisitCastExpr(CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001038 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001039
Anders Carlsson3068d112008-11-16 19:01:22 +00001040 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001041 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001042 }
Mike Stump1eb44332009-09-09 15:08:12 +00001043
Anders Carlsson3f704562008-12-21 22:39:40 +00001044 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001045 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001046 }
Mike Stump1eb44332009-09-09 15:08:12 +00001047
Douglas Gregored8abf12010-07-08 06:14:04 +00001048 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001049 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001050 }
1051
Eli Friedman664a1042009-02-27 04:45:43 +00001052 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1053 return Success(0, E);
1054 }
1055
Sebastian Redl64b45f72009-01-05 20:52:13 +00001056 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001057 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001058 }
1059
Francois Pichet6ad6f282010-12-07 00:08:36 +00001060 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1061 return Success(E->getValue(), E);
1062 }
1063
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001064 bool VisitChooseExpr(const ChooseExpr *E) {
1065 return Visit(E->getChosenSubExpr(Info.Ctx));
1066 }
1067
Eli Friedman722c7172009-02-28 03:59:05 +00001068 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001069 bool VisitUnaryImag(const UnaryOperator *E);
1070
Sebastian Redl295995c2010-09-10 20:55:47 +00001071 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001072 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1073
Chris Lattnerfcee0012008-07-11 21:24:13 +00001074private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001075 CharUnits GetAlignOfExpr(const Expr *E);
1076 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001077 static QualType GetObjectType(const Expr *E);
1078 bool TryEvaluateBuiltinObjectSize(CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001079 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001080};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001081} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001082
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001083static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001084 assert(E->getType()->isIntegralOrEnumerationType());
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001085 return IntExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1086}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001087
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001088static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001089 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001090
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001091 APValue Val;
1092 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1093 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001094 Result = Val.getInt();
1095 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001096}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001097
Eli Friedman04309752009-11-24 05:28:59 +00001098bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001099 // Enums are integer constant exprs.
Eli Friedman29a7f332009-12-10 22:29:29 +00001100 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D))
1101 return Success(ECD->getInitVal(), E);
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001102
1103 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001104 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001105 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1106 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001107
1108 if (isa<ParmVarDecl>(D))
1109 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1110
Eli Friedman04309752009-11-24 05:28:59 +00001111 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001112 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001113 if (APValue *V = VD->getEvaluatedValue()) {
1114 if (V->isInt())
1115 return Success(V->getInt(), E);
1116 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1117 }
1118
1119 if (VD->isEvaluatingValue())
1120 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1121
1122 VD->setEvaluatingValue();
1123
Eli Friedmana7dedf72010-09-06 00:10:32 +00001124 Expr::EvalResult EResult;
1125 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1126 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001127 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001128 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001129 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001130 return true;
1131 }
1132
Eli Friedmanc0131182009-12-03 20:31:57 +00001133 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001134 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001135 }
1136 }
1137
Chris Lattner4c4867e2008-07-12 00:38:25 +00001138 // Otherwise, random variable references are not constants.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001139 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001140}
1141
Chris Lattnera4d55d82008-10-06 06:40:35 +00001142/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1143/// as GCC.
1144static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1145 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001146 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001147 enum gcc_type_class {
1148 no_type_class = -1,
1149 void_type_class, integer_type_class, char_type_class,
1150 enumeral_type_class, boolean_type_class,
1151 pointer_type_class, reference_type_class, offset_type_class,
1152 real_type_class, complex_type_class,
1153 function_type_class, method_type_class,
1154 record_type_class, union_type_class,
1155 array_type_class, string_type_class,
1156 lang_type_class
1157 };
Mike Stump1eb44332009-09-09 15:08:12 +00001158
1159 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001160 // ideal, however it is what gcc does.
1161 if (E->getNumArgs() == 0)
1162 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001163
Chris Lattnera4d55d82008-10-06 06:40:35 +00001164 QualType ArgTy = E->getArg(0)->getType();
1165 if (ArgTy->isVoidType())
1166 return void_type_class;
1167 else if (ArgTy->isEnumeralType())
1168 return enumeral_type_class;
1169 else if (ArgTy->isBooleanType())
1170 return boolean_type_class;
1171 else if (ArgTy->isCharType())
1172 return string_type_class; // gcc doesn't appear to use char_type_class
1173 else if (ArgTy->isIntegerType())
1174 return integer_type_class;
1175 else if (ArgTy->isPointerType())
1176 return pointer_type_class;
1177 else if (ArgTy->isReferenceType())
1178 return reference_type_class;
1179 else if (ArgTy->isRealType())
1180 return real_type_class;
1181 else if (ArgTy->isComplexType())
1182 return complex_type_class;
1183 else if (ArgTy->isFunctionType())
1184 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001185 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001186 return record_type_class;
1187 else if (ArgTy->isUnionType())
1188 return union_type_class;
1189 else if (ArgTy->isArrayType())
1190 return array_type_class;
1191 else if (ArgTy->isUnionType())
1192 return union_type_class;
1193 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1194 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1195 return -1;
1196}
1197
John McCall42c8f872010-05-10 23:27:23 +00001198/// Retrieves the "underlying object type" of the given expression,
1199/// as used by __builtin_object_size.
1200QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1201 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1202 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1203 return VD->getType();
1204 } else if (isa<CompoundLiteralExpr>(E)) {
1205 return E->getType();
1206 }
1207
1208 return QualType();
1209}
1210
1211bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(CallExpr *E) {
1212 // TODO: Perhaps we should let LLVM lower this?
1213 LValue Base;
1214 if (!EvaluatePointer(E->getArg(0), Base, Info))
1215 return false;
1216
1217 // If we can prove the base is null, lower to zero now.
1218 const Expr *LVBase = Base.getLValueBase();
1219 if (!LVBase) return Success(0, E);
1220
1221 QualType T = GetObjectType(LVBase);
1222 if (T.isNull() ||
1223 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001224 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001225 T->isVariablyModifiedType() ||
1226 T->isDependentType())
1227 return false;
1228
1229 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1230 CharUnits Offset = Base.getLValueOffset();
1231
1232 if (!Offset.isNegative() && Offset <= Size)
1233 Size -= Offset;
1234 else
1235 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001236 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001237}
1238
Eli Friedmanc4a26382010-02-13 00:10:10 +00001239bool IntExprEvaluator::VisitCallExpr(CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001240 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001241 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001242 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001243
1244 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001245 if (TryEvaluateBuiltinObjectSize(E))
1246 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001247
Eric Christopherb2aaf512010-01-19 22:58:35 +00001248 // If evaluating the argument has side-effects we can't determine
1249 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001250 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001251 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001252 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001253 return Success(0, E);
1254 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001255
Mike Stump64eda9e2009-10-26 18:35:08 +00001256 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1257 }
1258
Chris Lattner019f4e82008-10-06 05:28:25 +00001259 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001260 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001261
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001262 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001263 // __builtin_constant_p always has one operand: it returns true if that
1264 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001265 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001266
1267 case Builtin::BI__builtin_eh_return_data_regno: {
1268 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1269 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1270 return Success(Operand, E);
1271 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001272
1273 case Builtin::BI__builtin_expect:
1274 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001275
1276 case Builtin::BIstrlen:
1277 case Builtin::BI__builtin_strlen:
1278 // As an extension, we support strlen() and __builtin_strlen() as constant
1279 // expressions when the argument is a string literal.
1280 if (StringLiteral *S
1281 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1282 // The string literal may have embedded null characters. Find the first
1283 // one and truncate there.
1284 llvm::StringRef Str = S->getString();
1285 llvm::StringRef::size_type Pos = Str.find(0);
1286 if (Pos != llvm::StringRef::npos)
1287 Str = Str.substr(0, Pos);
1288
1289 return Success(Str.size(), E);
1290 }
1291
1292 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001293 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001294}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001295
Chris Lattnerb542afe2008-07-11 19:10:17 +00001296bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001297 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001298 if (!Visit(E->getRHS()))
1299 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001300
Eli Friedman33ef1452009-02-26 10:19:36 +00001301 // If we can't evaluate the LHS, it might have side effects;
1302 // conservatively mark it.
1303 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1304 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001305
Anders Carlsson027f62e2008-12-01 02:07:06 +00001306 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001307 }
1308
1309 if (E->isLogicalOp()) {
1310 // These need to be handled specially because the operands aren't
1311 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001312 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001313
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001314 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001315 // We were able to evaluate the LHS, see if we can get away with not
1316 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001317 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001318 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001319
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001320 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001321 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001322 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001323 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001324 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001325 }
1326 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001327 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001328 // We can't evaluate the LHS; however, sometimes the result
1329 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001330 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1331 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001332 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001333 // must have had side effects.
1334 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001335
1336 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001337 }
1338 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001339 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001340
Eli Friedmana6afa762008-11-13 06:09:17 +00001341 return false;
1342 }
1343
Anders Carlsson286f85e2008-11-16 07:17:21 +00001344 QualType LHSTy = E->getLHS()->getType();
1345 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001346
1347 if (LHSTy->isAnyComplexType()) {
1348 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001349 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001350
1351 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1352 return false;
1353
1354 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1355 return false;
1356
1357 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001358 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001359 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001360 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001361 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1362
John McCall2de56d12010-08-25 11:45:40 +00001363 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001364 return Success((CR_r == APFloat::cmpEqual &&
1365 CR_i == APFloat::cmpEqual), E);
1366 else {
John McCall2de56d12010-08-25 11:45:40 +00001367 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001368 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001369 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001370 CR_r == APFloat::cmpLessThan ||
1371 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001372 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001373 CR_i == APFloat::cmpLessThan ||
1374 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001375 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001376 } else {
John McCall2de56d12010-08-25 11:45:40 +00001377 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001378 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1379 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1380 else {
John McCall2de56d12010-08-25 11:45:40 +00001381 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001382 "Invalid compex comparison.");
1383 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1384 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1385 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001386 }
1387 }
Mike Stump1eb44332009-09-09 15:08:12 +00001388
Anders Carlsson286f85e2008-11-16 07:17:21 +00001389 if (LHSTy->isRealFloatingType() &&
1390 RHSTy->isRealFloatingType()) {
1391 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001392
Anders Carlsson286f85e2008-11-16 07:17:21 +00001393 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1394 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001395
Anders Carlsson286f85e2008-11-16 07:17:21 +00001396 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1397 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001398
Anders Carlsson286f85e2008-11-16 07:17:21 +00001399 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001400
Anders Carlsson286f85e2008-11-16 07:17:21 +00001401 switch (E->getOpcode()) {
1402 default:
1403 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001404 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001405 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001406 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001407 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001408 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001409 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001410 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001411 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001412 E);
John McCall2de56d12010-08-25 11:45:40 +00001413 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001414 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001415 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001416 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001417 || CR == APFloat::cmpLessThan
1418 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001419 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001420 }
Mike Stump1eb44332009-09-09 15:08:12 +00001421
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001422 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001423 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001424 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001425 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1426 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001427
John McCallefdb83e2010-05-07 21:00:08 +00001428 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001429 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1430 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001431
Eli Friedman5bc86102009-06-14 02:17:33 +00001432 // Reject any bases from the normal codepath; we special-case comparisons
1433 // to null.
1434 if (LHSValue.getLValueBase()) {
1435 if (!E->isEqualityOp())
1436 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001437 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001438 return false;
1439 bool bres;
1440 if (!EvalPointerValueAsBool(LHSValue, bres))
1441 return false;
John McCall2de56d12010-08-25 11:45:40 +00001442 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001443 } else if (RHSValue.getLValueBase()) {
1444 if (!E->isEqualityOp())
1445 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001446 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001447 return false;
1448 bool bres;
1449 if (!EvalPointerValueAsBool(RHSValue, bres))
1450 return false;
John McCall2de56d12010-08-25 11:45:40 +00001451 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001452 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001453
John McCall2de56d12010-08-25 11:45:40 +00001454 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001455 QualType Type = E->getLHS()->getType();
1456 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001457
Ken Dycka7305832010-01-15 12:37:54 +00001458 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001459 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001460 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001461
Ken Dycka7305832010-01-15 12:37:54 +00001462 CharUnits Diff = LHSValue.getLValueOffset() -
1463 RHSValue.getLValueOffset();
1464 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001465 }
1466 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001467 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001468 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001469 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001470 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1471 }
1472 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001473 }
1474 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001475 if (!LHSTy->isIntegralOrEnumerationType() ||
1476 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001477 // We can't continue from here for non-integral types, and they
1478 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001479 return false;
1480 }
1481
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001482 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001483 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001484 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001485
Eli Friedman42edd0d2009-03-24 01:14:50 +00001486 APValue RHSVal;
1487 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001488 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001489
1490 // Handle cases like (unsigned long)&a + 4.
1491 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001492 CharUnits Offset = Result.getLValueOffset();
1493 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1494 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001495 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001496 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001497 else
Ken Dycka7305832010-01-15 12:37:54 +00001498 Offset -= AdditionalOffset;
1499 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001500 return true;
1501 }
1502
1503 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001504 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001505 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001506 CharUnits Offset = RHSVal.getLValueOffset();
1507 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1508 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001509 return true;
1510 }
1511
1512 // All the following cases expect both operands to be an integer
1513 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001514 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001515
Eli Friedman42edd0d2009-03-24 01:14:50 +00001516 APSInt& RHS = RHSVal.getInt();
1517
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001518 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001519 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001520 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001521 case BO_Mul: return Success(Result.getInt() * RHS, E);
1522 case BO_Add: return Success(Result.getInt() + RHS, E);
1523 case BO_Sub: return Success(Result.getInt() - RHS, E);
1524 case BO_And: return Success(Result.getInt() & RHS, E);
1525 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1526 case BO_Or: return Success(Result.getInt() | RHS, E);
1527 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001528 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001529 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001530 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001531 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001532 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001533 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001534 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001535 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001536 // During constant-folding, a negative shift is an opposite shift.
1537 if (RHS.isSigned() && RHS.isNegative()) {
1538 RHS = -RHS;
1539 goto shift_right;
1540 }
1541
1542 shift_left:
1543 unsigned SA
1544 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001545 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001546 }
John McCall2de56d12010-08-25 11:45:40 +00001547 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001548 // During constant-folding, a negative shift is an opposite shift.
1549 if (RHS.isSigned() && RHS.isNegative()) {
1550 RHS = -RHS;
1551 goto shift_left;
1552 }
1553
1554 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001555 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001556 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1557 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001558 }
Mike Stump1eb44332009-09-09 15:08:12 +00001559
John McCall2de56d12010-08-25 11:45:40 +00001560 case BO_LT: return Success(Result.getInt() < RHS, E);
1561 case BO_GT: return Success(Result.getInt() > RHS, E);
1562 case BO_LE: return Success(Result.getInt() <= RHS, E);
1563 case BO_GE: return Success(Result.getInt() >= RHS, E);
1564 case BO_EQ: return Success(Result.getInt() == RHS, E);
1565 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001566 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001567}
1568
John McCall56ca35d2011-02-17 10:25:35 +00001569bool IntExprEvaluator::
1570VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
1571 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
1572 if (opaque.hasError()) return false;
1573
1574 bool cond;
1575 if (!HandleConversionToBool(e->getCond(), cond, Info))
1576 return false;
1577
1578 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
1579}
1580
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001581bool IntExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
Nuno Lopesa25bd552008-11-16 22:06:39 +00001582 bool Cond;
1583 if (!HandleConversionToBool(E->getCond(), Cond, Info))
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001584 return false;
1585
Nuno Lopesa25bd552008-11-16 22:06:39 +00001586 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
Nuno Lopesca7c2ea2008-11-16 19:28:31 +00001587}
1588
Ken Dyck8b752f12010-01-27 17:10:57 +00001589CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001590 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1591 // the result is the size of the referenced type."
1592 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1593 // result shall be the alignment of the referenced type."
1594 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1595 T = Ref->getPointeeType();
1596
Eli Friedman2be58612009-05-30 21:09:44 +00001597 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001598 return Info.Ctx.toCharUnitsFromBits(
1599 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001600}
1601
Ken Dyck8b752f12010-01-27 17:10:57 +00001602CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001603 E = E->IgnoreParens();
1604
1605 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001606 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001607 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001608 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1609 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001610
Chris Lattneraf707ab2009-01-24 21:53:27 +00001611 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001612 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1613 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001614
Chris Lattnere9feb472009-01-24 21:09:06 +00001615 return GetAlignOfType(E->getType());
1616}
1617
1618
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001619/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1620/// a result as the expression's type.
1621bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1622 const UnaryExprOrTypeTraitExpr *E) {
1623 switch(E->getKind()) {
1624 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001625 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001626 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001627 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001628 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001629 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001630
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001631 case UETT_VecStep: {
1632 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001633
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001634 if (Ty->isVectorType()) {
1635 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001636
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001637 // The vec_step built-in functions that take a 3-component
1638 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1639 if (n == 3)
1640 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001641
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001642 return Success(n, E);
1643 } else
1644 return Success(1, E);
1645 }
1646
1647 case UETT_SizeOf: {
1648 QualType SrcTy = E->getTypeOfArgument();
1649 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1650 // the result is the size of the referenced type."
1651 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1652 // result shall be the alignment of the referenced type."
1653 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1654 SrcTy = Ref->getPointeeType();
1655
1656 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1657 // extension.
1658 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1659 return Success(1, E);
1660
1661 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1662 if (!SrcTy->isConstantSizeType())
1663 return false;
1664
1665 // Get information about the size.
1666 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1667 }
1668 }
1669
1670 llvm_unreachable("unknown expr/type trait");
1671 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001672}
1673
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001674bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1675 CharUnits Result;
1676 unsigned n = E->getNumComponents();
1677 OffsetOfExpr* OOE = const_cast<OffsetOfExpr*>(E);
1678 if (n == 0)
1679 return false;
1680 QualType CurrentType = E->getTypeSourceInfo()->getType();
1681 for (unsigned i = 0; i != n; ++i) {
1682 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1683 switch (ON.getKind()) {
1684 case OffsetOfExpr::OffsetOfNode::Array: {
1685 Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
1686 APSInt IdxResult;
1687 if (!EvaluateInteger(Idx, IdxResult, Info))
1688 return false;
1689 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1690 if (!AT)
1691 return false;
1692 CurrentType = AT->getElementType();
1693 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1694 Result += IdxResult.getSExtValue() * ElementSize;
1695 break;
1696 }
1697
1698 case OffsetOfExpr::OffsetOfNode::Field: {
1699 FieldDecl *MemberDecl = ON.getField();
1700 const RecordType *RT = CurrentType->getAs<RecordType>();
1701 if (!RT)
1702 return false;
1703 RecordDecl *RD = RT->getDecl();
1704 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001705 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001706 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001707 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001708 CurrentType = MemberDecl->getType().getNonReferenceType();
1709 break;
1710 }
1711
1712 case OffsetOfExpr::OffsetOfNode::Identifier:
1713 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001714 return false;
1715
1716 case OffsetOfExpr::OffsetOfNode::Base: {
1717 CXXBaseSpecifier *BaseSpec = ON.getBase();
1718 if (BaseSpec->isVirtual())
1719 return false;
1720
1721 // Find the layout of the class whose base we are looking into.
1722 const RecordType *RT = CurrentType->getAs<RecordType>();
1723 if (!RT)
1724 return false;
1725 RecordDecl *RD = RT->getDecl();
1726 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1727
1728 // Find the base class itself.
1729 CurrentType = BaseSpec->getType();
1730 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1731 if (!BaseRT)
1732 return false;
1733
1734 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001735 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001736 break;
1737 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001738 }
1739 }
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001740 return Success(Result, E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001741}
1742
Chris Lattnerb542afe2008-07-11 19:10:17 +00001743bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001744 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001745 // LNot's operand isn't necessarily an integer, so we handle it specially.
1746 bool bres;
1747 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1748 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001749 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001750 }
1751
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001752 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001753 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001754 return false;
1755
Chris Lattner87eae5e2008-07-11 22:52:41 +00001756 // Get the operand value into 'Result'.
1757 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001758 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001759
Chris Lattner75a48812008-07-11 22:15:16 +00001760 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001761 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001762 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1763 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001764 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001765 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001766 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1767 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001768 return true;
John McCall2de56d12010-08-25 11:45:40 +00001769 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001770 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001771 return true;
John McCall2de56d12010-08-25 11:45:40 +00001772 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001773 if (!Result.isInt()) return false;
1774 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001775 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001776 if (!Result.isInt()) return false;
1777 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001778 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001779}
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Chris Lattner732b2232008-07-12 01:15:53 +00001781/// HandleCast - This is used to evaluate implicit or explicit casts where the
1782/// result type is integer.
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001783bool IntExprEvaluator::VisitCastExpr(CastExpr *E) {
Anders Carlsson82206e22008-11-30 18:14:57 +00001784 Expr *SubExpr = E->getSubExpr();
1785 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001786 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001787
Eli Friedman46a52322011-03-25 00:43:55 +00001788 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001789 case CK_BaseToDerived:
1790 case CK_DerivedToBase:
1791 case CK_UncheckedDerivedToBase:
1792 case CK_Dynamic:
1793 case CK_ToUnion:
1794 case CK_ArrayToPointerDecay:
1795 case CK_FunctionToPointerDecay:
1796 case CK_NullToPointer:
1797 case CK_NullToMemberPointer:
1798 case CK_BaseToDerivedMemberPointer:
1799 case CK_DerivedToBaseMemberPointer:
1800 case CK_ConstructorConversion:
1801 case CK_IntegralToPointer:
1802 case CK_ToVoid:
1803 case CK_VectorSplat:
1804 case CK_IntegralToFloating:
1805 case CK_FloatingCast:
1806 case CK_AnyPointerToObjCPointerCast:
1807 case CK_AnyPointerToBlockPointerCast:
1808 case CK_ObjCObjectLValueCast:
1809 case CK_FloatingRealToComplex:
1810 case CK_FloatingComplexToReal:
1811 case CK_FloatingComplexCast:
1812 case CK_FloatingComplexToIntegralComplex:
1813 case CK_IntegralRealToComplex:
1814 case CK_IntegralComplexCast:
1815 case CK_IntegralComplexToFloatingComplex:
1816 llvm_unreachable("invalid cast kind for integral value");
1817
Eli Friedmane50c2972011-03-25 19:07:11 +00001818 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001819 case CK_Dependent:
1820 case CK_GetObjCProperty:
1821 case CK_LValueBitCast:
1822 case CK_UserDefinedConversion:
1823 return false;
1824
1825 case CK_LValueToRValue:
1826 case CK_NoOp:
1827 return Visit(E->getSubExpr());
1828
1829 case CK_MemberPointerToBoolean:
1830 case CK_PointerToBoolean:
1831 case CK_IntegralToBoolean:
1832 case CK_FloatingToBoolean:
1833 case CK_FloatingComplexToBoolean:
1834 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001835 bool BoolResult;
1836 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1837 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001838 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001839 }
1840
Eli Friedman46a52322011-03-25 00:43:55 +00001841 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001842 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001843 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001844
Eli Friedmanbe265702009-02-20 01:15:07 +00001845 if (!Result.isInt()) {
1846 // Only allow casts of lvalues if they are lossless.
1847 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1848 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001849
Daniel Dunbardd211642009-02-19 22:24:01 +00001850 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001851 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001852 }
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Eli Friedman46a52322011-03-25 00:43:55 +00001854 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001855 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001856 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001857 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001858
Daniel Dunbardd211642009-02-19 22:24:01 +00001859 if (LV.getLValueBase()) {
1860 // Only allow based lvalue casts if they are lossless.
1861 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1862 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001863
John McCallefdb83e2010-05-07 21:00:08 +00001864 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001865 return true;
1866 }
1867
Ken Dycka7305832010-01-15 12:37:54 +00001868 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1869 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001870 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001871 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001872
Eli Friedman46a52322011-03-25 00:43:55 +00001873 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001874 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001875 if (!EvaluateComplex(SubExpr, C, Info))
1876 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001877 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001878 }
Eli Friedman2217c872009-02-22 11:46:18 +00001879
Eli Friedman46a52322011-03-25 00:43:55 +00001880 case CK_FloatingToIntegral: {
1881 APFloat F(0.0);
1882 if (!EvaluateFloat(SubExpr, F, Info))
1883 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001884
Eli Friedman46a52322011-03-25 00:43:55 +00001885 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1886 }
1887 }
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Eli Friedman46a52322011-03-25 00:43:55 +00001889 llvm_unreachable("unknown cast resulting in integral value");
1890 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001891}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001892
Eli Friedman722c7172009-02-28 03:59:05 +00001893bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1894 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001895 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001896 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1897 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1898 return Success(LV.getComplexIntReal(), E);
1899 }
1900
1901 return Visit(E->getSubExpr());
1902}
1903
Eli Friedman664a1042009-02-27 04:45:43 +00001904bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001905 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001906 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001907 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1908 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1909 return Success(LV.getComplexIntImag(), E);
1910 }
1911
Eli Friedman664a1042009-02-27 04:45:43 +00001912 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1913 Info.EvalResult.HasSideEffects = true;
1914 return Success(0, E);
1915}
1916
Douglas Gregoree8aff02011-01-04 17:33:58 +00001917bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1918 return Success(E->getPackLength(), E);
1919}
1920
Sebastian Redl295995c2010-09-10 20:55:47 +00001921bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1922 return Success(E->getValue(), E);
1923}
1924
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001925//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001926// Float Evaluation
1927//===----------------------------------------------------------------------===//
1928
1929namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001930class FloatExprEvaluator
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001931 : public StmtVisitor<FloatExprEvaluator, bool> {
1932 EvalInfo &Info;
1933 APFloat &Result;
1934public:
1935 FloatExprEvaluator(EvalInfo &info, APFloat &result)
1936 : Info(info), Result(result) {}
1937
1938 bool VisitStmt(Stmt *S) {
1939 return false;
1940 }
1941
1942 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00001943 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
1944 return Visit(E->getResultExpr());
1945 }
Chris Lattner019f4e82008-10-06 05:28:25 +00001946 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001947
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001948 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001949 bool VisitBinaryOperator(const BinaryOperator *E);
1950 bool VisitFloatingLiteral(const FloatingLiteral *E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001951 bool VisitCastExpr(CastExpr *E);
Douglas Gregored8abf12010-07-08 06:14:04 +00001952 bool VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
Eli Friedman67f85fc2009-12-04 02:12:53 +00001953 bool VisitConditionalOperator(ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00001954 bool VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001955
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001956 bool VisitChooseExpr(const ChooseExpr *E)
1957 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
1958 bool VisitUnaryExtension(const UnaryOperator *E)
1959 { return Visit(E->getSubExpr()); }
John McCallabd3a852010-05-07 22:08:54 +00001960 bool VisitUnaryReal(const UnaryOperator *E);
1961 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001962
John McCall189d6ef2010-10-09 01:34:31 +00001963 bool VisitDeclRefExpr(const DeclRefExpr *E);
1964
John McCall56ca35d2011-02-17 10:25:35 +00001965 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
1966 const APValue *value = Info.getOpaqueValue(e);
1967 if (!value)
1968 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
1969 Result = value->getFloat();
1970 return true;
1971 }
1972
John McCallabd3a852010-05-07 22:08:54 +00001973 // FIXME: Missing: array subscript of vector, member of vector,
1974 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001975};
1976} // end anonymous namespace
1977
1978static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001979 assert(E->getType()->isRealFloatingType());
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001980 return FloatExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
1981}
1982
Jay Foad4ba2a172011-01-12 09:06:06 +00001983static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001984 QualType ResultTy,
1985 const Expr *Arg,
1986 bool SNaN,
1987 llvm::APFloat &Result) {
1988 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1989 if (!S) return false;
1990
1991 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1992
1993 llvm::APInt fill;
1994
1995 // Treat empty strings as if they were zero.
1996 if (S->getString().empty())
1997 fill = llvm::APInt(32, 0);
1998 else if (S->getString().getAsInteger(0, fill))
1999 return false;
2000
2001 if (SNaN)
2002 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2003 else
2004 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2005 return true;
2006}
2007
Chris Lattner019f4e82008-10-06 05:28:25 +00002008bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00002009 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner34a74ab2008-10-06 05:53:16 +00002010 default: return false;
Chris Lattner019f4e82008-10-06 05:28:25 +00002011 case Builtin::BI__builtin_huge_val:
2012 case Builtin::BI__builtin_huge_valf:
2013 case Builtin::BI__builtin_huge_vall:
2014 case Builtin::BI__builtin_inf:
2015 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002016 case Builtin::BI__builtin_infl: {
2017 const llvm::fltSemantics &Sem =
2018 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002019 Result = llvm::APFloat::getInf(Sem);
2020 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002021 }
Mike Stump1eb44332009-09-09 15:08:12 +00002022
John McCalldb7b72a2010-02-28 13:00:19 +00002023 case Builtin::BI__builtin_nans:
2024 case Builtin::BI__builtin_nansf:
2025 case Builtin::BI__builtin_nansl:
2026 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2027 true, Result);
2028
Chris Lattner9e621712008-10-06 06:31:58 +00002029 case Builtin::BI__builtin_nan:
2030 case Builtin::BI__builtin_nanf:
2031 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002032 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002033 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002034 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2035 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002036
2037 case Builtin::BI__builtin_fabs:
2038 case Builtin::BI__builtin_fabsf:
2039 case Builtin::BI__builtin_fabsl:
2040 if (!EvaluateFloat(E->getArg(0), Result, Info))
2041 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002042
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002043 if (Result.isNegative())
2044 Result.changeSign();
2045 return true;
2046
Mike Stump1eb44332009-09-09 15:08:12 +00002047 case Builtin::BI__builtin_copysign:
2048 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002049 case Builtin::BI__builtin_copysignl: {
2050 APFloat RHS(0.);
2051 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2052 !EvaluateFloat(E->getArg(1), RHS, Info))
2053 return false;
2054 Result.copySign(RHS);
2055 return true;
2056 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002057 }
2058}
2059
John McCall189d6ef2010-10-09 01:34:31 +00002060bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
2061 const Decl *D = E->getDecl();
2062 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2063 const VarDecl *VD = cast<VarDecl>(D);
2064
2065 // Require the qualifiers to be const and not volatile.
2066 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2067 if (!T.isConstQualified() || T.isVolatileQualified())
2068 return false;
2069
2070 const Expr *Init = VD->getAnyInitializer();
2071 if (!Init) return false;
2072
2073 if (APValue *V = VD->getEvaluatedValue()) {
2074 if (V->isFloat()) {
2075 Result = V->getFloat();
2076 return true;
2077 }
2078 return false;
2079 }
2080
2081 if (VD->isEvaluatingValue())
2082 return false;
2083
2084 VD->setEvaluatingValue();
2085
2086 Expr::EvalResult InitResult;
2087 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2088 InitResult.Val.isFloat()) {
2089 // Cache the evaluated value in the variable declaration.
2090 Result = InitResult.Val.getFloat();
2091 VD->setEvaluatedValue(InitResult.Val);
2092 return true;
2093 }
2094
2095 VD->setEvaluatedValue(APValue());
2096 return false;
2097}
2098
John McCallabd3a852010-05-07 22:08:54 +00002099bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002100 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2101 ComplexValue CV;
2102 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2103 return false;
2104 Result = CV.FloatReal;
2105 return true;
2106 }
2107
2108 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002109}
2110
2111bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002112 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2113 ComplexValue CV;
2114 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2115 return false;
2116 Result = CV.FloatImag;
2117 return true;
2118 }
2119
2120 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2121 Info.EvalResult.HasSideEffects = true;
2122 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2123 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002124 return true;
2125}
2126
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002127bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002128 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002129 return false;
2130
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002131 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2132 return false;
2133
2134 switch (E->getOpcode()) {
2135 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002136 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002137 return true;
John McCall2de56d12010-08-25 11:45:40 +00002138 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002139 Result.changeSign();
2140 return true;
2141 }
2142}
Chris Lattner019f4e82008-10-06 05:28:25 +00002143
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002144bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002145 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002146 if (!EvaluateFloat(E->getRHS(), Result, Info))
2147 return false;
2148
2149 // If we can't evaluate the LHS, it might have side effects;
2150 // conservatively mark it.
2151 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2152 Info.EvalResult.HasSideEffects = true;
2153
2154 return true;
2155 }
2156
Anders Carlsson96e93662010-10-31 01:21:47 +00002157 // We can't evaluate pointer-to-member operations.
2158 if (E->isPtrMemOp())
2159 return false;
2160
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002161 // FIXME: Diagnostics? I really don't understand how the warnings
2162 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002163 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002164 if (!EvaluateFloat(E->getLHS(), Result, Info))
2165 return false;
2166 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2167 return false;
2168
2169 switch (E->getOpcode()) {
2170 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002171 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002172 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2173 return true;
John McCall2de56d12010-08-25 11:45:40 +00002174 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002175 Result.add(RHS, APFloat::rmNearestTiesToEven);
2176 return true;
John McCall2de56d12010-08-25 11:45:40 +00002177 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002178 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2179 return true;
John McCall2de56d12010-08-25 11:45:40 +00002180 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002181 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2182 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002183 }
2184}
2185
2186bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2187 Result = E->getValue();
2188 return true;
2189}
2190
Eli Friedman4efaa272008-11-12 09:44:48 +00002191bool FloatExprEvaluator::VisitCastExpr(CastExpr *E) {
2192 Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002193
Eli Friedman2a523ee2011-03-25 00:54:52 +00002194 switch (E->getCastKind()) {
2195 default:
2196 return false;
2197
2198 case CK_LValueToRValue:
2199 case CK_NoOp:
2200 return Visit(SubExpr);
2201
2202 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002203 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002204 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002205 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002206 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002207 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002208 return true;
2209 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002210
2211 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002212 if (!Visit(SubExpr))
2213 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002214 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2215 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002216 return true;
2217 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002218
Eli Friedman2a523ee2011-03-25 00:54:52 +00002219 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002220 ComplexValue V;
2221 if (!EvaluateComplex(SubExpr, V, Info))
2222 return false;
2223 Result = V.getComplexFloatReal();
2224 return true;
2225 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002226 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002227
2228 return false;
2229}
2230
Douglas Gregored8abf12010-07-08 06:14:04 +00002231bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002232 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2233 return true;
2234}
2235
John McCall56ca35d2011-02-17 10:25:35 +00002236bool FloatExprEvaluator::
2237VisitBinaryConditionalOperator(BinaryConditionalOperator *e) {
2238 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2239 if (opaque.hasError()) return false;
2240
2241 bool cond;
2242 if (!HandleConversionToBool(e->getCond(), cond, Info))
2243 return false;
2244
2245 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2246}
2247
Eli Friedman67f85fc2009-12-04 02:12:53 +00002248bool FloatExprEvaluator::VisitConditionalOperator(ConditionalOperator *E) {
2249 bool Cond;
2250 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2251 return false;
2252
2253 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2254}
2255
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002256//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002257// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002258//===----------------------------------------------------------------------===//
2259
2260namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002261class ComplexExprEvaluator
John McCallf4cf1a12010-05-07 17:22:02 +00002262 : public StmtVisitor<ComplexExprEvaluator, bool> {
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002263 EvalInfo &Info;
John McCallf4cf1a12010-05-07 17:22:02 +00002264 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002266public:
John McCallf4cf1a12010-05-07 17:22:02 +00002267 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
2268 : Info(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002269
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002270 //===--------------------------------------------------------------------===//
2271 // Visitor Methods
2272 //===--------------------------------------------------------------------===//
2273
John McCallf4cf1a12010-05-07 17:22:02 +00002274 bool VisitStmt(Stmt *S) {
2275 return false;
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002276 }
Mike Stump1eb44332009-09-09 15:08:12 +00002277
John McCallf4cf1a12010-05-07 17:22:02 +00002278 bool VisitParenExpr(ParenExpr *E) { return Visit(E->getSubExpr()); }
Peter Collingbournef111d932011-04-15 00:35:48 +00002279 bool VisitGenericSelectionExpr(GenericSelectionExpr *E) {
2280 return Visit(E->getResultExpr());
2281 }
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002282
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002283 bool VisitImaginaryLiteral(ImaginaryLiteral *E);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002284
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002285 bool VisitCastExpr(CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002286
John McCallf4cf1a12010-05-07 17:22:02 +00002287 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002288 bool VisitUnaryOperator(const UnaryOperator *E);
2289 bool VisitConditionalOperator(const ConditionalOperator *E);
John McCall56ca35d2011-02-17 10:25:35 +00002290 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E);
John McCallf4cf1a12010-05-07 17:22:02 +00002291 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002292 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
John McCallf4cf1a12010-05-07 17:22:02 +00002293 bool VisitUnaryExtension(const UnaryOperator *E)
Eli Friedmanba98d6b2009-03-23 04:56:01 +00002294 { return Visit(E->getSubExpr()); }
John McCall56ca35d2011-02-17 10:25:35 +00002295 bool VisitOpaqueValueExpr(const OpaqueValueExpr *e) {
2296 const APValue *value = Info.getOpaqueValue(e);
2297 if (!value)
2298 return (e->getSourceExpr() ? Visit(e->getSourceExpr()) : false);
2299 Result.setFrom(*value);
2300 return true;
2301 }
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002302 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002303};
2304} // end anonymous namespace
2305
John McCallf4cf1a12010-05-07 17:22:02 +00002306static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2307 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002308 assert(E->getType()->isAnyComplexType());
John McCallf4cf1a12010-05-07 17:22:02 +00002309 return ComplexExprEvaluator(Info, Result).Visit(const_cast<Expr*>(E));
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002310}
2311
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002312bool ComplexExprEvaluator::VisitImaginaryLiteral(ImaginaryLiteral *E) {
2313 Expr* SubExpr = E->getSubExpr();
2314
2315 if (SubExpr->getType()->isRealFloatingType()) {
2316 Result.makeComplexFloat();
2317 APFloat &Imag = Result.FloatImag;
2318 if (!EvaluateFloat(SubExpr, Imag, Info))
2319 return false;
2320
2321 Result.FloatReal = APFloat(Imag.getSemantics());
2322 return true;
2323 } else {
2324 assert(SubExpr->getType()->isIntegerType() &&
2325 "Unexpected imaginary literal.");
2326
2327 Result.makeComplexInt();
2328 APSInt &Imag = Result.IntImag;
2329 if (!EvaluateInteger(SubExpr, Imag, Info))
2330 return false;
2331
2332 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2333 return true;
2334 }
2335}
2336
2337bool ComplexExprEvaluator::VisitCastExpr(CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002338
John McCall8786da72010-12-14 17:51:41 +00002339 switch (E->getCastKind()) {
2340 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002341 case CK_BaseToDerived:
2342 case CK_DerivedToBase:
2343 case CK_UncheckedDerivedToBase:
2344 case CK_Dynamic:
2345 case CK_ToUnion:
2346 case CK_ArrayToPointerDecay:
2347 case CK_FunctionToPointerDecay:
2348 case CK_NullToPointer:
2349 case CK_NullToMemberPointer:
2350 case CK_BaseToDerivedMemberPointer:
2351 case CK_DerivedToBaseMemberPointer:
2352 case CK_MemberPointerToBoolean:
2353 case CK_ConstructorConversion:
2354 case CK_IntegralToPointer:
2355 case CK_PointerToIntegral:
2356 case CK_PointerToBoolean:
2357 case CK_ToVoid:
2358 case CK_VectorSplat:
2359 case CK_IntegralCast:
2360 case CK_IntegralToBoolean:
2361 case CK_IntegralToFloating:
2362 case CK_FloatingToIntegral:
2363 case CK_FloatingToBoolean:
2364 case CK_FloatingCast:
2365 case CK_AnyPointerToObjCPointerCast:
2366 case CK_AnyPointerToBlockPointerCast:
2367 case CK_ObjCObjectLValueCast:
2368 case CK_FloatingComplexToReal:
2369 case CK_FloatingComplexToBoolean:
2370 case CK_IntegralComplexToReal:
2371 case CK_IntegralComplexToBoolean:
2372 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002373
John McCall8786da72010-12-14 17:51:41 +00002374 case CK_LValueToRValue:
2375 case CK_NoOp:
2376 return Visit(E->getSubExpr());
2377
2378 case CK_Dependent:
2379 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002380 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002381 case CK_UserDefinedConversion:
2382 return false;
2383
2384 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002385 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002386 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002387 return false;
2388
John McCall8786da72010-12-14 17:51:41 +00002389 Result.makeComplexFloat();
2390 Result.FloatImag = APFloat(Real.getSemantics());
2391 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002392 }
2393
John McCall8786da72010-12-14 17:51:41 +00002394 case CK_FloatingComplexCast: {
2395 if (!Visit(E->getSubExpr()))
2396 return false;
2397
2398 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2399 QualType From
2400 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2401
2402 Result.FloatReal
2403 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2404 Result.FloatImag
2405 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2406 return true;
2407 }
2408
2409 case CK_FloatingComplexToIntegralComplex: {
2410 if (!Visit(E->getSubExpr()))
2411 return false;
2412
2413 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2414 QualType From
2415 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2416 Result.makeComplexInt();
2417 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2418 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2419 return true;
2420 }
2421
2422 case CK_IntegralRealToComplex: {
2423 APSInt &Real = Result.IntReal;
2424 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2425 return false;
2426
2427 Result.makeComplexInt();
2428 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2429 return true;
2430 }
2431
2432 case CK_IntegralComplexCast: {
2433 if (!Visit(E->getSubExpr()))
2434 return false;
2435
2436 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2437 QualType From
2438 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2439
2440 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2441 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2442 return true;
2443 }
2444
2445 case CK_IntegralComplexToFloatingComplex: {
2446 if (!Visit(E->getSubExpr()))
2447 return false;
2448
2449 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2450 QualType From
2451 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2452 Result.makeComplexFloat();
2453 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2454 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2455 return true;
2456 }
2457 }
2458
2459 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002460 return false;
2461}
2462
John McCallf4cf1a12010-05-07 17:22:02 +00002463bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002464 if (E->getOpcode() == BO_Comma) {
2465 if (!Visit(E->getRHS()))
2466 return false;
2467
2468 // If we can't evaluate the LHS, it might have side effects;
2469 // conservatively mark it.
2470 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2471 Info.EvalResult.HasSideEffects = true;
2472
2473 return true;
2474 }
John McCallf4cf1a12010-05-07 17:22:02 +00002475 if (!Visit(E->getLHS()))
2476 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002477
John McCallf4cf1a12010-05-07 17:22:02 +00002478 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002479 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002480 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002481
Daniel Dunbar3f279872009-01-29 01:32:56 +00002482 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2483 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002484 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002485 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002486 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002487 if (Result.isComplexFloat()) {
2488 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2489 APFloat::rmNearestTiesToEven);
2490 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2491 APFloat::rmNearestTiesToEven);
2492 } else {
2493 Result.getComplexIntReal() += RHS.getComplexIntReal();
2494 Result.getComplexIntImag() += RHS.getComplexIntImag();
2495 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002496 break;
John McCall2de56d12010-08-25 11:45:40 +00002497 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002498 if (Result.isComplexFloat()) {
2499 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2500 APFloat::rmNearestTiesToEven);
2501 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2502 APFloat::rmNearestTiesToEven);
2503 } else {
2504 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2505 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2506 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002507 break;
John McCall2de56d12010-08-25 11:45:40 +00002508 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002509 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002510 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002511 APFloat &LHS_r = LHS.getComplexFloatReal();
2512 APFloat &LHS_i = LHS.getComplexFloatImag();
2513 APFloat &RHS_r = RHS.getComplexFloatReal();
2514 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002515
Daniel Dunbar3f279872009-01-29 01:32:56 +00002516 APFloat Tmp = LHS_r;
2517 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2518 Result.getComplexFloatReal() = Tmp;
2519 Tmp = LHS_i;
2520 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2521 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2522
2523 Tmp = LHS_r;
2524 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2525 Result.getComplexFloatImag() = Tmp;
2526 Tmp = LHS_i;
2527 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2528 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2529 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002530 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002531 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002532 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2533 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002534 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002535 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2536 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2537 }
2538 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002539 case BO_Div:
2540 if (Result.isComplexFloat()) {
2541 ComplexValue LHS = Result;
2542 APFloat &LHS_r = LHS.getComplexFloatReal();
2543 APFloat &LHS_i = LHS.getComplexFloatImag();
2544 APFloat &RHS_r = RHS.getComplexFloatReal();
2545 APFloat &RHS_i = RHS.getComplexFloatImag();
2546 APFloat &Res_r = Result.getComplexFloatReal();
2547 APFloat &Res_i = Result.getComplexFloatImag();
2548
2549 APFloat Den = RHS_r;
2550 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2551 APFloat Tmp = RHS_i;
2552 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2553 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2554
2555 Res_r = LHS_r;
2556 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2557 Tmp = LHS_i;
2558 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2559 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2560 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2561
2562 Res_i = LHS_i;
2563 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2564 Tmp = LHS_r;
2565 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2566 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2567 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2568 } else {
2569 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2570 // FIXME: what about diagnostics?
2571 return false;
2572 }
2573 ComplexValue LHS = Result;
2574 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2575 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2576 Result.getComplexIntReal() =
2577 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2578 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2579 Result.getComplexIntImag() =
2580 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2581 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2582 }
2583 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002584 }
2585
John McCallf4cf1a12010-05-07 17:22:02 +00002586 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002587}
2588
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002589bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2590 // Get the operand value into 'Result'.
2591 if (!Visit(E->getSubExpr()))
2592 return false;
2593
2594 switch (E->getOpcode()) {
2595 default:
2596 // FIXME: what about diagnostics?
2597 return false;
2598 case UO_Extension:
2599 return true;
2600 case UO_Plus:
2601 // The result is always just the subexpr.
2602 return true;
2603 case UO_Minus:
2604 if (Result.isComplexFloat()) {
2605 Result.getComplexFloatReal().changeSign();
2606 Result.getComplexFloatImag().changeSign();
2607 }
2608 else {
2609 Result.getComplexIntReal() = -Result.getComplexIntReal();
2610 Result.getComplexIntImag() = -Result.getComplexIntImag();
2611 }
2612 return true;
2613 case UO_Not:
2614 if (Result.isComplexFloat())
2615 Result.getComplexFloatImag().changeSign();
2616 else
2617 Result.getComplexIntImag() = -Result.getComplexIntImag();
2618 return true;
2619 }
2620}
2621
John McCall56ca35d2011-02-17 10:25:35 +00002622bool ComplexExprEvaluator::
2623VisitBinaryConditionalOperator(const BinaryConditionalOperator *e) {
2624 OpaqueValueEvaluation opaque(Info, e->getOpaqueValue(), e->getCommon());
2625 if (opaque.hasError()) return false;
2626
2627 bool cond;
2628 if (!HandleConversionToBool(e->getCond(), cond, Info))
2629 return false;
2630
2631 return Visit(cond ? e->getTrueExpr() : e->getFalseExpr());
2632}
2633
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002634bool ComplexExprEvaluator::VisitConditionalOperator(const ConditionalOperator *E) {
2635 bool Cond;
2636 if (!HandleConversionToBool(E->getCond(), Cond, Info))
2637 return false;
2638
2639 return Visit(Cond ? E->getTrueExpr() : E->getFalseExpr());
2640}
2641
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002642//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002643// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002644//===----------------------------------------------------------------------===//
2645
John McCall56ca35d2011-02-17 10:25:35 +00002646static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002647 if (E->getType()->isVectorType()) {
2648 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002649 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002650 } else if (E->getType()->isIntegerType()) {
2651 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(const_cast<Expr*>(E)))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002652 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002653 if (Info.EvalResult.Val.isLValue() &&
2654 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002655 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002656 } else if (E->getType()->hasPointerRepresentation()) {
2657 LValue LV;
2658 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002659 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002660 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002661 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002662 LV.moveInto(Info.EvalResult.Val);
2663 } else if (E->getType()->isRealFloatingType()) {
2664 llvm::APFloat F(0.0);
2665 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002666 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002667
John McCallefdb83e2010-05-07 21:00:08 +00002668 Info.EvalResult.Val = APValue(F);
2669 } else if (E->getType()->isAnyComplexType()) {
2670 ComplexValue C;
2671 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002672 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002673 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002674 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002675 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002676
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002677 return true;
2678}
2679
John McCall56ca35d2011-02-17 10:25:35 +00002680/// Evaluate - Return true if this is a constant which we can fold using
2681/// any crazy technique (that has nothing to do with language standards) that
2682/// we want to. If this function returns true, it returns the folded constant
2683/// in Result.
2684bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2685 EvalInfo Info(Ctx, Result);
2686 return ::Evaluate(Info, this);
2687}
2688
Jay Foad4ba2a172011-01-12 09:06:06 +00002689bool Expr::EvaluateAsBooleanCondition(bool &Result,
2690 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002691 EvalResult Scratch;
2692 EvalInfo Info(Ctx, Scratch);
2693
2694 return HandleConversionToBool(this, Result, Info);
2695}
2696
Jay Foad4ba2a172011-01-12 09:06:06 +00002697bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002698 EvalInfo Info(Ctx, Result);
2699
John McCallefdb83e2010-05-07 21:00:08 +00002700 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002701 if (EvaluateLValue(this, LV, Info) &&
2702 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002703 IsGlobalLValue(LV.Base)) {
2704 LV.moveInto(Result.Val);
2705 return true;
2706 }
2707 return false;
2708}
2709
Jay Foad4ba2a172011-01-12 09:06:06 +00002710bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2711 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002712 EvalInfo Info(Ctx, Result);
2713
2714 LValue LV;
2715 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002716 LV.moveInto(Result.Val);
2717 return true;
2718 }
2719 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002720}
2721
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002722/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002723/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002724bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002725 EvalResult Result;
2726 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002727}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002728
Jay Foad4ba2a172011-01-12 09:06:06 +00002729bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002730 Expr::EvalResult Result;
2731 EvalInfo Info(Ctx, Result);
2732 return HasSideEffect(Info).Visit(const_cast<Expr*>(this));
2733}
2734
Jay Foad4ba2a172011-01-12 09:06:06 +00002735APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002736 EvalResult EvalResult;
2737 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002738 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002739 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002740 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002741
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002742 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002743}
John McCalld905f5a2010-05-07 05:32:02 +00002744
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002745 bool Expr::EvalResult::isGlobalLValue() const {
2746 assert(Val.isLValue());
2747 return IsGlobalLValue(Val.getLValueBase());
2748 }
2749
2750
John McCalld905f5a2010-05-07 05:32:02 +00002751/// isIntegerConstantExpr - this recursive routine will test if an expression is
2752/// an integer constant expression.
2753
2754/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2755/// comma, etc
2756///
2757/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2758/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2759/// cast+dereference.
2760
2761// CheckICE - This function does the fundamental ICE checking: the returned
2762// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2763// Note that to reduce code duplication, this helper does no evaluation
2764// itself; the caller checks whether the expression is evaluatable, and
2765// in the rare cases where CheckICE actually cares about the evaluated
2766// value, it calls into Evalute.
2767//
2768// Meanings of Val:
2769// 0: This expression is an ICE if it can be evaluated by Evaluate.
2770// 1: This expression is not an ICE, but if it isn't evaluated, it's
2771// a legal subexpression for an ICE. This return value is used to handle
2772// the comma operator in C99 mode.
2773// 2: This expression is not an ICE, and is not a legal subexpression for one.
2774
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002775namespace {
2776
John McCalld905f5a2010-05-07 05:32:02 +00002777struct ICEDiag {
2778 unsigned Val;
2779 SourceLocation Loc;
2780
2781 public:
2782 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2783 ICEDiag() : Val(0) {}
2784};
2785
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002786}
2787
2788static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002789
2790static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2791 Expr::EvalResult EVResult;
2792 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2793 !EVResult.Val.isInt()) {
2794 return ICEDiag(2, E->getLocStart());
2795 }
2796 return NoDiag();
2797}
2798
2799static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2800 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002801 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002802 return ICEDiag(2, E->getLocStart());
2803 }
2804
2805 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002806#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002807#define STMT(Node, Base) case Expr::Node##Class:
2808#define EXPR(Node, Base)
2809#include "clang/AST/StmtNodes.inc"
2810 case Expr::PredefinedExprClass:
2811 case Expr::FloatingLiteralClass:
2812 case Expr::ImaginaryLiteralClass:
2813 case Expr::StringLiteralClass:
2814 case Expr::ArraySubscriptExprClass:
2815 case Expr::MemberExprClass:
2816 case Expr::CompoundAssignOperatorClass:
2817 case Expr::CompoundLiteralExprClass:
2818 case Expr::ExtVectorElementExprClass:
2819 case Expr::InitListExprClass:
2820 case Expr::DesignatedInitExprClass:
2821 case Expr::ImplicitValueInitExprClass:
2822 case Expr::ParenListExprClass:
2823 case Expr::VAArgExprClass:
2824 case Expr::AddrLabelExprClass:
2825 case Expr::StmtExprClass:
2826 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002827 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002828 case Expr::CXXDynamicCastExprClass:
2829 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002830 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002831 case Expr::CXXNullPtrLiteralExprClass:
2832 case Expr::CXXThisExprClass:
2833 case Expr::CXXThrowExprClass:
2834 case Expr::CXXNewExprClass:
2835 case Expr::CXXDeleteExprClass:
2836 case Expr::CXXPseudoDestructorExprClass:
2837 case Expr::UnresolvedLookupExprClass:
2838 case Expr::DependentScopeDeclRefExprClass:
2839 case Expr::CXXConstructExprClass:
2840 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002841 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002842 case Expr::CXXTemporaryObjectExprClass:
2843 case Expr::CXXUnresolvedConstructExprClass:
2844 case Expr::CXXDependentScopeMemberExprClass:
2845 case Expr::UnresolvedMemberExprClass:
2846 case Expr::ObjCStringLiteralClass:
2847 case Expr::ObjCEncodeExprClass:
2848 case Expr::ObjCMessageExprClass:
2849 case Expr::ObjCSelectorExprClass:
2850 case Expr::ObjCProtocolExprClass:
2851 case Expr::ObjCIvarRefExprClass:
2852 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002853 case Expr::ObjCIsaExprClass:
2854 case Expr::ShuffleVectorExprClass:
2855 case Expr::BlockExprClass:
2856 case Expr::BlockDeclRefExprClass:
2857 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002858 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002859 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002860 case Expr::SubstNonTypeTemplateParmPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002861 return ICEDiag(2, E->getLocStart());
2862
Douglas Gregoree8aff02011-01-04 17:33:58 +00002863 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002864 case Expr::GNUNullExprClass:
2865 // GCC considers the GNU __null value to be an integral constant expression.
2866 return NoDiag();
2867
2868 case Expr::ParenExprClass:
2869 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002870 case Expr::GenericSelectionExprClass:
2871 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002872 case Expr::IntegerLiteralClass:
2873 case Expr::CharacterLiteralClass:
2874 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002875 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002876 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002877 case Expr::BinaryTypeTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002878 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002879 return NoDiag();
2880 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002881 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002882 const CallExpr *CE = cast<CallExpr>(E);
2883 if (CE->isBuiltinCall(Ctx))
2884 return CheckEvalInICE(E, Ctx);
2885 return ICEDiag(2, E->getLocStart());
2886 }
2887 case Expr::DeclRefExprClass:
2888 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2889 return NoDiag();
2890 if (Ctx.getLangOptions().CPlusPlus &&
2891 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2892 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2893
2894 // Parameter variables are never constants. Without this check,
2895 // getAnyInitializer() can find a default argument, which leads
2896 // to chaos.
2897 if (isa<ParmVarDecl>(D))
2898 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2899
2900 // C++ 7.1.5.1p2
2901 // A variable of non-volatile const-qualified integral or enumeration
2902 // type initialized by an ICE can be used in ICEs.
2903 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2904 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2905 if (Quals.hasVolatile() || !Quals.hasConst())
2906 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2907
2908 // Look for a declaration of this variable that has an initializer.
2909 const VarDecl *ID = 0;
2910 const Expr *Init = Dcl->getAnyInitializer(ID);
2911 if (Init) {
2912 if (ID->isInitKnownICE()) {
2913 // We have already checked whether this subexpression is an
2914 // integral constant expression.
2915 if (ID->isInitICE())
2916 return NoDiag();
2917 else
2918 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2919 }
2920
2921 // It's an ICE whether or not the definition we found is
2922 // out-of-line. See DR 721 and the discussion in Clang PR
2923 // 6206 for details.
2924
2925 if (Dcl->isCheckingICE()) {
2926 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2927 }
2928
2929 Dcl->setCheckingICE();
2930 ICEDiag Result = CheckICE(Init, Ctx);
2931 // Cache the result of the ICE test.
2932 Dcl->setInitKnownICE(Result.Val == 0);
2933 return Result;
2934 }
2935 }
2936 }
2937 return ICEDiag(2, E->getLocStart());
2938 case Expr::UnaryOperatorClass: {
2939 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2940 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002941 case UO_PostInc:
2942 case UO_PostDec:
2943 case UO_PreInc:
2944 case UO_PreDec:
2945 case UO_AddrOf:
2946 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002947 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002948 case UO_Extension:
2949 case UO_LNot:
2950 case UO_Plus:
2951 case UO_Minus:
2952 case UO_Not:
2953 case UO_Real:
2954 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002955 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002956 }
2957
2958 // OffsetOf falls through here.
2959 }
2960 case Expr::OffsetOfExprClass: {
2961 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2962 // Evaluate matches the proposed gcc behavior for cases like
2963 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2964 // compliance: we should warn earlier for offsetof expressions with
2965 // array subscripts that aren't ICEs, and if the array subscripts
2966 // are ICEs, the value of the offsetof must be an integer constant.
2967 return CheckEvalInICE(E, Ctx);
2968 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002969 case Expr::UnaryExprOrTypeTraitExprClass: {
2970 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2971 if ((Exp->getKind() == UETT_SizeOf) &&
2972 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002973 return ICEDiag(2, E->getLocStart());
2974 return NoDiag();
2975 }
2976 case Expr::BinaryOperatorClass: {
2977 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2978 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002979 case BO_PtrMemD:
2980 case BO_PtrMemI:
2981 case BO_Assign:
2982 case BO_MulAssign:
2983 case BO_DivAssign:
2984 case BO_RemAssign:
2985 case BO_AddAssign:
2986 case BO_SubAssign:
2987 case BO_ShlAssign:
2988 case BO_ShrAssign:
2989 case BO_AndAssign:
2990 case BO_XorAssign:
2991 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002992 return ICEDiag(2, E->getLocStart());
2993
John McCall2de56d12010-08-25 11:45:40 +00002994 case BO_Mul:
2995 case BO_Div:
2996 case BO_Rem:
2997 case BO_Add:
2998 case BO_Sub:
2999 case BO_Shl:
3000 case BO_Shr:
3001 case BO_LT:
3002 case BO_GT:
3003 case BO_LE:
3004 case BO_GE:
3005 case BO_EQ:
3006 case BO_NE:
3007 case BO_And:
3008 case BO_Xor:
3009 case BO_Or:
3010 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00003011 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3012 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00003013 if (Exp->getOpcode() == BO_Div ||
3014 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00003015 // Evaluate gives an error for undefined Div/Rem, so make sure
3016 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00003017 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00003018 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
3019 if (REval == 0)
3020 return ICEDiag(1, E->getLocStart());
3021 if (REval.isSigned() && REval.isAllOnesValue()) {
3022 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
3023 if (LEval.isMinSignedValue())
3024 return ICEDiag(1, E->getLocStart());
3025 }
3026 }
3027 }
John McCall2de56d12010-08-25 11:45:40 +00003028 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00003029 if (Ctx.getLangOptions().C99) {
3030 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3031 // if it isn't evaluated.
3032 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3033 return ICEDiag(1, E->getLocStart());
3034 } else {
3035 // In both C89 and C++, commas in ICEs are illegal.
3036 return ICEDiag(2, E->getLocStart());
3037 }
3038 }
3039 if (LHSResult.Val >= RHSResult.Val)
3040 return LHSResult;
3041 return RHSResult;
3042 }
John McCall2de56d12010-08-25 11:45:40 +00003043 case BO_LAnd:
3044 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00003045 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3046 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3047 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3048 // Rare case where the RHS has a comma "side-effect"; we need
3049 // to actually check the condition to see whether the side
3050 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003051 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003052 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3053 return RHSResult;
3054 return NoDiag();
3055 }
3056
3057 if (LHSResult.Val >= RHSResult.Val)
3058 return LHSResult;
3059 return RHSResult;
3060 }
3061 }
3062 }
3063 case Expr::ImplicitCastExprClass:
3064 case Expr::CStyleCastExprClass:
3065 case Expr::CXXFunctionalCastExprClass:
3066 case Expr::CXXStaticCastExprClass:
3067 case Expr::CXXReinterpretCastExprClass:
3068 case Expr::CXXConstCastExprClass: {
3069 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003070 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003071 return CheckICE(SubExpr, Ctx);
3072 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3073 return NoDiag();
3074 return ICEDiag(2, E->getLocStart());
3075 }
John McCall56ca35d2011-02-17 10:25:35 +00003076 case Expr::BinaryConditionalOperatorClass: {
3077 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3078 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3079 if (CommonResult.Val == 2) return CommonResult;
3080 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3081 if (FalseResult.Val == 2) return FalseResult;
3082 if (CommonResult.Val == 1) return CommonResult;
3083 if (FalseResult.Val == 1 &&
3084 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3085 return FalseResult;
3086 }
John McCalld905f5a2010-05-07 05:32:02 +00003087 case Expr::ConditionalOperatorClass: {
3088 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3089 // If the condition (ignoring parens) is a __builtin_constant_p call,
3090 // then only the true side is actually considered in an integer constant
3091 // expression, and it is fully evaluated. This is an important GNU
3092 // extension. See GCC PR38377 for discussion.
3093 if (const CallExpr *CallCE
3094 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3095 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3096 Expr::EvalResult EVResult;
3097 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3098 !EVResult.Val.isInt()) {
3099 return ICEDiag(2, E->getLocStart());
3100 }
3101 return NoDiag();
3102 }
3103 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
3104 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3105 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3106 if (CondResult.Val == 2)
3107 return CondResult;
3108 if (TrueResult.Val == 2)
3109 return TrueResult;
3110 if (FalseResult.Val == 2)
3111 return FalseResult;
3112 if (CondResult.Val == 1)
3113 return CondResult;
3114 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3115 return NoDiag();
3116 // Rare case where the diagnostics depend on which side is evaluated
3117 // Note that if we get here, CondResult is 0, and at least one of
3118 // TrueResult and FalseResult is non-zero.
3119 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3120 return FalseResult;
3121 }
3122 return TrueResult;
3123 }
3124 case Expr::CXXDefaultArgExprClass:
3125 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3126 case Expr::ChooseExprClass: {
3127 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3128 }
3129 }
3130
3131 // Silence a GCC warning
3132 return ICEDiag(2, E->getLocStart());
3133}
3134
3135bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3136 SourceLocation *Loc, bool isEvaluated) const {
3137 ICEDiag d = CheckICE(this, Ctx);
3138 if (d.Val != 0) {
3139 if (Loc) *Loc = d.Loc;
3140 return false;
3141 }
3142 EvalResult EvalResult;
3143 if (!Evaluate(EvalResult, Ctx))
3144 llvm_unreachable("ICE cannot be evaluated!");
3145 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3146 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3147 Result = EvalResult.Val.getInt();
3148 return true;
3149}