blob: fdcff0a4dafac85a21c1399b23480dd8208b6d39 [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 {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000105 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCallefdb83e2010-05-07 21:00:08 +0000109 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.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000227 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000228 bool ignored;
Jeffrey Yasskin3e1ef782011-07-15 17:03:07 +0000229 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
230 return Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000231}
232
Mike Stump1eb44332009-09-09 15:08:12 +0000233static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000234 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000235 bool ignored;
236 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000237 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000238 APFloat::rmNearestTiesToEven, &ignored);
239 return Result;
240}
241
Mike Stump1eb44332009-09-09 15:08:12 +0000242static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000243 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000244 unsigned DestWidth = Ctx.getIntWidth(DestType);
245 APSInt Result = Value;
246 // Figure out if this is a truncate, extend or noop cast.
247 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +0000248 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000249 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000250 return Result;
251}
252
Mike Stump1eb44332009-09-09 15:08:12 +0000253static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000254 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000255
256 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
257 Result.convertFromAPInt(Value, Value.isSigned(),
258 APFloat::rmNearestTiesToEven);
259 return Result;
260}
261
Mike Stumpc4c90452009-10-27 22:09:17 +0000262namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000263class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000264 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stumpc4c90452009-10-27 22:09:17 +0000265 EvalInfo &Info;
266public:
267
268 HasSideEffect(EvalInfo &info) : Info(info) {}
269
270 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000271 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000272 return true;
273 }
274
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000275 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
276 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000277 return Visit(E->getResultExpr());
278 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000279 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000280 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000281 return true;
282 return false;
283 }
John McCallf85e1932011-06-15 23:02:42 +0000284 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
285 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
286 return true;
287 return false;
288 }
289 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
290 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
291 return true;
292 return false;
293 }
294
Mike Stumpc4c90452009-10-27 22:09:17 +0000295 // We don't want to evaluate BlockExprs multiple times, as they generate
296 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000297 bool VisitBlockExpr(const BlockExpr *E) { return true; }
298 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
299 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000300 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000301 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
302 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
303 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
304 bool VisitStringLiteral(const StringLiteral *E) { return false; }
305 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
306 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000307 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000308 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000309 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000310 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000311 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000312 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
313 bool VisitBinAssign(const BinaryOperator *E) { return true; }
314 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
315 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +0000316 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000317 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
318 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
319 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
321 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000322 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000323 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000324 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000325 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000326 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000327
328 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000329 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +0000330 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
331 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000332 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000333 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000334 return false;
335 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000336
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000337 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000338};
339
John McCall56ca35d2011-02-17 10:25:35 +0000340class OpaqueValueEvaluation {
341 EvalInfo &info;
342 OpaqueValueExpr *opaqueValue;
343
344public:
345 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
346 Expr *value)
347 : info(info), opaqueValue(opaqueValue) {
348
349 // If evaluation fails, fail immediately.
350 if (!Evaluate(info, value)) {
351 this->opaqueValue = 0;
352 return;
353 }
354 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
355 }
356
357 bool hasError() const { return opaqueValue == 0; }
358
359 ~OpaqueValueEvaluation() {
360 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
361 }
362};
363
Mike Stumpc4c90452009-10-27 22:09:17 +0000364} // end anonymous namespace
365
Eli Friedman4efaa272008-11-12 09:44:48 +0000366//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000367// Generic Evaluation
368//===----------------------------------------------------------------------===//
369namespace {
370
371template <class Derived, typename RetTy=void>
372class ExprEvaluatorBase
373 : public ConstStmtVisitor<Derived, RetTy> {
374private:
375 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
376 return static_cast<Derived*>(this)->Success(V, E);
377 }
378 RetTy DerivedError(const Expr *E) {
379 return static_cast<Derived*>(this)->Error(E);
380 }
381
382protected:
383 EvalInfo &Info;
384 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
385 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
386
387public:
388 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
389
390 RetTy VisitStmt(const Stmt *) {
391 assert(0 && "Expression evaluator should not be called on stmts");
392 return DerivedError(0);
393 }
394 RetTy VisitExpr(const Expr *E) {
395 return DerivedError(E);
396 }
397
398 RetTy VisitParenExpr(const ParenExpr *E)
399 { return StmtVisitorTy::Visit(E->getSubExpr()); }
400 RetTy VisitUnaryExtension(const UnaryOperator *E)
401 { return StmtVisitorTy::Visit(E->getSubExpr()); }
402 RetTy VisitUnaryPlus(const UnaryOperator *E)
403 { return StmtVisitorTy::Visit(E->getSubExpr()); }
404 RetTy VisitChooseExpr(const ChooseExpr *E)
405 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
406 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
407 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +0000408 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
409 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000410
411 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
412 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
413 if (opaque.hasError())
414 return DerivedError(E);
415
416 bool cond;
417 if (!HandleConversionToBool(E->getCond(), cond, Info))
418 return DerivedError(E);
419
420 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
421 }
422
423 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
424 bool BoolResult;
425 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
426 return DerivedError(E);
427
428 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
429 return StmtVisitorTy::Visit(EvalExpr);
430 }
431
432 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
433 const APValue *value = Info.getOpaqueValue(E);
434 if (!value)
435 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
436 : DerivedError(E));
437 return DerivedSuccess(*value, E);
438 }
439};
440
441}
442
443//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000444// LValue Evaluation
445//===----------------------------------------------------------------------===//
446namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000447class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000448 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000449 LValue &Result;
450
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000451 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000452 Result.Base = E;
453 Result.Offset = CharUnits::Zero();
454 return true;
455 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000456public:
Mike Stump1eb44332009-09-09 15:08:12 +0000457
John McCallefdb83e2010-05-07 21:00:08 +0000458 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000459 ExprEvaluatorBaseTy(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000460
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000461 bool Success(const APValue &V, const Expr *E) {
462 Result.setFrom(V);
463 return true;
464 }
465 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000466 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000467 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000468
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000469 bool VisitDeclRefExpr(const DeclRefExpr *E);
470 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
471 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
472 bool VisitMemberExpr(const MemberExpr *E);
473 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
474 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
475 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
476 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000477
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000478 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000479 switch (E->getCastKind()) {
480 default:
John McCallefdb83e2010-05-07 21:00:08 +0000481 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000482
John McCall2de56d12010-08-25 11:45:40 +0000483 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000484 return Visit(E->getSubExpr());
485 }
486 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000487 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000488
Eli Friedman4efaa272008-11-12 09:44:48 +0000489};
490} // end anonymous namespace
491
John McCallefdb83e2010-05-07 21:00:08 +0000492static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000493 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000494}
495
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000496bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000497 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000498 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000499 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000500 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000501 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000502 // Reference parameters can refer to anything even if they have an
503 // "initializer" in the form of a default argument.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000504 if (!isa<ParmVarDecl>(VD))
505 // FIXME: Check whether VD might be overridden!
506 if (const Expr *Init = VD->getAnyInitializer())
507 return Visit(Init);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000508 }
509
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000510 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000511}
512
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000513bool
514LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000515 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000516}
517
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000518bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000519 QualType Ty;
520 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000521 if (!EvaluatePointer(E->getBase(), Result, Info))
522 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000523 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000524 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000525 if (!Visit(E->getBase()))
526 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000527 Ty = E->getBase()->getType();
528 }
529
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000530 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000531 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000532
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000533 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000534 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000535 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000536
537 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000538 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000539
Eli Friedman82905742011-07-07 01:54:01 +0000540 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000541 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000542 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000543}
544
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000545bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000546 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000547 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Anders Carlsson3068d112008-11-16 19:01:22 +0000549 APSInt Index;
550 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000551 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000552
Ken Dyck199c3d62010-01-11 17:06:35 +0000553 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000554 Result.Offset += Index.getSExtValue() * ElementSize;
555 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000556}
Eli Friedman4efaa272008-11-12 09:44:48 +0000557
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000558bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000559 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000560}
561
Eli Friedman4efaa272008-11-12 09:44:48 +0000562//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000563// Pointer Evaluation
564//===----------------------------------------------------------------------===//
565
Anders Carlssonc754aa62008-07-08 05:13:58 +0000566namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000567class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000568 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000569 LValue &Result;
570
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000571 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000572 Result.Base = E;
573 Result.Offset = CharUnits::Zero();
574 return true;
575 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000576public:
Mike Stump1eb44332009-09-09 15:08:12 +0000577
John McCallefdb83e2010-05-07 21:00:08 +0000578 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000579 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000580
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000581 bool Success(const APValue &V, const Expr *E) {
582 Result.setFrom(V);
583 return true;
584 }
585 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000586 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000587 }
588
John McCallefdb83e2010-05-07 21:00:08 +0000589 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000590 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000591 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000592 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000593 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000594 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000595 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000596 bool VisitCallExpr(const CallExpr *E);
597 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000598 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000599 return Success(E);
600 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000601 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000602 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000603 { return Success((Expr*)0); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000604 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000605 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000606
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000607 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000608};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000609} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000610
John McCallefdb83e2010-05-07 21:00:08 +0000611static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000612 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000613 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000614}
615
John McCallefdb83e2010-05-07 21:00:08 +0000616bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000617 if (E->getOpcode() != BO_Add &&
618 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000619 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000621 const Expr *PExp = E->getLHS();
622 const Expr *IExp = E->getRHS();
623 if (IExp->getType()->isPointerType())
624 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000625
John McCallefdb83e2010-05-07 21:00:08 +0000626 if (!EvaluatePointer(PExp, Result, Info))
627 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000628
John McCallefdb83e2010-05-07 21:00:08 +0000629 llvm::APSInt Offset;
630 if (!EvaluateInteger(IExp, Offset, Info))
631 return false;
632 int64_t AdditionalOffset
633 = Offset.isSigned() ? Offset.getSExtValue()
634 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000635
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000636 // Compute the new offset in the appropriate width.
637
638 QualType PointeeType =
639 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000640 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000642 // Explicitly handle GNU void* and function pointer arithmetic extensions.
643 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000644 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000645 else
John McCallefdb83e2010-05-07 21:00:08 +0000646 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000647
John McCall2de56d12010-08-25 11:45:40 +0000648 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000649 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000650 else
John McCallefdb83e2010-05-07 21:00:08 +0000651 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000652
John McCallefdb83e2010-05-07 21:00:08 +0000653 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000654}
Eli Friedman4efaa272008-11-12 09:44:48 +0000655
John McCallefdb83e2010-05-07 21:00:08 +0000656bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
657 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000658}
Mike Stump1eb44332009-09-09 15:08:12 +0000659
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000660
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000661bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
662 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000663
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000664 switch (E->getCastKind()) {
665 default:
666 break;
667
John McCall2de56d12010-08-25 11:45:40 +0000668 case CK_NoOp:
669 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000670 case CK_AnyPointerToObjCPointerCast:
671 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000672 return Visit(SubExpr);
673
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000674 case CK_DerivedToBase:
675 case CK_UncheckedDerivedToBase: {
676 LValue BaseLV;
677 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
678 return false;
679
680 // Now figure out the necessary offset to add to the baseLV to get from
681 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000682 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000683
684 QualType Ty = E->getSubExpr()->getType();
685 const CXXRecordDecl *DerivedDecl =
686 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
687
688 for (CastExpr::path_const_iterator PathI = E->path_begin(),
689 PathE = E->path_end(); PathI != PathE; ++PathI) {
690 const CXXBaseSpecifier *Base = *PathI;
691
692 // FIXME: If the base is virtual, we'd need to determine the type of the
693 // most derived class and we don't support that right now.
694 if (Base->isVirtual())
695 return false;
696
697 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
698 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
699
Ken Dyck7c7f8202011-01-26 02:17:08 +0000700 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000701 DerivedDecl = BaseDecl;
702 }
703
704 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000705 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000706 return true;
707 }
708
John McCall404cd162010-11-13 01:35:44 +0000709 case CK_NullToPointer: {
710 Result.Base = 0;
711 Result.Offset = CharUnits::Zero();
712 return true;
713 }
714
John McCall2de56d12010-08-25 11:45:40 +0000715 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000716 APValue Value;
717 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000718 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000719
John McCallefdb83e2010-05-07 21:00:08 +0000720 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000721 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000722 Result.Base = 0;
723 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
724 return true;
725 } else {
726 // Cast is of an lvalue, no need to change value.
727 Result.Base = Value.getLValueBase();
728 Result.Offset = Value.getLValueOffset();
729 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000730 }
731 }
John McCall2de56d12010-08-25 11:45:40 +0000732 case CK_ArrayToPointerDecay:
733 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000734 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000735 }
736
John McCallefdb83e2010-05-07 21:00:08 +0000737 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000738}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000739
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000740bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000741 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000742 Builtin::BI__builtin___CFStringMakeConstantString ||
743 E->isBuiltinCall(Info.Ctx) ==
744 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000745 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000746
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000747 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000748}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000749
750//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000751// Vector Evaluation
752//===----------------------------------------------------------------------===//
753
754namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000755 class VectorExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000756 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman91110ee2009-02-23 04:23:56 +0000757 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000758 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000759
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000760 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000762 APValue Success(const APValue &V, const Expr *E) { return V; }
763 APValue Error(const Expr *E) { return APValue(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Eli Friedman91110ee2009-02-23 04:23:56 +0000765 APValue VisitUnaryReal(const UnaryOperator *E)
766 { return Visit(E->getSubExpr()); }
767 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
768 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000769 APValue VisitCastExpr(const CastExpr* E);
770 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
771 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000772 APValue VisitUnaryImag(const UnaryOperator *E);
773 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000774 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000775 // shufflevector, ExtVectorElementExpr
776 // (Note that these require implementing conversions
777 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000778 };
779} // end anonymous namespace
780
781static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
782 if (!E->getType()->isVectorType())
783 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000784 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000785 return !Result.isUninit();
786}
787
788APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000789 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000790 QualType EltTy = VTy->getElementType();
791 unsigned NElts = VTy->getNumElements();
792 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000793
Nate Begeman59b5da62009-01-18 03:20:47 +0000794 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000795 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000796
Eli Friedman46a52322011-03-25 00:43:55 +0000797 switch (E->getCastKind()) {
798 case CK_VectorSplat: {
799 APValue Result = APValue();
800 if (SETy->isIntegerType()) {
801 APSInt IntResult;
802 if (!EvaluateInteger(SE, IntResult, Info))
803 return APValue();
804 Result = APValue(IntResult);
805 } else if (SETy->isRealFloatingType()) {
806 APFloat F(0.0);
807 if (!EvaluateFloat(SE, F, Info))
808 return APValue();
809 Result = APValue(F);
810 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000811 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000812 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000813
814 // Splat and create vector APValue.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000815 SmallVector<APValue, 4> Elts(NElts, Result);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000816 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000817 }
Eli Friedman46a52322011-03-25 00:43:55 +0000818 case CK_BitCast: {
819 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000820 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000821
Eli Friedman46a52322011-03-25 00:43:55 +0000822 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000823 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000824
Eli Friedman46a52322011-03-25 00:43:55 +0000825 APSInt Init;
826 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000827 return APValue();
828
Eli Friedman46a52322011-03-25 00:43:55 +0000829 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
830 "Vectors must be composed of ints or floats");
831
Chris Lattner5f9e2722011-07-23 10:55:15 +0000832 SmallVector<APValue, 4> Elts;
Eli Friedman46a52322011-03-25 00:43:55 +0000833 for (unsigned i = 0; i != NElts; ++i) {
834 APSInt Tmp = Init.extOrTrunc(EltWidth);
835
836 if (EltTy->isIntegerType())
837 Elts.push_back(APValue(Tmp));
838 else
839 Elts.push_back(APValue(APFloat(Tmp)));
840
841 Init >>= EltWidth;
842 }
843 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000844 }
Eli Friedman46a52322011-03-25 00:43:55 +0000845 case CK_LValueToRValue:
846 case CK_NoOp:
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000847 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000848 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000849 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000850 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000851}
852
Mike Stump1eb44332009-09-09 15:08:12 +0000853APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000854VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000855 return this->Visit(E->getInitializer());
Nate Begeman59b5da62009-01-18 03:20:47 +0000856}
857
Mike Stump1eb44332009-09-09 15:08:12 +0000858APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000859VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000860 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000861 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000862 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Nate Begeman59b5da62009-01-18 03:20:47 +0000864 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +0000865 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +0000866
John McCalla7d6c222010-06-11 17:54:15 +0000867 // If a vector is initialized with a single element, that value
868 // becomes every element of the vector, not just the first.
869 // This is the behavior described in the IBM AltiVec documentation.
870 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000871
872 // Handle the case where the vector is initialized by a another
873 // vector (OpenCL 6.1.6).
874 if (E->getInit(0)->getType()->isVectorType())
875 return this->Visit(const_cast<Expr*>(E->getInit(0)));
876
John McCalla7d6c222010-06-11 17:54:15 +0000877 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000878 if (EltTy->isIntegerType()) {
879 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000880 if (!EvaluateInteger(E->getInit(0), sInt, Info))
881 return APValue();
882 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000883 } else {
884 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000885 if (!EvaluateFloat(E->getInit(0), f, Info))
886 return APValue();
887 InitValue = APValue(f);
888 }
889 for (unsigned i = 0; i < NumElements; i++) {
890 Elements.push_back(InitValue);
891 }
892 } else {
893 for (unsigned i = 0; i < NumElements; i++) {
894 if (EltTy->isIntegerType()) {
895 llvm::APSInt sInt(32);
896 if (i < NumInits) {
897 if (!EvaluateInteger(E->getInit(i), sInt, Info))
898 return APValue();
899 } else {
900 sInt = Info.Ctx.MakeIntValue(0, EltTy);
901 }
902 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000903 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000904 llvm::APFloat f(0.0);
905 if (i < NumInits) {
906 if (!EvaluateFloat(E->getInit(i), f, Info))
907 return APValue();
908 } else {
909 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
910 }
911 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000912 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000913 }
914 }
915 return APValue(&Elements[0], Elements.size());
916}
917
Mike Stump1eb44332009-09-09 15:08:12 +0000918APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000919VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000920 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000921 QualType EltTy = VT->getElementType();
922 APValue ZeroElement;
923 if (EltTy->isIntegerType())
924 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
925 else
926 ZeroElement =
927 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
928
Chris Lattner5f9e2722011-07-23 10:55:15 +0000929 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Eli Friedman91110ee2009-02-23 04:23:56 +0000930 return APValue(&Elements[0], Elements.size());
931}
932
Eli Friedman91110ee2009-02-23 04:23:56 +0000933APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
934 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
935 Info.EvalResult.HasSideEffects = true;
936 return GetZeroVector(E->getType());
937}
938
Nate Begeman59b5da62009-01-18 03:20:47 +0000939//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000940// Integer Evaluation
941//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000942
943namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000944class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000945 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000946 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000947public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000948 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000949 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000950
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000951 bool Success(const llvm::APSInt &SI, const Expr *E) {
952 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000953 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000954 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000955 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000956 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000957 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000958 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000959 return true;
960 }
961
Daniel Dunbar131eb432009-02-19 09:06:44 +0000962 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000963 assert(E->getType()->isIntegralOrEnumerationType() &&
964 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000965 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000966 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000967 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +0000968 Result.getInt().setIsUnsigned(
969 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000970 return true;
971 }
972
973 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000974 assert(E->getType()->isIntegralOrEnumerationType() &&
975 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000976 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000977 return true;
978 }
979
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000980 bool Success(CharUnits Size, const Expr *E) {
981 return Success(Size.getQuantity(), E);
982 }
983
984
Anders Carlsson82206e22008-11-30 18:14:57 +0000985 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000986 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000987 if (Info.EvalResult.Diag == 0) {
988 Info.EvalResult.DiagLoc = L;
989 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000990 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000991 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000992 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000993 }
Mike Stump1eb44332009-09-09 15:08:12 +0000994
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000995 bool Success(const APValue &V, const Expr *E) {
996 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +0000997 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000998 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000999 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +00001000 }
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001002 //===--------------------------------------------------------------------===//
1003 // Visitor Methods
1004 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001005
Chris Lattner4c4867e2008-07-12 00:38:25 +00001006 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001007 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001008 }
1009 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001010 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001011 }
Eli Friedman04309752009-11-24 05:28:59 +00001012
1013 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1014 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001015 if (CheckReferencedDecl(E, E->getDecl()))
1016 return true;
1017
1018 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001019 }
1020 bool VisitMemberExpr(const MemberExpr *E) {
1021 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1022 // Conservatively assume a MemberExpr will have side-effects
1023 Info.EvalResult.HasSideEffects = true;
1024 return true;
1025 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001026
1027 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001028 }
1029
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001030 bool VisitCallExpr(const 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);
Anders Carlsson06a36752008-07-08 05:49:43 +00001034
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001035 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001036 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001037
Anders Carlsson3068d112008-11-16 19:01:22 +00001038 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001039 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001040 }
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Anders Carlsson3f704562008-12-21 22:39:40 +00001042 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001043 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001044 }
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Douglas Gregored8abf12010-07-08 06:14:04 +00001046 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001047 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001048 }
1049
Eli Friedman664a1042009-02-27 04:45:43 +00001050 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1051 return Success(0, E);
1052 }
1053
Sebastian Redl64b45f72009-01-05 20:52:13 +00001054 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001055 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001056 }
1057
Francois Pichet6ad6f282010-12-07 00:08:36 +00001058 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1059 return Success(E->getValue(), E);
1060 }
1061
John Wiegley21ff2e52011-04-28 00:16:57 +00001062 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1063 return Success(E->getValue(), E);
1064 }
1065
John Wiegley55262202011-04-25 06:54:41 +00001066 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1067 return Success(E->getValue(), E);
1068 }
1069
Eli Friedman722c7172009-02-28 03:59:05 +00001070 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001071 bool VisitUnaryImag(const UnaryOperator *E);
1072
Sebastian Redl295995c2010-09-10 20:55:47 +00001073 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001074 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1075
Chris Lattnerfcee0012008-07-11 21:24:13 +00001076private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001077 CharUnits GetAlignOfExpr(const Expr *E);
1078 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001079 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001080 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001081 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001082};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001083} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001084
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001085static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001086 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001087 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001088}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001089
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001090static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001091 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001092
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001093 APValue Val;
1094 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1095 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001096 Result = Val.getInt();
1097 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001098}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001099
Eli Friedman04309752009-11-24 05:28:59 +00001100bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001101 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001102 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001103 // Check for signedness/width mismatches between E type and ECD value.
1104 bool SameSign = (ECD->getInitVal().isSigned()
1105 == E->getType()->isSignedIntegerOrEnumerationType());
1106 bool SameWidth = (ECD->getInitVal().getBitWidth()
1107 == Info.Ctx.getIntWidth(E->getType()));
1108 if (SameSign && SameWidth)
1109 return Success(ECD->getInitVal(), E);
1110 else {
1111 // Get rid of mismatch (otherwise Success assertions will fail)
1112 // by computing a new value matching the type of E.
1113 llvm::APSInt Val = ECD->getInitVal();
1114 if (!SameSign)
1115 Val.setIsSigned(!ECD->getInitVal().isSigned());
1116 if (!SameWidth)
1117 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1118 return Success(Val, E);
1119 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001120 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001121
1122 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001123 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001124 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1125 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001126
1127 if (isa<ParmVarDecl>(D))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001128 return false;
Anders Carlssonf6b60252010-02-03 21:58:41 +00001129
Eli Friedman04309752009-11-24 05:28:59 +00001130 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001131 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001132 if (APValue *V = VD->getEvaluatedValue()) {
1133 if (V->isInt())
1134 return Success(V->getInt(), E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001135 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001136 }
1137
1138 if (VD->isEvaluatingValue())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001139 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001140
1141 VD->setEvaluatingValue();
1142
Eli Friedmana7dedf72010-09-06 00:10:32 +00001143 Expr::EvalResult EResult;
1144 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1145 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001146 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001147 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001148 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001149 return true;
1150 }
1151
Eli Friedmanc0131182009-12-03 20:31:57 +00001152 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001153 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001154 }
1155 }
1156
Chris Lattner4c4867e2008-07-12 00:38:25 +00001157 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001158 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001159}
1160
Chris Lattnera4d55d82008-10-06 06:40:35 +00001161/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1162/// as GCC.
1163static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1164 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001165 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001166 enum gcc_type_class {
1167 no_type_class = -1,
1168 void_type_class, integer_type_class, char_type_class,
1169 enumeral_type_class, boolean_type_class,
1170 pointer_type_class, reference_type_class, offset_type_class,
1171 real_type_class, complex_type_class,
1172 function_type_class, method_type_class,
1173 record_type_class, union_type_class,
1174 array_type_class, string_type_class,
1175 lang_type_class
1176 };
Mike Stump1eb44332009-09-09 15:08:12 +00001177
1178 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001179 // ideal, however it is what gcc does.
1180 if (E->getNumArgs() == 0)
1181 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001182
Chris Lattnera4d55d82008-10-06 06:40:35 +00001183 QualType ArgTy = E->getArg(0)->getType();
1184 if (ArgTy->isVoidType())
1185 return void_type_class;
1186 else if (ArgTy->isEnumeralType())
1187 return enumeral_type_class;
1188 else if (ArgTy->isBooleanType())
1189 return boolean_type_class;
1190 else if (ArgTy->isCharType())
1191 return string_type_class; // gcc doesn't appear to use char_type_class
1192 else if (ArgTy->isIntegerType())
1193 return integer_type_class;
1194 else if (ArgTy->isPointerType())
1195 return pointer_type_class;
1196 else if (ArgTy->isReferenceType())
1197 return reference_type_class;
1198 else if (ArgTy->isRealType())
1199 return real_type_class;
1200 else if (ArgTy->isComplexType())
1201 return complex_type_class;
1202 else if (ArgTy->isFunctionType())
1203 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001204 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001205 return record_type_class;
1206 else if (ArgTy->isUnionType())
1207 return union_type_class;
1208 else if (ArgTy->isArrayType())
1209 return array_type_class;
1210 else if (ArgTy->isUnionType())
1211 return union_type_class;
1212 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1213 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1214 return -1;
1215}
1216
John McCall42c8f872010-05-10 23:27:23 +00001217/// Retrieves the "underlying object type" of the given expression,
1218/// as used by __builtin_object_size.
1219QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1220 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1221 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1222 return VD->getType();
1223 } else if (isa<CompoundLiteralExpr>(E)) {
1224 return E->getType();
1225 }
1226
1227 return QualType();
1228}
1229
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001230bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001231 // TODO: Perhaps we should let LLVM lower this?
1232 LValue Base;
1233 if (!EvaluatePointer(E->getArg(0), Base, Info))
1234 return false;
1235
1236 // If we can prove the base is null, lower to zero now.
1237 const Expr *LVBase = Base.getLValueBase();
1238 if (!LVBase) return Success(0, E);
1239
1240 QualType T = GetObjectType(LVBase);
1241 if (T.isNull() ||
1242 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001243 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001244 T->isVariablyModifiedType() ||
1245 T->isDependentType())
1246 return false;
1247
1248 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1249 CharUnits Offset = Base.getLValueOffset();
1250
1251 if (!Offset.isNegative() && Offset <= Size)
1252 Size -= Offset;
1253 else
1254 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001255 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001256}
1257
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001258bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001259 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001260 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001261 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001262
1263 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001264 if (TryEvaluateBuiltinObjectSize(E))
1265 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001266
Eric Christopherb2aaf512010-01-19 22:58:35 +00001267 // If evaluating the argument has side-effects we can't determine
1268 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001269 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001270 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001271 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001272 return Success(0, E);
1273 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001274
Mike Stump64eda9e2009-10-26 18:35:08 +00001275 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1276 }
1277
Chris Lattner019f4e82008-10-06 05:28:25 +00001278 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001279 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001281 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001282 // __builtin_constant_p always has one operand: it returns true if that
1283 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001284 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001285
1286 case Builtin::BI__builtin_eh_return_data_regno: {
1287 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1288 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1289 return Success(Operand, E);
1290 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001291
1292 case Builtin::BI__builtin_expect:
1293 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001294
1295 case Builtin::BIstrlen:
1296 case Builtin::BI__builtin_strlen:
1297 // As an extension, we support strlen() and __builtin_strlen() as constant
1298 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001299 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001300 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1301 // The string literal may have embedded null characters. Find the first
1302 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001303 StringRef Str = S->getString();
1304 StringRef::size_type Pos = Str.find(0);
1305 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00001306 Str = Str.substr(0, Pos);
1307
1308 return Success(Str.size(), E);
1309 }
1310
1311 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001312 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001313}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001314
Chris Lattnerb542afe2008-07-11 19:10:17 +00001315bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001316 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001317 if (!Visit(E->getRHS()))
1318 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001319
Eli Friedman33ef1452009-02-26 10:19:36 +00001320 // If we can't evaluate the LHS, it might have side effects;
1321 // conservatively mark it.
1322 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1323 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001324
Anders Carlsson027f62e2008-12-01 02:07:06 +00001325 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001326 }
1327
1328 if (E->isLogicalOp()) {
1329 // These need to be handled specially because the operands aren't
1330 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001331 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001333 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001334 // We were able to evaluate the LHS, see if we can get away with not
1335 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001336 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001337 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001338
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001339 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001340 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001341 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001342 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001343 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001344 }
1345 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001346 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001347 // We can't evaluate the LHS; however, sometimes the result
1348 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001349 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1350 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001351 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001352 // must have had side effects.
1353 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001354
1355 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001356 }
1357 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001358 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001359
Eli Friedmana6afa762008-11-13 06:09:17 +00001360 return false;
1361 }
1362
Anders Carlsson286f85e2008-11-16 07:17:21 +00001363 QualType LHSTy = E->getLHS()->getType();
1364 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001365
1366 if (LHSTy->isAnyComplexType()) {
1367 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001368 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001369
1370 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1371 return false;
1372
1373 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1374 return false;
1375
1376 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001377 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001378 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001379 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001380 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1381
John McCall2de56d12010-08-25 11:45:40 +00001382 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001383 return Success((CR_r == APFloat::cmpEqual &&
1384 CR_i == APFloat::cmpEqual), E);
1385 else {
John McCall2de56d12010-08-25 11:45:40 +00001386 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001387 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001388 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001389 CR_r == APFloat::cmpLessThan ||
1390 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001391 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001392 CR_i == APFloat::cmpLessThan ||
1393 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001394 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001395 } else {
John McCall2de56d12010-08-25 11:45:40 +00001396 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001397 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1398 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1399 else {
John McCall2de56d12010-08-25 11:45:40 +00001400 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001401 "Invalid compex comparison.");
1402 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1403 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1404 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001405 }
1406 }
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Anders Carlsson286f85e2008-11-16 07:17:21 +00001408 if (LHSTy->isRealFloatingType() &&
1409 RHSTy->isRealFloatingType()) {
1410 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Anders Carlsson286f85e2008-11-16 07:17:21 +00001412 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1413 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Anders Carlsson286f85e2008-11-16 07:17:21 +00001415 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1416 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Anders Carlsson286f85e2008-11-16 07:17:21 +00001418 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001419
Anders Carlsson286f85e2008-11-16 07:17:21 +00001420 switch (E->getOpcode()) {
1421 default:
1422 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001423 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001424 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001425 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001426 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001427 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001428 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001429 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001430 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001431 E);
John McCall2de56d12010-08-25 11:45:40 +00001432 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001433 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001434 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001435 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001436 || CR == APFloat::cmpLessThan
1437 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001438 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001441 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001442 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001443 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001444 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1445 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001446
John McCallefdb83e2010-05-07 21:00:08 +00001447 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001448 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1449 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001450
Eli Friedman5bc86102009-06-14 02:17:33 +00001451 // Reject any bases from the normal codepath; we special-case comparisons
1452 // to null.
1453 if (LHSValue.getLValueBase()) {
1454 if (!E->isEqualityOp())
1455 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001456 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001457 return false;
1458 bool bres;
1459 if (!EvalPointerValueAsBool(LHSValue, bres))
1460 return false;
John McCall2de56d12010-08-25 11:45:40 +00001461 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001462 } else if (RHSValue.getLValueBase()) {
1463 if (!E->isEqualityOp())
1464 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001465 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001466 return false;
1467 bool bres;
1468 if (!EvalPointerValueAsBool(RHSValue, bres))
1469 return false;
John McCall2de56d12010-08-25 11:45:40 +00001470 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001471 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001472
John McCall2de56d12010-08-25 11:45:40 +00001473 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001474 QualType Type = E->getLHS()->getType();
1475 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001476
Ken Dycka7305832010-01-15 12:37:54 +00001477 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001478 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001479 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001480
Ken Dycka7305832010-01-15 12:37:54 +00001481 CharUnits Diff = LHSValue.getLValueOffset() -
1482 RHSValue.getLValueOffset();
1483 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001484 }
1485 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001486 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001487 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001488 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001489 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1490 }
1491 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001492 }
1493 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001494 if (!LHSTy->isIntegralOrEnumerationType() ||
1495 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001496 // We can't continue from here for non-integral types, and they
1497 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001498 return false;
1499 }
1500
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001501 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001502 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001503 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001504
Eli Friedman42edd0d2009-03-24 01:14:50 +00001505 APValue RHSVal;
1506 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001507 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001508
1509 // Handle cases like (unsigned long)&a + 4.
1510 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001511 CharUnits Offset = Result.getLValueOffset();
1512 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1513 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001514 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001515 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001516 else
Ken Dycka7305832010-01-15 12:37:54 +00001517 Offset -= AdditionalOffset;
1518 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001519 return true;
1520 }
1521
1522 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001523 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001524 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001525 CharUnits Offset = RHSVal.getLValueOffset();
1526 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1527 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001528 return true;
1529 }
1530
1531 // All the following cases expect both operands to be an integer
1532 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001533 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001534
Eli Friedman42edd0d2009-03-24 01:14:50 +00001535 APSInt& RHS = RHSVal.getInt();
1536
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001537 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001538 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001539 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001540 case BO_Mul: return Success(Result.getInt() * RHS, E);
1541 case BO_Add: return Success(Result.getInt() + RHS, E);
1542 case BO_Sub: return Success(Result.getInt() - RHS, E);
1543 case BO_And: return Success(Result.getInt() & RHS, E);
1544 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1545 case BO_Or: return Success(Result.getInt() | RHS, E);
1546 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001547 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001548 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001549 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001550 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001551 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001552 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001553 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001554 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001555 // During constant-folding, a negative shift is an opposite shift.
1556 if (RHS.isSigned() && RHS.isNegative()) {
1557 RHS = -RHS;
1558 goto shift_right;
1559 }
1560
1561 shift_left:
1562 unsigned SA
1563 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001564 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001565 }
John McCall2de56d12010-08-25 11:45:40 +00001566 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001567 // During constant-folding, a negative shift is an opposite shift.
1568 if (RHS.isSigned() && RHS.isNegative()) {
1569 RHS = -RHS;
1570 goto shift_left;
1571 }
1572
1573 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001574 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001575 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1576 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001577 }
Mike Stump1eb44332009-09-09 15:08:12 +00001578
John McCall2de56d12010-08-25 11:45:40 +00001579 case BO_LT: return Success(Result.getInt() < RHS, E);
1580 case BO_GT: return Success(Result.getInt() > RHS, E);
1581 case BO_LE: return Success(Result.getInt() <= RHS, E);
1582 case BO_GE: return Success(Result.getInt() >= RHS, E);
1583 case BO_EQ: return Success(Result.getInt() == RHS, E);
1584 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001585 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001586}
1587
Ken Dyck8b752f12010-01-27 17:10:57 +00001588CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001589 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1590 // the result is the size of the referenced type."
1591 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1592 // result shall be the alignment of the referenced type."
1593 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1594 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00001595
1596 // __alignof is defined to return the preferred alignment.
1597 return Info.Ctx.toCharUnitsFromBits(
1598 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001599}
1600
Ken Dyck8b752f12010-01-27 17:10:57 +00001601CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001602 E = E->IgnoreParens();
1603
1604 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001605 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001606 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001607 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1608 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001609
Chris Lattneraf707ab2009-01-24 21:53:27 +00001610 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001611 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1612 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001613
Chris Lattnere9feb472009-01-24 21:09:06 +00001614 return GetAlignOfType(E->getType());
1615}
1616
1617
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001618/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1619/// a result as the expression's type.
1620bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1621 const UnaryExprOrTypeTraitExpr *E) {
1622 switch(E->getKind()) {
1623 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001624 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001625 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001626 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001627 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001628 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001629
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001630 case UETT_VecStep: {
1631 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001632
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001633 if (Ty->isVectorType()) {
1634 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001635
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001636 // The vec_step built-in functions that take a 3-component
1637 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1638 if (n == 3)
1639 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001640
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001641 return Success(n, E);
1642 } else
1643 return Success(1, E);
1644 }
1645
1646 case UETT_SizeOf: {
1647 QualType SrcTy = E->getTypeOfArgument();
1648 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1649 // the result is the size of the referenced type."
1650 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1651 // result shall be the alignment of the referenced type."
1652 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1653 SrcTy = Ref->getPointeeType();
1654
1655 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1656 // extension.
1657 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1658 return Success(1, E);
1659
1660 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1661 if (!SrcTy->isConstantSizeType())
1662 return false;
1663
1664 // Get information about the size.
1665 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1666 }
1667 }
1668
1669 llvm_unreachable("unknown expr/type trait");
1670 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001671}
1672
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001673bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001674 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001675 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001676 if (n == 0)
1677 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001678 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001679 for (unsigned i = 0; i != n; ++i) {
1680 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1681 switch (ON.getKind()) {
1682 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001683 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001684 APSInt IdxResult;
1685 if (!EvaluateInteger(Idx, IdxResult, Info))
1686 return false;
1687 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1688 if (!AT)
1689 return false;
1690 CurrentType = AT->getElementType();
1691 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1692 Result += IdxResult.getSExtValue() * ElementSize;
1693 break;
1694 }
1695
1696 case OffsetOfExpr::OffsetOfNode::Field: {
1697 FieldDecl *MemberDecl = ON.getField();
1698 const RecordType *RT = CurrentType->getAs<RecordType>();
1699 if (!RT)
1700 return false;
1701 RecordDecl *RD = RT->getDecl();
1702 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001703 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001704 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001705 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001706 CurrentType = MemberDecl->getType().getNonReferenceType();
1707 break;
1708 }
1709
1710 case OffsetOfExpr::OffsetOfNode::Identifier:
1711 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001712 return false;
1713
1714 case OffsetOfExpr::OffsetOfNode::Base: {
1715 CXXBaseSpecifier *BaseSpec = ON.getBase();
1716 if (BaseSpec->isVirtual())
1717 return false;
1718
1719 // Find the layout of the class whose base we are looking into.
1720 const RecordType *RT = CurrentType->getAs<RecordType>();
1721 if (!RT)
1722 return false;
1723 RecordDecl *RD = RT->getDecl();
1724 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1725
1726 // Find the base class itself.
1727 CurrentType = BaseSpec->getType();
1728 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1729 if (!BaseRT)
1730 return false;
1731
1732 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001733 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001734 break;
1735 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001736 }
1737 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001738 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001739}
1740
Chris Lattnerb542afe2008-07-11 19:10:17 +00001741bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001742 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001743 // LNot's operand isn't necessarily an integer, so we handle it specially.
1744 bool bres;
1745 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1746 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001747 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001748 }
1749
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001750 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001751 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001752 return false;
1753
Chris Lattner87eae5e2008-07-11 22:52:41 +00001754 // Get the operand value into 'Result'.
1755 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001756 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001757
Chris Lattner75a48812008-07-11 22:15:16 +00001758 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001759 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001760 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1761 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001762 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001763 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001764 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1765 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001766 return true;
John McCall2de56d12010-08-25 11:45:40 +00001767 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001768 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001769 return true;
John McCall2de56d12010-08-25 11:45:40 +00001770 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001771 if (!Result.isInt()) return false;
1772 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001773 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001774 if (!Result.isInt()) return false;
1775 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001776 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001777}
Mike Stump1eb44332009-09-09 15:08:12 +00001778
Chris Lattner732b2232008-07-12 01:15:53 +00001779/// HandleCast - This is used to evaluate implicit or explicit casts where the
1780/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001781bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1782 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001783 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001784 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001785
Eli Friedman46a52322011-03-25 00:43:55 +00001786 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001787 case CK_BaseToDerived:
1788 case CK_DerivedToBase:
1789 case CK_UncheckedDerivedToBase:
1790 case CK_Dynamic:
1791 case CK_ToUnion:
1792 case CK_ArrayToPointerDecay:
1793 case CK_FunctionToPointerDecay:
1794 case CK_NullToPointer:
1795 case CK_NullToMemberPointer:
1796 case CK_BaseToDerivedMemberPointer:
1797 case CK_DerivedToBaseMemberPointer:
1798 case CK_ConstructorConversion:
1799 case CK_IntegralToPointer:
1800 case CK_ToVoid:
1801 case CK_VectorSplat:
1802 case CK_IntegralToFloating:
1803 case CK_FloatingCast:
1804 case CK_AnyPointerToObjCPointerCast:
1805 case CK_AnyPointerToBlockPointerCast:
1806 case CK_ObjCObjectLValueCast:
1807 case CK_FloatingRealToComplex:
1808 case CK_FloatingComplexToReal:
1809 case CK_FloatingComplexCast:
1810 case CK_FloatingComplexToIntegralComplex:
1811 case CK_IntegralRealToComplex:
1812 case CK_IntegralComplexCast:
1813 case CK_IntegralComplexToFloatingComplex:
1814 llvm_unreachable("invalid cast kind for integral value");
1815
Eli Friedmane50c2972011-03-25 19:07:11 +00001816 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001817 case CK_Dependent:
1818 case CK_GetObjCProperty:
1819 case CK_LValueBitCast:
1820 case CK_UserDefinedConversion:
John McCallf85e1932011-06-15 23:02:42 +00001821 case CK_ObjCProduceObject:
1822 case CK_ObjCConsumeObject:
John McCall7e5e5f42011-07-07 06:58:02 +00001823 case CK_ObjCReclaimReturnedObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001824 return false;
1825
1826 case CK_LValueToRValue:
1827 case CK_NoOp:
1828 return Visit(E->getSubExpr());
1829
1830 case CK_MemberPointerToBoolean:
1831 case CK_PointerToBoolean:
1832 case CK_IntegralToBoolean:
1833 case CK_FloatingToBoolean:
1834 case CK_FloatingComplexToBoolean:
1835 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001836 bool BoolResult;
1837 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1838 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001839 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001840 }
1841
Eli Friedman46a52322011-03-25 00:43:55 +00001842 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001843 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001844 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001845
Eli Friedmanbe265702009-02-20 01:15:07 +00001846 if (!Result.isInt()) {
1847 // Only allow casts of lvalues if they are lossless.
1848 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1849 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001850
Daniel Dunbardd211642009-02-19 22:24:01 +00001851 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001852 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001853 }
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Eli Friedman46a52322011-03-25 00:43:55 +00001855 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001856 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001857 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001858 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001859
Daniel Dunbardd211642009-02-19 22:24:01 +00001860 if (LV.getLValueBase()) {
1861 // Only allow based lvalue casts if they are lossless.
1862 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1863 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001864
John McCallefdb83e2010-05-07 21:00:08 +00001865 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001866 return true;
1867 }
1868
Ken Dycka7305832010-01-15 12:37:54 +00001869 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1870 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001871 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001872 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001873
Eli Friedman46a52322011-03-25 00:43:55 +00001874 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001875 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001876 if (!EvaluateComplex(SubExpr, C, Info))
1877 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001878 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001879 }
Eli Friedman2217c872009-02-22 11:46:18 +00001880
Eli Friedman46a52322011-03-25 00:43:55 +00001881 case CK_FloatingToIntegral: {
1882 APFloat F(0.0);
1883 if (!EvaluateFloat(SubExpr, F, Info))
1884 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001885
Eli Friedman46a52322011-03-25 00:43:55 +00001886 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1887 }
1888 }
Mike Stump1eb44332009-09-09 15:08:12 +00001889
Eli Friedman46a52322011-03-25 00:43:55 +00001890 llvm_unreachable("unknown cast resulting in integral value");
1891 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001892}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001893
Eli Friedman722c7172009-02-28 03:59:05 +00001894bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1895 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001896 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001897 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1898 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1899 return Success(LV.getComplexIntReal(), E);
1900 }
1901
1902 return Visit(E->getSubExpr());
1903}
1904
Eli Friedman664a1042009-02-27 04:45:43 +00001905bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001906 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001907 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001908 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1909 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1910 return Success(LV.getComplexIntImag(), E);
1911 }
1912
Eli Friedman664a1042009-02-27 04:45:43 +00001913 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1914 Info.EvalResult.HasSideEffects = true;
1915 return Success(0, E);
1916}
1917
Douglas Gregoree8aff02011-01-04 17:33:58 +00001918bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1919 return Success(E->getPackLength(), E);
1920}
1921
Sebastian Redl295995c2010-09-10 20:55:47 +00001922bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1923 return Success(E->getValue(), E);
1924}
1925
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001926//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001927// Float Evaluation
1928//===----------------------------------------------------------------------===//
1929
1930namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001931class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001932 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001933 APFloat &Result;
1934public:
1935 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001936 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001937
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001938 bool Success(const APValue &V, const Expr *e) {
1939 Result = V.getFloat();
1940 return true;
1941 }
1942 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001943 return false;
1944 }
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);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001951 bool VisitCastExpr(const CastExpr *E);
1952 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001953
John McCallabd3a852010-05-07 22:08:54 +00001954 bool VisitUnaryReal(const UnaryOperator *E);
1955 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001956
John McCall189d6ef2010-10-09 01:34:31 +00001957 bool VisitDeclRefExpr(const DeclRefExpr *E);
1958
John McCallabd3a852010-05-07 22:08:54 +00001959 // FIXME: Missing: array subscript of vector, member of vector,
1960 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001961};
1962} // end anonymous namespace
1963
1964static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001965 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001966 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001967}
1968
Jay Foad4ba2a172011-01-12 09:06:06 +00001969static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001970 QualType ResultTy,
1971 const Expr *Arg,
1972 bool SNaN,
1973 llvm::APFloat &Result) {
1974 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1975 if (!S) return false;
1976
1977 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1978
1979 llvm::APInt fill;
1980
1981 // Treat empty strings as if they were zero.
1982 if (S->getString().empty())
1983 fill = llvm::APInt(32, 0);
1984 else if (S->getString().getAsInteger(0, fill))
1985 return false;
1986
1987 if (SNaN)
1988 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1989 else
1990 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1991 return true;
1992}
1993
Chris Lattner019f4e82008-10-06 05:28:25 +00001994bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001995 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001996 default:
1997 return ExprEvaluatorBaseTy::VisitCallExpr(E);
1998
Chris Lattner019f4e82008-10-06 05:28:25 +00001999 case Builtin::BI__builtin_huge_val:
2000 case Builtin::BI__builtin_huge_valf:
2001 case Builtin::BI__builtin_huge_vall:
2002 case Builtin::BI__builtin_inf:
2003 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002004 case Builtin::BI__builtin_infl: {
2005 const llvm::fltSemantics &Sem =
2006 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002007 Result = llvm::APFloat::getInf(Sem);
2008 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002009 }
Mike Stump1eb44332009-09-09 15:08:12 +00002010
John McCalldb7b72a2010-02-28 13:00:19 +00002011 case Builtin::BI__builtin_nans:
2012 case Builtin::BI__builtin_nansf:
2013 case Builtin::BI__builtin_nansl:
2014 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2015 true, Result);
2016
Chris Lattner9e621712008-10-06 06:31:58 +00002017 case Builtin::BI__builtin_nan:
2018 case Builtin::BI__builtin_nanf:
2019 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002020 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002021 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002022 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2023 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002024
2025 case Builtin::BI__builtin_fabs:
2026 case Builtin::BI__builtin_fabsf:
2027 case Builtin::BI__builtin_fabsl:
2028 if (!EvaluateFloat(E->getArg(0), Result, Info))
2029 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002030
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002031 if (Result.isNegative())
2032 Result.changeSign();
2033 return true;
2034
Mike Stump1eb44332009-09-09 15:08:12 +00002035 case Builtin::BI__builtin_copysign:
2036 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002037 case Builtin::BI__builtin_copysignl: {
2038 APFloat RHS(0.);
2039 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2040 !EvaluateFloat(E->getArg(1), RHS, Info))
2041 return false;
2042 Result.copySign(RHS);
2043 return true;
2044 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002045 }
2046}
2047
John McCall189d6ef2010-10-09 01:34:31 +00002048bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002049 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2050 return true;
2051
John McCall189d6ef2010-10-09 01:34:31 +00002052 const Decl *D = E->getDecl();
2053 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2054 const VarDecl *VD = cast<VarDecl>(D);
2055
2056 // Require the qualifiers to be const and not volatile.
2057 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2058 if (!T.isConstQualified() || T.isVolatileQualified())
2059 return false;
2060
2061 const Expr *Init = VD->getAnyInitializer();
2062 if (!Init) return false;
2063
2064 if (APValue *V = VD->getEvaluatedValue()) {
2065 if (V->isFloat()) {
2066 Result = V->getFloat();
2067 return true;
2068 }
2069 return false;
2070 }
2071
2072 if (VD->isEvaluatingValue())
2073 return false;
2074
2075 VD->setEvaluatingValue();
2076
2077 Expr::EvalResult InitResult;
2078 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2079 InitResult.Val.isFloat()) {
2080 // Cache the evaluated value in the variable declaration.
2081 Result = InitResult.Val.getFloat();
2082 VD->setEvaluatedValue(InitResult.Val);
2083 return true;
2084 }
2085
2086 VD->setEvaluatedValue(APValue());
2087 return false;
2088}
2089
John McCallabd3a852010-05-07 22:08:54 +00002090bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002091 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2092 ComplexValue CV;
2093 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2094 return false;
2095 Result = CV.FloatReal;
2096 return true;
2097 }
2098
2099 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002100}
2101
2102bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002103 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2104 ComplexValue CV;
2105 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2106 return false;
2107 Result = CV.FloatImag;
2108 return true;
2109 }
2110
2111 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2112 Info.EvalResult.HasSideEffects = true;
2113 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2114 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002115 return true;
2116}
2117
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002118bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002119 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002120 return false;
2121
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002122 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2123 return false;
2124
2125 switch (E->getOpcode()) {
2126 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002127 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002128 return true;
John McCall2de56d12010-08-25 11:45:40 +00002129 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002130 Result.changeSign();
2131 return true;
2132 }
2133}
Chris Lattner019f4e82008-10-06 05:28:25 +00002134
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002135bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002136 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002137 if (!EvaluateFloat(E->getRHS(), Result, Info))
2138 return false;
2139
2140 // If we can't evaluate the LHS, it might have side effects;
2141 // conservatively mark it.
2142 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2143 Info.EvalResult.HasSideEffects = true;
2144
2145 return true;
2146 }
2147
Anders Carlsson96e93662010-10-31 01:21:47 +00002148 // We can't evaluate pointer-to-member operations.
2149 if (E->isPtrMemOp())
2150 return false;
2151
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002152 // FIXME: Diagnostics? I really don't understand how the warnings
2153 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002154 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002155 if (!EvaluateFloat(E->getLHS(), Result, Info))
2156 return false;
2157 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2158 return false;
2159
2160 switch (E->getOpcode()) {
2161 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002162 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002163 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2164 return true;
John McCall2de56d12010-08-25 11:45:40 +00002165 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002166 Result.add(RHS, APFloat::rmNearestTiesToEven);
2167 return true;
John McCall2de56d12010-08-25 11:45:40 +00002168 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002169 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2170 return true;
John McCall2de56d12010-08-25 11:45:40 +00002171 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002172 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2173 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002174 }
2175}
2176
2177bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2178 Result = E->getValue();
2179 return true;
2180}
2181
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002182bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2183 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002184
Eli Friedman2a523ee2011-03-25 00:54:52 +00002185 switch (E->getCastKind()) {
2186 default:
2187 return false;
2188
2189 case CK_LValueToRValue:
2190 case CK_NoOp:
2191 return Visit(SubExpr);
2192
2193 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002194 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002195 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002196 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002197 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002198 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002199 return true;
2200 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002201
2202 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002203 if (!Visit(SubExpr))
2204 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002205 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2206 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002207 return true;
2208 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002209
Eli Friedman2a523ee2011-03-25 00:54:52 +00002210 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002211 ComplexValue V;
2212 if (!EvaluateComplex(SubExpr, V, Info))
2213 return false;
2214 Result = V.getComplexFloatReal();
2215 return true;
2216 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002217 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002218
2219 return false;
2220}
2221
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002222bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002223 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2224 return true;
2225}
2226
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002227//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002228// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002229//===----------------------------------------------------------------------===//
2230
2231namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002232class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002233 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002234 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002235
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002236public:
John McCallf4cf1a12010-05-07 17:22:02 +00002237 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002238 : ExprEvaluatorBaseTy(info), Result(Result) {}
2239
2240 bool Success(const APValue &V, const Expr *e) {
2241 Result.setFrom(V);
2242 return true;
2243 }
2244 bool Error(const Expr *E) {
2245 return false;
2246 }
Mike Stump1eb44332009-09-09 15:08:12 +00002247
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002248 //===--------------------------------------------------------------------===//
2249 // Visitor Methods
2250 //===--------------------------------------------------------------------===//
2251
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002252 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002253
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002254 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002255
John McCallf4cf1a12010-05-07 17:22:02 +00002256 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002257 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002258 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002259};
2260} // end anonymous namespace
2261
John McCallf4cf1a12010-05-07 17:22:02 +00002262static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2263 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002264 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002265 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002266}
2267
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002268bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2269 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002270
2271 if (SubExpr->getType()->isRealFloatingType()) {
2272 Result.makeComplexFloat();
2273 APFloat &Imag = Result.FloatImag;
2274 if (!EvaluateFloat(SubExpr, Imag, Info))
2275 return false;
2276
2277 Result.FloatReal = APFloat(Imag.getSemantics());
2278 return true;
2279 } else {
2280 assert(SubExpr->getType()->isIntegerType() &&
2281 "Unexpected imaginary literal.");
2282
2283 Result.makeComplexInt();
2284 APSInt &Imag = Result.IntImag;
2285 if (!EvaluateInteger(SubExpr, Imag, Info))
2286 return false;
2287
2288 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2289 return true;
2290 }
2291}
2292
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002293bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002294
John McCall8786da72010-12-14 17:51:41 +00002295 switch (E->getCastKind()) {
2296 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002297 case CK_BaseToDerived:
2298 case CK_DerivedToBase:
2299 case CK_UncheckedDerivedToBase:
2300 case CK_Dynamic:
2301 case CK_ToUnion:
2302 case CK_ArrayToPointerDecay:
2303 case CK_FunctionToPointerDecay:
2304 case CK_NullToPointer:
2305 case CK_NullToMemberPointer:
2306 case CK_BaseToDerivedMemberPointer:
2307 case CK_DerivedToBaseMemberPointer:
2308 case CK_MemberPointerToBoolean:
2309 case CK_ConstructorConversion:
2310 case CK_IntegralToPointer:
2311 case CK_PointerToIntegral:
2312 case CK_PointerToBoolean:
2313 case CK_ToVoid:
2314 case CK_VectorSplat:
2315 case CK_IntegralCast:
2316 case CK_IntegralToBoolean:
2317 case CK_IntegralToFloating:
2318 case CK_FloatingToIntegral:
2319 case CK_FloatingToBoolean:
2320 case CK_FloatingCast:
2321 case CK_AnyPointerToObjCPointerCast:
2322 case CK_AnyPointerToBlockPointerCast:
2323 case CK_ObjCObjectLValueCast:
2324 case CK_FloatingComplexToReal:
2325 case CK_FloatingComplexToBoolean:
2326 case CK_IntegralComplexToReal:
2327 case CK_IntegralComplexToBoolean:
John McCallf85e1932011-06-15 23:02:42 +00002328 case CK_ObjCProduceObject:
2329 case CK_ObjCConsumeObject:
John McCall7e5e5f42011-07-07 06:58:02 +00002330 case CK_ObjCReclaimReturnedObject:
John McCall8786da72010-12-14 17:51:41 +00002331 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002332
John McCall8786da72010-12-14 17:51:41 +00002333 case CK_LValueToRValue:
2334 case CK_NoOp:
2335 return Visit(E->getSubExpr());
2336
2337 case CK_Dependent:
2338 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002339 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002340 case CK_UserDefinedConversion:
2341 return false;
2342
2343 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002344 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002345 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002346 return false;
2347
John McCall8786da72010-12-14 17:51:41 +00002348 Result.makeComplexFloat();
2349 Result.FloatImag = APFloat(Real.getSemantics());
2350 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002351 }
2352
John McCall8786da72010-12-14 17:51:41 +00002353 case CK_FloatingComplexCast: {
2354 if (!Visit(E->getSubExpr()))
2355 return false;
2356
2357 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2358 QualType From
2359 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2360
2361 Result.FloatReal
2362 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2363 Result.FloatImag
2364 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2365 return true;
2366 }
2367
2368 case CK_FloatingComplexToIntegralComplex: {
2369 if (!Visit(E->getSubExpr()))
2370 return false;
2371
2372 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2373 QualType From
2374 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2375 Result.makeComplexInt();
2376 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2377 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2378 return true;
2379 }
2380
2381 case CK_IntegralRealToComplex: {
2382 APSInt &Real = Result.IntReal;
2383 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2384 return false;
2385
2386 Result.makeComplexInt();
2387 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2388 return true;
2389 }
2390
2391 case CK_IntegralComplexCast: {
2392 if (!Visit(E->getSubExpr()))
2393 return false;
2394
2395 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2396 QualType From
2397 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2398
2399 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2400 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2401 return true;
2402 }
2403
2404 case CK_IntegralComplexToFloatingComplex: {
2405 if (!Visit(E->getSubExpr()))
2406 return false;
2407
2408 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2409 QualType From
2410 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2411 Result.makeComplexFloat();
2412 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2413 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2414 return true;
2415 }
2416 }
2417
2418 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002419 return false;
2420}
2421
John McCallf4cf1a12010-05-07 17:22:02 +00002422bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002423 if (E->getOpcode() == BO_Comma) {
2424 if (!Visit(E->getRHS()))
2425 return false;
2426
2427 // If we can't evaluate the LHS, it might have side effects;
2428 // conservatively mark it.
2429 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2430 Info.EvalResult.HasSideEffects = true;
2431
2432 return true;
2433 }
John McCallf4cf1a12010-05-07 17:22:02 +00002434 if (!Visit(E->getLHS()))
2435 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002436
John McCallf4cf1a12010-05-07 17:22:02 +00002437 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002438 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002439 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002440
Daniel Dunbar3f279872009-01-29 01:32:56 +00002441 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2442 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002443 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002444 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002445 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002446 if (Result.isComplexFloat()) {
2447 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2448 APFloat::rmNearestTiesToEven);
2449 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2450 APFloat::rmNearestTiesToEven);
2451 } else {
2452 Result.getComplexIntReal() += RHS.getComplexIntReal();
2453 Result.getComplexIntImag() += RHS.getComplexIntImag();
2454 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002455 break;
John McCall2de56d12010-08-25 11:45:40 +00002456 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002457 if (Result.isComplexFloat()) {
2458 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2459 APFloat::rmNearestTiesToEven);
2460 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2461 APFloat::rmNearestTiesToEven);
2462 } else {
2463 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2464 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2465 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002466 break;
John McCall2de56d12010-08-25 11:45:40 +00002467 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002468 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002469 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002470 APFloat &LHS_r = LHS.getComplexFloatReal();
2471 APFloat &LHS_i = LHS.getComplexFloatImag();
2472 APFloat &RHS_r = RHS.getComplexFloatReal();
2473 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002474
Daniel Dunbar3f279872009-01-29 01:32:56 +00002475 APFloat Tmp = LHS_r;
2476 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2477 Result.getComplexFloatReal() = Tmp;
2478 Tmp = LHS_i;
2479 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2480 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2481
2482 Tmp = LHS_r;
2483 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2484 Result.getComplexFloatImag() = Tmp;
2485 Tmp = LHS_i;
2486 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2487 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2488 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002489 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002490 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002491 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2492 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002493 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002494 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2495 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2496 }
2497 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002498 case BO_Div:
2499 if (Result.isComplexFloat()) {
2500 ComplexValue LHS = Result;
2501 APFloat &LHS_r = LHS.getComplexFloatReal();
2502 APFloat &LHS_i = LHS.getComplexFloatImag();
2503 APFloat &RHS_r = RHS.getComplexFloatReal();
2504 APFloat &RHS_i = RHS.getComplexFloatImag();
2505 APFloat &Res_r = Result.getComplexFloatReal();
2506 APFloat &Res_i = Result.getComplexFloatImag();
2507
2508 APFloat Den = RHS_r;
2509 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2510 APFloat Tmp = RHS_i;
2511 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2512 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2513
2514 Res_r = LHS_r;
2515 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2516 Tmp = LHS_i;
2517 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2518 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2519 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2520
2521 Res_i = LHS_i;
2522 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2523 Tmp = LHS_r;
2524 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2525 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2526 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2527 } else {
2528 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2529 // FIXME: what about diagnostics?
2530 return false;
2531 }
2532 ComplexValue LHS = Result;
2533 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2534 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2535 Result.getComplexIntReal() =
2536 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2537 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2538 Result.getComplexIntImag() =
2539 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2540 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2541 }
2542 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002543 }
2544
John McCallf4cf1a12010-05-07 17:22:02 +00002545 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002546}
2547
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002548bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2549 // Get the operand value into 'Result'.
2550 if (!Visit(E->getSubExpr()))
2551 return false;
2552
2553 switch (E->getOpcode()) {
2554 default:
2555 // FIXME: what about diagnostics?
2556 return false;
2557 case UO_Extension:
2558 return true;
2559 case UO_Plus:
2560 // The result is always just the subexpr.
2561 return true;
2562 case UO_Minus:
2563 if (Result.isComplexFloat()) {
2564 Result.getComplexFloatReal().changeSign();
2565 Result.getComplexFloatImag().changeSign();
2566 }
2567 else {
2568 Result.getComplexIntReal() = -Result.getComplexIntReal();
2569 Result.getComplexIntImag() = -Result.getComplexIntImag();
2570 }
2571 return true;
2572 case UO_Not:
2573 if (Result.isComplexFloat())
2574 Result.getComplexFloatImag().changeSign();
2575 else
2576 Result.getComplexIntImag() = -Result.getComplexIntImag();
2577 return true;
2578 }
2579}
2580
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002581//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002582// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002583//===----------------------------------------------------------------------===//
2584
John McCall56ca35d2011-02-17 10:25:35 +00002585static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002586 if (E->getType()->isVectorType()) {
2587 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002588 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002589 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002590 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002591 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002592 if (Info.EvalResult.Val.isLValue() &&
2593 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002594 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002595 } else if (E->getType()->hasPointerRepresentation()) {
2596 LValue LV;
2597 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002598 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002599 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002600 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002601 LV.moveInto(Info.EvalResult.Val);
2602 } else if (E->getType()->isRealFloatingType()) {
2603 llvm::APFloat F(0.0);
2604 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002605 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002606
John McCallefdb83e2010-05-07 21:00:08 +00002607 Info.EvalResult.Val = APValue(F);
2608 } else if (E->getType()->isAnyComplexType()) {
2609 ComplexValue C;
2610 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002611 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002612 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002613 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002614 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002615
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002616 return true;
2617}
2618
John McCall56ca35d2011-02-17 10:25:35 +00002619/// Evaluate - Return true if this is a constant which we can fold using
2620/// any crazy technique (that has nothing to do with language standards) that
2621/// we want to. If this function returns true, it returns the folded constant
2622/// in Result.
2623bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2624 EvalInfo Info(Ctx, Result);
2625 return ::Evaluate(Info, this);
2626}
2627
Jay Foad4ba2a172011-01-12 09:06:06 +00002628bool Expr::EvaluateAsBooleanCondition(bool &Result,
2629 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002630 EvalResult Scratch;
2631 EvalInfo Info(Ctx, Scratch);
2632
2633 return HandleConversionToBool(this, Result, Info);
2634}
2635
Jay Foad4ba2a172011-01-12 09:06:06 +00002636bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002637 EvalInfo Info(Ctx, Result);
2638
John McCallefdb83e2010-05-07 21:00:08 +00002639 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002640 if (EvaluateLValue(this, LV, Info) &&
2641 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002642 IsGlobalLValue(LV.Base)) {
2643 LV.moveInto(Result.Val);
2644 return true;
2645 }
2646 return false;
2647}
2648
Jay Foad4ba2a172011-01-12 09:06:06 +00002649bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2650 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002651 EvalInfo Info(Ctx, Result);
2652
2653 LValue LV;
2654 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002655 LV.moveInto(Result.Val);
2656 return true;
2657 }
2658 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002659}
2660
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002661/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002662/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002663bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002664 EvalResult Result;
2665 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002666}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002667
Jay Foad4ba2a172011-01-12 09:06:06 +00002668bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002669 Expr::EvalResult Result;
2670 EvalInfo Info(Ctx, Result);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002671 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002672}
2673
Jay Foad4ba2a172011-01-12 09:06:06 +00002674APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002675 EvalResult EvalResult;
2676 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002677 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002678 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002679 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002680
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002681 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002682}
John McCalld905f5a2010-05-07 05:32:02 +00002683
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002684 bool Expr::EvalResult::isGlobalLValue() const {
2685 assert(Val.isLValue());
2686 return IsGlobalLValue(Val.getLValueBase());
2687 }
2688
2689
John McCalld905f5a2010-05-07 05:32:02 +00002690/// isIntegerConstantExpr - this recursive routine will test if an expression is
2691/// an integer constant expression.
2692
2693/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2694/// comma, etc
2695///
2696/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2697/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2698/// cast+dereference.
2699
2700// CheckICE - This function does the fundamental ICE checking: the returned
2701// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2702// Note that to reduce code duplication, this helper does no evaluation
2703// itself; the caller checks whether the expression is evaluatable, and
2704// in the rare cases where CheckICE actually cares about the evaluated
2705// value, it calls into Evalute.
2706//
2707// Meanings of Val:
2708// 0: This expression is an ICE if it can be evaluated by Evaluate.
2709// 1: This expression is not an ICE, but if it isn't evaluated, it's
2710// a legal subexpression for an ICE. This return value is used to handle
2711// the comma operator in C99 mode.
2712// 2: This expression is not an ICE, and is not a legal subexpression for one.
2713
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002714namespace {
2715
John McCalld905f5a2010-05-07 05:32:02 +00002716struct ICEDiag {
2717 unsigned Val;
2718 SourceLocation Loc;
2719
2720 public:
2721 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2722 ICEDiag() : Val(0) {}
2723};
2724
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002725}
2726
2727static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002728
2729static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2730 Expr::EvalResult EVResult;
2731 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2732 !EVResult.Val.isInt()) {
2733 return ICEDiag(2, E->getLocStart());
2734 }
2735 return NoDiag();
2736}
2737
2738static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2739 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002740 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002741 return ICEDiag(2, E->getLocStart());
2742 }
2743
2744 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002745#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002746#define STMT(Node, Base) case Expr::Node##Class:
2747#define EXPR(Node, Base)
2748#include "clang/AST/StmtNodes.inc"
2749 case Expr::PredefinedExprClass:
2750 case Expr::FloatingLiteralClass:
2751 case Expr::ImaginaryLiteralClass:
2752 case Expr::StringLiteralClass:
2753 case Expr::ArraySubscriptExprClass:
2754 case Expr::MemberExprClass:
2755 case Expr::CompoundAssignOperatorClass:
2756 case Expr::CompoundLiteralExprClass:
2757 case Expr::ExtVectorElementExprClass:
2758 case Expr::InitListExprClass:
2759 case Expr::DesignatedInitExprClass:
2760 case Expr::ImplicitValueInitExprClass:
2761 case Expr::ParenListExprClass:
2762 case Expr::VAArgExprClass:
2763 case Expr::AddrLabelExprClass:
2764 case Expr::StmtExprClass:
2765 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002766 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002767 case Expr::CXXDynamicCastExprClass:
2768 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002769 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002770 case Expr::CXXNullPtrLiteralExprClass:
2771 case Expr::CXXThisExprClass:
2772 case Expr::CXXThrowExprClass:
2773 case Expr::CXXNewExprClass:
2774 case Expr::CXXDeleteExprClass:
2775 case Expr::CXXPseudoDestructorExprClass:
2776 case Expr::UnresolvedLookupExprClass:
2777 case Expr::DependentScopeDeclRefExprClass:
2778 case Expr::CXXConstructExprClass:
2779 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002780 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002781 case Expr::CXXTemporaryObjectExprClass:
2782 case Expr::CXXUnresolvedConstructExprClass:
2783 case Expr::CXXDependentScopeMemberExprClass:
2784 case Expr::UnresolvedMemberExprClass:
2785 case Expr::ObjCStringLiteralClass:
2786 case Expr::ObjCEncodeExprClass:
2787 case Expr::ObjCMessageExprClass:
2788 case Expr::ObjCSelectorExprClass:
2789 case Expr::ObjCProtocolExprClass:
2790 case Expr::ObjCIvarRefExprClass:
2791 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002792 case Expr::ObjCIsaExprClass:
2793 case Expr::ShuffleVectorExprClass:
2794 case Expr::BlockExprClass:
2795 case Expr::BlockDeclRefExprClass:
2796 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002797 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002798 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002799 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002800 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002801 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002802 case Expr::MaterializeTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002803 return ICEDiag(2, E->getLocStart());
2804
Douglas Gregoree8aff02011-01-04 17:33:58 +00002805 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002806 case Expr::GNUNullExprClass:
2807 // GCC considers the GNU __null value to be an integral constant expression.
2808 return NoDiag();
2809
John McCall91a57552011-07-15 05:09:51 +00002810 case Expr::SubstNonTypeTemplateParmExprClass:
2811 return
2812 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2813
John McCalld905f5a2010-05-07 05:32:02 +00002814 case Expr::ParenExprClass:
2815 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002816 case Expr::GenericSelectionExprClass:
2817 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002818 case Expr::IntegerLiteralClass:
2819 case Expr::CharacterLiteralClass:
2820 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002821 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002822 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002823 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002824 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002825 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002826 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002827 return NoDiag();
2828 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002829 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002830 const CallExpr *CE = cast<CallExpr>(E);
2831 if (CE->isBuiltinCall(Ctx))
2832 return CheckEvalInICE(E, Ctx);
2833 return ICEDiag(2, E->getLocStart());
2834 }
2835 case Expr::DeclRefExprClass:
2836 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2837 return NoDiag();
2838 if (Ctx.getLangOptions().CPlusPlus &&
2839 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2840 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2841
2842 // Parameter variables are never constants. Without this check,
2843 // getAnyInitializer() can find a default argument, which leads
2844 // to chaos.
2845 if (isa<ParmVarDecl>(D))
2846 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2847
2848 // C++ 7.1.5.1p2
2849 // A variable of non-volatile const-qualified integral or enumeration
2850 // type initialized by an ICE can be used in ICEs.
2851 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2852 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2853 if (Quals.hasVolatile() || !Quals.hasConst())
2854 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2855
2856 // Look for a declaration of this variable that has an initializer.
2857 const VarDecl *ID = 0;
2858 const Expr *Init = Dcl->getAnyInitializer(ID);
2859 if (Init) {
2860 if (ID->isInitKnownICE()) {
2861 // We have already checked whether this subexpression is an
2862 // integral constant expression.
2863 if (ID->isInitICE())
2864 return NoDiag();
2865 else
2866 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2867 }
2868
2869 // It's an ICE whether or not the definition we found is
2870 // out-of-line. See DR 721 and the discussion in Clang PR
2871 // 6206 for details.
2872
2873 if (Dcl->isCheckingICE()) {
2874 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2875 }
2876
2877 Dcl->setCheckingICE();
2878 ICEDiag Result = CheckICE(Init, Ctx);
2879 // Cache the result of the ICE test.
2880 Dcl->setInitKnownICE(Result.Val == 0);
2881 return Result;
2882 }
2883 }
2884 }
2885 return ICEDiag(2, E->getLocStart());
2886 case Expr::UnaryOperatorClass: {
2887 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2888 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002889 case UO_PostInc:
2890 case UO_PostDec:
2891 case UO_PreInc:
2892 case UO_PreDec:
2893 case UO_AddrOf:
2894 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002895 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002896 case UO_Extension:
2897 case UO_LNot:
2898 case UO_Plus:
2899 case UO_Minus:
2900 case UO_Not:
2901 case UO_Real:
2902 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002903 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002904 }
2905
2906 // OffsetOf falls through here.
2907 }
2908 case Expr::OffsetOfExprClass: {
2909 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2910 // Evaluate matches the proposed gcc behavior for cases like
2911 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2912 // compliance: we should warn earlier for offsetof expressions with
2913 // array subscripts that aren't ICEs, and if the array subscripts
2914 // are ICEs, the value of the offsetof must be an integer constant.
2915 return CheckEvalInICE(E, Ctx);
2916 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002917 case Expr::UnaryExprOrTypeTraitExprClass: {
2918 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2919 if ((Exp->getKind() == UETT_SizeOf) &&
2920 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002921 return ICEDiag(2, E->getLocStart());
2922 return NoDiag();
2923 }
2924 case Expr::BinaryOperatorClass: {
2925 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2926 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002927 case BO_PtrMemD:
2928 case BO_PtrMemI:
2929 case BO_Assign:
2930 case BO_MulAssign:
2931 case BO_DivAssign:
2932 case BO_RemAssign:
2933 case BO_AddAssign:
2934 case BO_SubAssign:
2935 case BO_ShlAssign:
2936 case BO_ShrAssign:
2937 case BO_AndAssign:
2938 case BO_XorAssign:
2939 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002940 return ICEDiag(2, E->getLocStart());
2941
John McCall2de56d12010-08-25 11:45:40 +00002942 case BO_Mul:
2943 case BO_Div:
2944 case BO_Rem:
2945 case BO_Add:
2946 case BO_Sub:
2947 case BO_Shl:
2948 case BO_Shr:
2949 case BO_LT:
2950 case BO_GT:
2951 case BO_LE:
2952 case BO_GE:
2953 case BO_EQ:
2954 case BO_NE:
2955 case BO_And:
2956 case BO_Xor:
2957 case BO_Or:
2958 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002959 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2960 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002961 if (Exp->getOpcode() == BO_Div ||
2962 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002963 // Evaluate gives an error for undefined Div/Rem, so make sure
2964 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00002965 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00002966 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2967 if (REval == 0)
2968 return ICEDiag(1, E->getLocStart());
2969 if (REval.isSigned() && REval.isAllOnesValue()) {
2970 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2971 if (LEval.isMinSignedValue())
2972 return ICEDiag(1, E->getLocStart());
2973 }
2974 }
2975 }
John McCall2de56d12010-08-25 11:45:40 +00002976 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002977 if (Ctx.getLangOptions().C99) {
2978 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2979 // if it isn't evaluated.
2980 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2981 return ICEDiag(1, E->getLocStart());
2982 } else {
2983 // In both C89 and C++, commas in ICEs are illegal.
2984 return ICEDiag(2, E->getLocStart());
2985 }
2986 }
2987 if (LHSResult.Val >= RHSResult.Val)
2988 return LHSResult;
2989 return RHSResult;
2990 }
John McCall2de56d12010-08-25 11:45:40 +00002991 case BO_LAnd:
2992 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002993 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00002994
2995 // C++0x [expr.const]p2:
2996 // [...] subexpressions of logical AND (5.14), logical OR
2997 // (5.15), and condi- tional (5.16) operations that are not
2998 // evaluated are not considered.
2999 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3000 if (Exp->getOpcode() == BO_LAnd &&
3001 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
3002 return LHSResult;
3003
3004 if (Exp->getOpcode() == BO_LOr &&
3005 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
3006 return LHSResult;
3007 }
3008
John McCalld905f5a2010-05-07 05:32:02 +00003009 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3010 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3011 // Rare case where the RHS has a comma "side-effect"; we need
3012 // to actually check the condition to see whether the side
3013 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003014 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003015 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3016 return RHSResult;
3017 return NoDiag();
3018 }
3019
3020 if (LHSResult.Val >= RHSResult.Val)
3021 return LHSResult;
3022 return RHSResult;
3023 }
3024 }
3025 }
3026 case Expr::ImplicitCastExprClass:
3027 case Expr::CStyleCastExprClass:
3028 case Expr::CXXFunctionalCastExprClass:
3029 case Expr::CXXStaticCastExprClass:
3030 case Expr::CXXReinterpretCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003031 case Expr::CXXConstCastExprClass:
3032 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003033 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003034 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003035 return CheckICE(SubExpr, Ctx);
3036 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3037 return NoDiag();
3038 return ICEDiag(2, E->getLocStart());
3039 }
John McCall56ca35d2011-02-17 10:25:35 +00003040 case Expr::BinaryConditionalOperatorClass: {
3041 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3042 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3043 if (CommonResult.Val == 2) return CommonResult;
3044 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3045 if (FalseResult.Val == 2) return FalseResult;
3046 if (CommonResult.Val == 1) return CommonResult;
3047 if (FalseResult.Val == 1 &&
3048 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3049 return FalseResult;
3050 }
John McCalld905f5a2010-05-07 05:32:02 +00003051 case Expr::ConditionalOperatorClass: {
3052 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3053 // If the condition (ignoring parens) is a __builtin_constant_p call,
3054 // then only the true side is actually considered in an integer constant
3055 // expression, and it is fully evaluated. This is an important GNU
3056 // extension. See GCC PR38377 for discussion.
3057 if (const CallExpr *CallCE
3058 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3059 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3060 Expr::EvalResult EVResult;
3061 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3062 !EVResult.Val.isInt()) {
3063 return ICEDiag(2, E->getLocStart());
3064 }
3065 return NoDiag();
3066 }
3067 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003068 if (CondResult.Val == 2)
3069 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003070
3071 // C++0x [expr.const]p2:
3072 // subexpressions of [...] conditional (5.16) operations that
3073 // are not evaluated are not considered
3074 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3075 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3076 : false;
3077 ICEDiag TrueResult = NoDiag();
3078 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3079 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3080 ICEDiag FalseResult = NoDiag();
3081 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3082 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3083
John McCalld905f5a2010-05-07 05:32:02 +00003084 if (TrueResult.Val == 2)
3085 return TrueResult;
3086 if (FalseResult.Val == 2)
3087 return FalseResult;
3088 if (CondResult.Val == 1)
3089 return CondResult;
3090 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3091 return NoDiag();
3092 // Rare case where the diagnostics depend on which side is evaluated
3093 // Note that if we get here, CondResult is 0, and at least one of
3094 // TrueResult and FalseResult is non-zero.
3095 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3096 return FalseResult;
3097 }
3098 return TrueResult;
3099 }
3100 case Expr::CXXDefaultArgExprClass:
3101 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3102 case Expr::ChooseExprClass: {
3103 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3104 }
3105 }
3106
3107 // Silence a GCC warning
3108 return ICEDiag(2, E->getLocStart());
3109}
3110
3111bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3112 SourceLocation *Loc, bool isEvaluated) const {
3113 ICEDiag d = CheckICE(this, Ctx);
3114 if (d.Val != 0) {
3115 if (Loc) *Loc = d.Loc;
3116 return false;
3117 }
3118 EvalResult EvalResult;
3119 if (!Evaluate(EvalResult, Ctx))
3120 llvm_unreachable("ICE cannot be evaluated!");
3121 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3122 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3123 Result = EvalResult.Val.getInt();
3124 return true;
3125}