blob: df75bc8a735f03a420b9508748c7de3343289743 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-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 Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-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 McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Benjamin Kramer024e6192011-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) {}
Richard Smith4ce706a2011-10-11 21:43:33 +000062
63 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramer024e6192011-03-04 13:12:48 +000064 };
65
John McCall93d91dc2010-05-07 17:22:02 +000066 struct ComplexValue {
67 private:
68 bool IsInt;
69
70 public:
71 APSInt IntReal, IntImag;
72 APFloat FloatReal, FloatImag;
73
74 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
75
76 void makeComplexFloat() { IsInt = false; }
77 bool isComplexFloat() const { return !IsInt; }
78 APFloat &getComplexFloatReal() { return FloatReal; }
79 APFloat &getComplexFloatImag() { return FloatImag; }
80
81 void makeComplexInt() { IsInt = true; }
82 bool isComplexInt() const { return IsInt; }
83 APSInt &getComplexIntReal() { return IntReal; }
84 APSInt &getComplexIntImag() { return IntImag; }
85
John McCallc07a0c72011-02-17 10:25:35 +000086 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +000087 if (isComplexFloat())
88 v = APValue(FloatReal, FloatImag);
89 else
90 v = APValue(IntReal, IntImag);
91 }
John McCallc07a0c72011-02-17 10:25:35 +000092 void setFrom(const APValue &v) {
93 assert(v.isComplexFloat() || v.isComplexInt());
94 if (v.isComplexFloat()) {
95 makeComplexFloat();
96 FloatReal = v.getComplexFloatReal();
97 FloatImag = v.getComplexFloatImag();
98 } else {
99 makeComplexInt();
100 IntReal = v.getComplexIntReal();
101 IntImag = v.getComplexIntImag();
102 }
103 }
John McCall93d91dc2010-05-07 17:22:02 +0000104 };
John McCall45d55e42010-05-07 21:00:08 +0000105
106 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000107 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000108 CharUnits Offset;
109
Peter Collingbournee9200682011-05-13 03:29:01 +0000110 const Expr *getLValueBase() { return Base; }
John McCall45d55e42010-05-07 21:00:08 +0000111 CharUnits getLValueOffset() { return Offset; }
112
John McCallc07a0c72011-02-17 10:25:35 +0000113 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000114 v = APValue(Base, Offset);
115 }
John McCallc07a0c72011-02-17 10:25:35 +0000116 void setFrom(const APValue &v) {
117 assert(v.isLValue());
118 Base = v.getLValueBase();
119 Offset = v.getLValueOffset();
120 }
John McCall45d55e42010-05-07 21:00:08 +0000121 };
John McCall93d91dc2010-05-07 17:22:02 +0000122}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000123
John McCallc07a0c72011-02-17 10:25:35 +0000124static bool Evaluate(EvalInfo &info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000125static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
126static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000127static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000128static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
129 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000130static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000131static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000132
133//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000134// Misc utilities
135//===----------------------------------------------------------------------===//
136
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000137static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000138 if (!E) return true;
139
140 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
141 if (isa<FunctionDecl>(DRE->getDecl()))
142 return true;
143 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
144 return VD->hasGlobalStorage();
145 return false;
146 }
147
148 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
149 return CLE->isFileScope();
150
151 return true;
152}
153
John McCall45d55e42010-05-07 21:00:08 +0000154static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
155 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000156
John McCalleb3e4f32010-05-07 21:34:32 +0000157 // A null base expression indicates a null pointer. These are always
158 // evaluatable, and they are false unless the offset is zero.
159 if (!Base) {
160 Result = !Value.Offset.isZero();
161 return true;
162 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000163
John McCall95007602010-05-10 23:27:23 +0000164 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000165 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000166
John McCalleb3e4f32010-05-07 21:34:32 +0000167 // We have a non-null base expression. These are generally known to
168 // be true, but if it'a decl-ref to a weak symbol it can be null at
169 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000170 Result = true;
171
172 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000173 if (!DeclRef)
174 return true;
175
John McCalleb3e4f32010-05-07 21:34:32 +0000176 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000177 const ValueDecl* Decl = DeclRef->getDecl();
178 if (Decl->hasAttr<WeakAttr>() ||
179 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000180 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000181 return false;
182
Eli Friedman334046a2009-06-14 02:17:33 +0000183 return true;
184}
185
John McCall1be1c632010-01-05 23:42:56 +0000186static bool HandleConversionToBool(const Expr* E, bool& Result,
187 EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000188 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000189 APSInt IntResult;
190 if (!EvaluateInteger(E, IntResult, Info))
191 return false;
192 Result = IntResult != 0;
193 return true;
194 } else if (E->getType()->isRealFloatingType()) {
195 APFloat FloatResult(0.0);
196 if (!EvaluateFloat(E, FloatResult, Info))
197 return false;
198 Result = !FloatResult.isZero();
199 return true;
Eli Friedman64004332009-03-23 04:38:34 +0000200 } else if (E->getType()->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +0000201 LValue PointerResult;
Eli Friedman9a156e52008-11-12 09:44:48 +0000202 if (!EvaluatePointer(E, PointerResult, Info))
203 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000204 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000205 } else if (E->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +0000206 ComplexValue ComplexResult;
Eli Friedman64004332009-03-23 04:38:34 +0000207 if (!EvaluateComplex(E, ComplexResult, Info))
208 return false;
209 if (ComplexResult.isComplexFloat()) {
210 Result = !ComplexResult.getComplexFloatReal().isZero() ||
211 !ComplexResult.getComplexFloatImag().isZero();
212 } else {
213 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
214 ComplexResult.getComplexIntImag().getBoolValue();
215 }
216 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000217 }
218
219 return false;
220}
221
Mike Stump11289f42009-09-09 15:08:12 +0000222static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000223 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000224 unsigned DestWidth = Ctx.getIntWidth(DestType);
225 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000226 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000227
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000228 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000229 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000230 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000231 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
232 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000233}
234
Mike Stump11289f42009-09-09 15:08:12 +0000235static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000236 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000237 bool ignored;
238 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000239 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000240 APFloat::rmNearestTiesToEven, &ignored);
241 return Result;
242}
243
Mike Stump11289f42009-09-09 15:08:12 +0000244static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000245 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000246 unsigned DestWidth = Ctx.getIntWidth(DestType);
247 APSInt Result = Value;
248 // Figure out if this is a truncate, extend or noop cast.
249 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000250 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000251 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000252 return Result;
253}
254
Mike Stump11289f42009-09-09 15:08:12 +0000255static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000256 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000257
258 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
259 Result.convertFromAPInt(Value, Value.isSigned(),
260 APFloat::rmNearestTiesToEven);
261 return Result;
262}
263
Mike Stump876387b2009-10-27 22:09:17 +0000264namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000265class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000266 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stump876387b2009-10-27 22:09:17 +0000267 EvalInfo &Info;
268public:
269
270 HasSideEffect(EvalInfo &info) : Info(info) {}
271
272 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000273 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000274 return true;
275 }
276
Peter Collingbournee9200682011-05-13 03:29:01 +0000277 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
278 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000279 return Visit(E->getResultExpr());
280 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000281 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000282 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000283 return true;
284 return false;
285 }
John McCall31168b02011-06-15 23:02:42 +0000286 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
287 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
288 return true;
289 return false;
290 }
291 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
292 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
293 return true;
294 return false;
295 }
296
Mike Stump876387b2009-10-27 22:09:17 +0000297 // We don't want to evaluate BlockExprs multiple times, as they generate
298 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000299 bool VisitBlockExpr(const BlockExpr *E) { return true; }
300 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
301 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000302 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000303 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
304 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
305 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
306 bool VisitStringLiteral(const StringLiteral *E) { return false; }
307 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
308 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000309 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000310 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000311 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000312 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000313 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000314 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
315 bool VisitBinAssign(const BinaryOperator *E) { return true; }
316 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
317 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000318 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000319 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
321 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
322 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
323 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000324 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000325 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000326 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000327 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000328 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000329
330 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000331 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000332 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
333 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000334 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000335 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000336 return false;
337 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000338
Peter Collingbournee9200682011-05-13 03:29:01 +0000339 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000340};
341
John McCallc07a0c72011-02-17 10:25:35 +0000342class OpaqueValueEvaluation {
343 EvalInfo &info;
344 OpaqueValueExpr *opaqueValue;
345
346public:
347 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
348 Expr *value)
349 : info(info), opaqueValue(opaqueValue) {
350
351 // If evaluation fails, fail immediately.
352 if (!Evaluate(info, value)) {
353 this->opaqueValue = 0;
354 return;
355 }
356 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
357 }
358
359 bool hasError() const { return opaqueValue == 0; }
360
361 ~OpaqueValueEvaluation() {
362 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
363 }
364};
365
Mike Stump876387b2009-10-27 22:09:17 +0000366} // end anonymous namespace
367
Eli Friedman9a156e52008-11-12 09:44:48 +0000368//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000369// Generic Evaluation
370//===----------------------------------------------------------------------===//
371namespace {
372
373template <class Derived, typename RetTy=void>
374class ExprEvaluatorBase
375 : public ConstStmtVisitor<Derived, RetTy> {
376private:
377 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
378 return static_cast<Derived*>(this)->Success(V, E);
379 }
380 RetTy DerivedError(const Expr *E) {
381 return static_cast<Derived*>(this)->Error(E);
382 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000383 RetTy DerivedValueInitialization(const Expr *E) {
384 return static_cast<Derived*>(this)->ValueInitialization(E);
385 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000386
387protected:
388 EvalInfo &Info;
389 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
390 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
391
Richard Smith4ce706a2011-10-11 21:43:33 +0000392 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
393
Peter Collingbournee9200682011-05-13 03:29:01 +0000394public:
395 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
396
397 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000398 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000399 }
400 RetTy VisitExpr(const Expr *E) {
401 return DerivedError(E);
402 }
403
404 RetTy VisitParenExpr(const ParenExpr *E)
405 { return StmtVisitorTy::Visit(E->getSubExpr()); }
406 RetTy VisitUnaryExtension(const UnaryOperator *E)
407 { return StmtVisitorTy::Visit(E->getSubExpr()); }
408 RetTy VisitUnaryPlus(const UnaryOperator *E)
409 { return StmtVisitorTy::Visit(E->getSubExpr()); }
410 RetTy VisitChooseExpr(const ChooseExpr *E)
411 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
412 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
413 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000414 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
415 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000416
417 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
418 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
419 if (opaque.hasError())
420 return DerivedError(E);
421
422 bool cond;
423 if (!HandleConversionToBool(E->getCond(), cond, Info))
424 return DerivedError(E);
425
426 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
427 }
428
429 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
430 bool BoolResult;
431 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
432 return DerivedError(E);
433
434 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
435 return StmtVisitorTy::Visit(EvalExpr);
436 }
437
438 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
439 const APValue *value = Info.getOpaqueValue(E);
440 if (!value)
441 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
442 : DerivedError(E));
443 return DerivedSuccess(*value, E);
444 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000445
446 RetTy VisitInitListExpr(const InitListExpr *E) {
447 if (Info.getLangOpts().CPlusPlus0x) {
448 if (E->getNumInits() == 0)
449 return DerivedValueInitialization(E);
450 if (E->getNumInits() == 1)
451 return StmtVisitorTy::Visit(E->getInit(0));
452 }
453 return DerivedError(E);
454 }
455 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
456 return DerivedValueInitialization(E);
457 }
458 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
459 return DerivedValueInitialization(E);
460 }
461
Peter Collingbournee9200682011-05-13 03:29:01 +0000462};
463
464}
465
466//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000467// LValue Evaluation
468//===----------------------------------------------------------------------===//
469namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000470class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000471 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000472 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000473 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000474
Peter Collingbournee9200682011-05-13 03:29:01 +0000475 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000476 Result.Base = E;
477 Result.Offset = CharUnits::Zero();
478 return true;
479 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000480public:
Mike Stump11289f42009-09-09 15:08:12 +0000481
John McCall45d55e42010-05-07 21:00:08 +0000482 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000483 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000484
Peter Collingbournee9200682011-05-13 03:29:01 +0000485 bool Success(const APValue &V, const Expr *E) {
486 Result.setFrom(V);
487 return true;
488 }
489 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000490 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000491 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000492
Peter Collingbournee9200682011-05-13 03:29:01 +0000493 bool VisitDeclRefExpr(const DeclRefExpr *E);
494 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
495 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
496 bool VisitMemberExpr(const MemberExpr *E);
497 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
498 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
499 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
500 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000501
Peter Collingbournee9200682011-05-13 03:29:01 +0000502 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000503 switch (E->getCastKind()) {
504 default:
John McCall45d55e42010-05-07 21:00:08 +0000505 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000506
John McCalle3027922010-08-25 11:45:40 +0000507 case CK_NoOp:
Eli Friedmance3e02a2011-10-11 00:13:24 +0000508 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000509 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000510
511 // FIXME: Support CK_DerivedToBase and friends.
Anders Carlssonde55f642009-10-03 16:30:22 +0000512 }
513 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000514
Eli Friedman449fe542009-03-23 04:56:01 +0000515 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000516
Eli Friedman9a156e52008-11-12 09:44:48 +0000517};
518} // end anonymous namespace
519
John McCall45d55e42010-05-07 21:00:08 +0000520static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000521 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000522}
523
Peter Collingbournee9200682011-05-13 03:29:01 +0000524bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000525 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000526 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000527 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000528 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000529 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000530 // Reference parameters can refer to anything even if they have an
531 // "initializer" in the form of a default argument.
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000532 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000533 // FIXME: Check whether VD might be overridden!
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000534
535 // Check for recursive initializers of references.
536 if (PrevDecl == VD)
537 return Error(E);
538 PrevDecl = VD;
Peter Collingbournee9200682011-05-13 03:29:01 +0000539 if (const Expr *Init = VD->getAnyInitializer())
540 return Visit(Init);
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000541 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000542 }
543
Peter Collingbournee9200682011-05-13 03:29:01 +0000544 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000545}
546
Peter Collingbournee9200682011-05-13 03:29:01 +0000547bool
548LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000549 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000550}
551
Peter Collingbournee9200682011-05-13 03:29:01 +0000552bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000553 QualType Ty;
554 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000555 if (!EvaluatePointer(E->getBase(), Result, Info))
556 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000557 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000558 } else {
John McCall45d55e42010-05-07 21:00:08 +0000559 if (!Visit(E->getBase()))
560 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000561 Ty = E->getBase()->getType();
562 }
563
Peter Collingbournee9200682011-05-13 03:29:01 +0000564 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000565 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000566
Peter Collingbournee9200682011-05-13 03:29:01 +0000567 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000568 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000569 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000570
571 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000572 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000573
Eli Friedmana3c122d2011-07-07 01:54:01 +0000574 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000575 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000576 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000577}
578
Peter Collingbournee9200682011-05-13 03:29:01 +0000579bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000580 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000581 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000582
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000583 APSInt Index;
584 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000585 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000586
Ken Dyck40775002010-01-11 17:06:35 +0000587 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000588 Result.Offset += Index.getSExtValue() * ElementSize;
589 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000590}
Eli Friedman9a156e52008-11-12 09:44:48 +0000591
Peter Collingbournee9200682011-05-13 03:29:01 +0000592bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000593 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000594}
595
Eli Friedman9a156e52008-11-12 09:44:48 +0000596//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000597// Pointer Evaluation
598//===----------------------------------------------------------------------===//
599
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000600namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000601class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000602 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000603 LValue &Result;
604
Peter Collingbournee9200682011-05-13 03:29:01 +0000605 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000606 Result.Base = E;
607 Result.Offset = CharUnits::Zero();
608 return true;
609 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000610public:
Mike Stump11289f42009-09-09 15:08:12 +0000611
John McCall45d55e42010-05-07 21:00:08 +0000612 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000613 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000614
Peter Collingbournee9200682011-05-13 03:29:01 +0000615 bool Success(const APValue &V, const Expr *E) {
616 Result.setFrom(V);
617 return true;
618 }
619 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000620 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000621 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000622 bool ValueInitialization(const Expr *E) {
623 return Success((Expr*)0);
624 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000625
John McCall45d55e42010-05-07 21:00:08 +0000626 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000627 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000628 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000629 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000630 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000631 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000632 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000633 bool VisitCallExpr(const CallExpr *E);
634 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000635 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000636 return Success(E);
637 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000638 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000639 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +0000640 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +0000641
Eli Friedman449fe542009-03-23 04:56:01 +0000642 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000643};
Chris Lattner05706e882008-07-11 18:11:29 +0000644} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000645
John McCall45d55e42010-05-07 21:00:08 +0000646static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000647 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000648 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000649}
650
John McCall45d55e42010-05-07 21:00:08 +0000651bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000652 if (E->getOpcode() != BO_Add &&
653 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000654 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000655
Chris Lattner05706e882008-07-11 18:11:29 +0000656 const Expr *PExp = E->getLHS();
657 const Expr *IExp = E->getRHS();
658 if (IExp->getType()->isPointerType())
659 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000660
John McCall45d55e42010-05-07 21:00:08 +0000661 if (!EvaluatePointer(PExp, Result, Info))
662 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000663
John McCall45d55e42010-05-07 21:00:08 +0000664 llvm::APSInt Offset;
665 if (!EvaluateInteger(IExp, Offset, Info))
666 return false;
667 int64_t AdditionalOffset
668 = Offset.isSigned() ? Offset.getSExtValue()
669 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000670
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000671 // Compute the new offset in the appropriate width.
672
673 QualType PointeeType =
674 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000675 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000676
Anders Carlssonef56fba2009-02-19 04:55:58 +0000677 // Explicitly handle GNU void* and function pointer arithmetic extensions.
678 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000679 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000680 else
John McCall45d55e42010-05-07 21:00:08 +0000681 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000682
John McCalle3027922010-08-25 11:45:40 +0000683 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000684 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000685 else
John McCall45d55e42010-05-07 21:00:08 +0000686 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000687
John McCall45d55e42010-05-07 21:00:08 +0000688 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000689}
Eli Friedman9a156e52008-11-12 09:44:48 +0000690
John McCall45d55e42010-05-07 21:00:08 +0000691bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
692 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000693}
Mike Stump11289f42009-09-09 15:08:12 +0000694
Chris Lattner05706e882008-07-11 18:11:29 +0000695
Peter Collingbournee9200682011-05-13 03:29:01 +0000696bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
697 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000698
Eli Friedman847a2bc2009-12-27 05:43:15 +0000699 switch (E->getCastKind()) {
700 default:
701 break;
702
John McCalle3027922010-08-25 11:45:40 +0000703 case CK_NoOp:
704 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +0000705 case CK_CPointerToObjCPointerCast:
706 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +0000707 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000708 return Visit(SubExpr);
709
Anders Carlsson18275092010-10-31 20:41:46 +0000710 case CK_DerivedToBase:
711 case CK_UncheckedDerivedToBase: {
712 LValue BaseLV;
713 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
714 return false;
715
716 // Now figure out the necessary offset to add to the baseLV to get from
717 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000718 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000719
720 QualType Ty = E->getSubExpr()->getType();
721 const CXXRecordDecl *DerivedDecl =
722 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
723
724 for (CastExpr::path_const_iterator PathI = E->path_begin(),
725 PathE = E->path_end(); PathI != PathE; ++PathI) {
726 const CXXBaseSpecifier *Base = *PathI;
727
728 // FIXME: If the base is virtual, we'd need to determine the type of the
729 // most derived class and we don't support that right now.
730 if (Base->isVirtual())
731 return false;
732
733 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
734 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
735
Ken Dyck02155cb2011-01-26 02:17:08 +0000736 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000737 DerivedDecl = BaseDecl;
738 }
739
740 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000741 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000742 return true;
743 }
744
John McCalle84af4e2010-11-13 01:35:44 +0000745 case CK_NullToPointer: {
746 Result.Base = 0;
747 Result.Offset = CharUnits::Zero();
748 return true;
749 }
750
John McCalle3027922010-08-25 11:45:40 +0000751 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000752 APValue Value;
753 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000754 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000755
John McCall45d55e42010-05-07 21:00:08 +0000756 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000757 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000758 Result.Base = 0;
759 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
760 return true;
761 } else {
762 // Cast is of an lvalue, no need to change value.
763 Result.Base = Value.getLValueBase();
764 Result.Offset = Value.getLValueOffset();
765 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000766 }
767 }
John McCalle3027922010-08-25 11:45:40 +0000768 case CK_ArrayToPointerDecay:
769 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000770 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000771 }
772
John McCall45d55e42010-05-07 21:00:08 +0000773 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000774}
Chris Lattner05706e882008-07-11 18:11:29 +0000775
Peter Collingbournee9200682011-05-13 03:29:01 +0000776bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000777 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000778 Builtin::BI__builtin___CFStringMakeConstantString ||
779 E->isBuiltinCall(Info.Ctx) ==
780 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000781 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000782
Peter Collingbournee9200682011-05-13 03:29:01 +0000783 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000784}
Chris Lattner05706e882008-07-11 18:11:29 +0000785
786//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000787// Vector Evaluation
788//===----------------------------------------------------------------------===//
789
790namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000791 class VectorExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000792 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman3ae59112009-02-23 04:23:56 +0000793 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000794 public:
Mike Stump11289f42009-09-09 15:08:12 +0000795
Peter Collingbournee9200682011-05-13 03:29:01 +0000796 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000797
Peter Collingbournee9200682011-05-13 03:29:01 +0000798 APValue Success(const APValue &V, const Expr *E) { return V; }
799 APValue Error(const Expr *E) { return APValue(); }
Richard Smith4ce706a2011-10-11 21:43:33 +0000800 APValue ValueInitialization(const Expr *E)
801 { return GetZeroVector(E->getType()); }
Mike Stump11289f42009-09-09 15:08:12 +0000802
Eli Friedman3ae59112009-02-23 04:23:56 +0000803 APValue VisitUnaryReal(const UnaryOperator *E)
804 { return Visit(E->getSubExpr()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000805 APValue VisitCastExpr(const CastExpr* E);
806 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
807 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000808 APValue VisitUnaryImag(const UnaryOperator *E);
809 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000810 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000811 // shufflevector, ExtVectorElementExpr
812 // (Note that these require implementing conversions
813 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000814 };
815} // end anonymous namespace
816
817static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
818 if (!E->getType()->isVectorType())
819 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +0000820 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000821 return !Result.isUninit();
822}
823
824APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000825 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000826 QualType EltTy = VTy->getElementType();
827 unsigned NElts = VTy->getNumElements();
828 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000829
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000830 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000831 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000832
Eli Friedmanc757de22011-03-25 00:43:55 +0000833 switch (E->getCastKind()) {
834 case CK_VectorSplat: {
835 APValue Result = APValue();
836 if (SETy->isIntegerType()) {
837 APSInt IntResult;
838 if (!EvaluateInteger(SE, IntResult, Info))
839 return APValue();
840 Result = APValue(IntResult);
841 } else if (SETy->isRealFloatingType()) {
842 APFloat F(0.0);
843 if (!EvaluateFloat(SE, F, Info))
844 return APValue();
845 Result = APValue(F);
846 } else {
Anders Carlsson6fc22042011-03-25 11:22:47 +0000847 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000848 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000849
850 // Splat and create vector APValue.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000851 SmallVector<APValue, 4> Elts(NElts, Result);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000852 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000853 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000854 case CK_BitCast: {
855 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000856 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000857
Eli Friedmanc757de22011-03-25 00:43:55 +0000858 if (!SETy->isIntegerType())
Anders Carlsson6fc22042011-03-25 11:22:47 +0000859 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000860
Eli Friedmanc757de22011-03-25 00:43:55 +0000861 APSInt Init;
862 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000863 return APValue();
864
Eli Friedmanc757de22011-03-25 00:43:55 +0000865 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
866 "Vectors must be composed of ints or floats");
867
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000868 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +0000869 for (unsigned i = 0; i != NElts; ++i) {
870 APSInt Tmp = Init.extOrTrunc(EltWidth);
871
872 if (EltTy->isIntegerType())
873 Elts.push_back(APValue(Tmp));
874 else
875 Elts.push_back(APValue(APFloat(Tmp)));
876
877 Init >>= EltWidth;
878 }
879 return APValue(&Elts[0], Elts.size());
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000880 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000881 case CK_LValueToRValue:
882 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000883 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000884 default:
Anders Carlsson6fc22042011-03-25 11:22:47 +0000885 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000886 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000887}
888
Mike Stump11289f42009-09-09 15:08:12 +0000889APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000890VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000891 return this->Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000892}
893
Mike Stump11289f42009-09-09 15:08:12 +0000894APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000895VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000896 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000897 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000898 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000899
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000900 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000901 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000902
John McCall875679e2010-06-11 17:54:15 +0000903 // If a vector is initialized with a single element, that value
904 // becomes every element of the vector, not just the first.
905 // This is the behavior described in the IBM AltiVec documentation.
906 if (NumInits == 1) {
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000907
908 // Handle the case where the vector is initialized by a another
909 // vector (OpenCL 6.1.6).
910 if (E->getInit(0)->getType()->isVectorType())
911 return this->Visit(const_cast<Expr*>(E->getInit(0)));
912
John McCall875679e2010-06-11 17:54:15 +0000913 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000914 if (EltTy->isIntegerType()) {
915 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000916 if (!EvaluateInteger(E->getInit(0), sInt, Info))
917 return APValue();
918 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000919 } else {
920 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000921 if (!EvaluateFloat(E->getInit(0), f, Info))
922 return APValue();
923 InitValue = APValue(f);
924 }
925 for (unsigned i = 0; i < NumElements; i++) {
926 Elements.push_back(InitValue);
927 }
928 } else {
929 for (unsigned i = 0; i < NumElements; i++) {
930 if (EltTy->isIntegerType()) {
931 llvm::APSInt sInt(32);
932 if (i < NumInits) {
933 if (!EvaluateInteger(E->getInit(i), sInt, Info))
934 return APValue();
935 } else {
936 sInt = Info.Ctx.MakeIntValue(0, EltTy);
937 }
938 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000939 } else {
John McCall875679e2010-06-11 17:54:15 +0000940 llvm::APFloat f(0.0);
941 if (i < NumInits) {
942 if (!EvaluateFloat(E->getInit(i), f, Info))
943 return APValue();
944 } else {
945 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
946 }
947 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000948 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000949 }
950 }
951 return APValue(&Elements[0], Elements.size());
952}
953
Mike Stump11289f42009-09-09 15:08:12 +0000954APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000955VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000956 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000957 QualType EltTy = VT->getElementType();
958 APValue ZeroElement;
959 if (EltTy->isIntegerType())
960 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
961 else
962 ZeroElement =
963 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
964
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000965 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Eli Friedman3ae59112009-02-23 04:23:56 +0000966 return APValue(&Elements[0], Elements.size());
967}
968
Eli Friedman3ae59112009-02-23 04:23:56 +0000969APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
970 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
971 Info.EvalResult.HasSideEffects = true;
972 return GetZeroVector(E->getType());
973}
974
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000975//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000976// Integer Evaluation
977//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000978
979namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000980class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000981 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000982 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000983public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000984 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000985 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000986
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000987 bool Success(const llvm::APSInt &SI, const Expr *E) {
988 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +0000989 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000990 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000991 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000992 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000993 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000994 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000995 return true;
996 }
997
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000998 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000999 assert(E->getType()->isIntegralOrEnumerationType() &&
1000 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001001 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001002 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001003 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001004 Result.getInt().setIsUnsigned(
1005 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001006 return true;
1007 }
1008
1009 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001010 assert(E->getType()->isIntegralOrEnumerationType() &&
1011 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001012 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001013 return true;
1014 }
1015
Ken Dyckdbc01912011-03-11 02:13:43 +00001016 bool Success(CharUnits Size, const Expr *E) {
1017 return Success(Size.getQuantity(), E);
1018 }
1019
1020
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001021 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001022 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +00001023 if (Info.EvalResult.Diag == 0) {
1024 Info.EvalResult.DiagLoc = L;
1025 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001026 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001027 }
Chris Lattner99415702008-07-12 00:14:42 +00001028 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001029 }
Mike Stump11289f42009-09-09 15:08:12 +00001030
Peter Collingbournee9200682011-05-13 03:29:01 +00001031 bool Success(const APValue &V, const Expr *E) {
1032 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001033 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001034 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001035 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001036 }
Mike Stump11289f42009-09-09 15:08:12 +00001037
Richard Smith4ce706a2011-10-11 21:43:33 +00001038 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1039
Peter Collingbournee9200682011-05-13 03:29:01 +00001040 //===--------------------------------------------------------------------===//
1041 // Visitor Methods
1042 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001043
Chris Lattner7174bf32008-07-12 00:38:25 +00001044 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001045 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001046 }
1047 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001048 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001049 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001050
1051 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1052 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001053 if (CheckReferencedDecl(E, E->getDecl()))
1054 return true;
1055
1056 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001057 }
1058 bool VisitMemberExpr(const MemberExpr *E) {
1059 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1060 // Conservatively assume a MemberExpr will have side-effects
1061 Info.EvalResult.HasSideEffects = true;
1062 return true;
1063 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001064
1065 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001066 }
1067
Peter Collingbournee9200682011-05-13 03:29:01 +00001068 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001069 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001070 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001071 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001072
Peter Collingbournee9200682011-05-13 03:29:01 +00001073 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001074 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001075
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001076 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001077 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001078 }
Mike Stump11289f42009-09-09 15:08:12 +00001079
Richard Smith4ce706a2011-10-11 21:43:33 +00001080 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001081 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001082 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001083 }
1084
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001085 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001086 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001087 }
1088
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001089 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1090 return Success(E->getValue(), E);
1091 }
1092
John Wiegley6242b6a2011-04-28 00:16:57 +00001093 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1094 return Success(E->getValue(), E);
1095 }
1096
John Wiegleyf9f65842011-04-25 06:54:41 +00001097 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1098 return Success(E->getValue(), E);
1099 }
1100
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001101 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001102 bool VisitUnaryImag(const UnaryOperator *E);
1103
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001104 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001105 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001106
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001107private:
Ken Dyck160146e2010-01-27 17:10:57 +00001108 CharUnits GetAlignOfExpr(const Expr *E);
1109 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001110 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001111 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001112 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001113};
Chris Lattner05706e882008-07-11 18:11:29 +00001114} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001115
Daniel Dunbarce399542009-02-20 18:22:23 +00001116static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001117 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001118 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001119}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001120
Daniel Dunbarce399542009-02-20 18:22:23 +00001121static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001122 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001123
Daniel Dunbarce399542009-02-20 18:22:23 +00001124 APValue Val;
1125 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1126 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001127 Result = Val.getInt();
1128 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001129}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001130
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001131bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001132 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001133 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001134 // Check for signedness/width mismatches between E type and ECD value.
1135 bool SameSign = (ECD->getInitVal().isSigned()
1136 == E->getType()->isSignedIntegerOrEnumerationType());
1137 bool SameWidth = (ECD->getInitVal().getBitWidth()
1138 == Info.Ctx.getIntWidth(E->getType()));
1139 if (SameSign && SameWidth)
1140 return Success(ECD->getInitVal(), E);
1141 else {
1142 // Get rid of mismatch (otherwise Success assertions will fail)
1143 // by computing a new value matching the type of E.
1144 llvm::APSInt Val = ECD->getInitVal();
1145 if (!SameSign)
1146 Val.setIsSigned(!ECD->getInitVal().isSigned());
1147 if (!SameWidth)
1148 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1149 return Success(Val, E);
1150 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001151 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001152
1153 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001154 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001155 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1156 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001157
1158 if (isa<ParmVarDecl>(D))
Peter Collingbournee9200682011-05-13 03:29:01 +00001159 return false;
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001160
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001161 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001162 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001163 if (APValue *V = VD->getEvaluatedValue()) {
1164 if (V->isInt())
1165 return Success(V->getInt(), E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001166 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001167 }
1168
1169 if (VD->isEvaluatingValue())
Peter Collingbournee9200682011-05-13 03:29:01 +00001170 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001171
1172 VD->setEvaluatingValue();
1173
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001174 Expr::EvalResult EResult;
1175 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1176 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001177 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001178 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001179 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001180 return true;
1181 }
1182
Eli Friedman1d6fb162009-12-03 20:31:57 +00001183 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001184 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001185 }
1186 }
1187
Chris Lattner7174bf32008-07-12 00:38:25 +00001188 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001189 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001190}
1191
Chris Lattner86ee2862008-10-06 06:40:35 +00001192/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1193/// as GCC.
1194static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1195 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001196 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001197 enum gcc_type_class {
1198 no_type_class = -1,
1199 void_type_class, integer_type_class, char_type_class,
1200 enumeral_type_class, boolean_type_class,
1201 pointer_type_class, reference_type_class, offset_type_class,
1202 real_type_class, complex_type_class,
1203 function_type_class, method_type_class,
1204 record_type_class, union_type_class,
1205 array_type_class, string_type_class,
1206 lang_type_class
1207 };
Mike Stump11289f42009-09-09 15:08:12 +00001208
1209 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001210 // ideal, however it is what gcc does.
1211 if (E->getNumArgs() == 0)
1212 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001213
Chris Lattner86ee2862008-10-06 06:40:35 +00001214 QualType ArgTy = E->getArg(0)->getType();
1215 if (ArgTy->isVoidType())
1216 return void_type_class;
1217 else if (ArgTy->isEnumeralType())
1218 return enumeral_type_class;
1219 else if (ArgTy->isBooleanType())
1220 return boolean_type_class;
1221 else if (ArgTy->isCharType())
1222 return string_type_class; // gcc doesn't appear to use char_type_class
1223 else if (ArgTy->isIntegerType())
1224 return integer_type_class;
1225 else if (ArgTy->isPointerType())
1226 return pointer_type_class;
1227 else if (ArgTy->isReferenceType())
1228 return reference_type_class;
1229 else if (ArgTy->isRealType())
1230 return real_type_class;
1231 else if (ArgTy->isComplexType())
1232 return complex_type_class;
1233 else if (ArgTy->isFunctionType())
1234 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001235 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001236 return record_type_class;
1237 else if (ArgTy->isUnionType())
1238 return union_type_class;
1239 else if (ArgTy->isArrayType())
1240 return array_type_class;
1241 else if (ArgTy->isUnionType())
1242 return union_type_class;
1243 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001244 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001245 return -1;
1246}
1247
John McCall95007602010-05-10 23:27:23 +00001248/// Retrieves the "underlying object type" of the given expression,
1249/// as used by __builtin_object_size.
1250QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1251 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1252 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1253 return VD->getType();
1254 } else if (isa<CompoundLiteralExpr>(E)) {
1255 return E->getType();
1256 }
1257
1258 return QualType();
1259}
1260
Peter Collingbournee9200682011-05-13 03:29:01 +00001261bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001262 // TODO: Perhaps we should let LLVM lower this?
1263 LValue Base;
1264 if (!EvaluatePointer(E->getArg(0), Base, Info))
1265 return false;
1266
1267 // If we can prove the base is null, lower to zero now.
1268 const Expr *LVBase = Base.getLValueBase();
1269 if (!LVBase) return Success(0, E);
1270
1271 QualType T = GetObjectType(LVBase);
1272 if (T.isNull() ||
1273 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001274 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001275 T->isVariablyModifiedType() ||
1276 T->isDependentType())
1277 return false;
1278
1279 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1280 CharUnits Offset = Base.getLValueOffset();
1281
1282 if (!Offset.isNegative() && Offset <= Size)
1283 Size -= Offset;
1284 else
1285 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001286 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001287}
1288
Peter Collingbournee9200682011-05-13 03:29:01 +00001289bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001290 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001291 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001292 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001293
1294 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001295 if (TryEvaluateBuiltinObjectSize(E))
1296 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001297
Eric Christopher99469702010-01-19 22:58:35 +00001298 // If evaluating the argument has side-effects we can't determine
1299 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001300 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001301 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001302 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001303 return Success(0, E);
1304 }
Mike Stump876387b2009-10-27 22:09:17 +00001305
Mike Stump722cedf2009-10-26 18:35:08 +00001306 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1307 }
1308
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001309 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001310 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001311
Anders Carlsson4c76e932008-11-24 04:21:33 +00001312 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001313 // __builtin_constant_p always has one operand: it returns true if that
1314 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001315 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001316
1317 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001318 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001319 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001320 return Success(Operand, E);
1321 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001322
1323 case Builtin::BI__builtin_expect:
1324 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001325
1326 case Builtin::BIstrlen:
1327 case Builtin::BI__builtin_strlen:
1328 // As an extension, we support strlen() and __builtin_strlen() as constant
1329 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001330 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001331 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1332 // The string literal may have embedded null characters. Find the first
1333 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001334 StringRef Str = S->getString();
1335 StringRef::size_type Pos = Str.find(0);
1336 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001337 Str = Str.substr(0, Pos);
1338
1339 return Success(Str.size(), E);
1340 }
1341
1342 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001343 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001344}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001345
Chris Lattnere13042c2008-07-11 19:10:17 +00001346bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001347 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001348 if (!Visit(E->getRHS()))
1349 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001350
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001351 // If we can't evaluate the LHS, it might have side effects;
1352 // conservatively mark it.
1353 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1354 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001355
Anders Carlsson564730a2008-12-01 02:07:06 +00001356 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001357 }
1358
1359 if (E->isLogicalOp()) {
1360 // These need to be handled specially because the operands aren't
1361 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001362 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001363
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001364 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001365 // We were able to evaluate the LHS, see if we can get away with not
1366 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001367 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001368 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001369
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001370 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001371 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001372 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001373 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001374 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001375 }
1376 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001377 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001378 // We can't evaluate the LHS; however, sometimes the result
1379 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001380 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1381 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001382 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001383 // must have had side effects.
1384 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001385
1386 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001387 }
1388 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001389 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001390
Eli Friedman5a332ea2008-11-13 06:09:17 +00001391 return false;
1392 }
1393
Anders Carlssonacc79812008-11-16 07:17:21 +00001394 QualType LHSTy = E->getLHS()->getType();
1395 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001396
1397 if (LHSTy->isAnyComplexType()) {
1398 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001399 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001400
1401 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1402 return false;
1403
1404 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1405 return false;
1406
1407 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001408 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001409 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001410 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001411 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1412
John McCalle3027922010-08-25 11:45:40 +00001413 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001414 return Success((CR_r == APFloat::cmpEqual &&
1415 CR_i == APFloat::cmpEqual), E);
1416 else {
John McCalle3027922010-08-25 11:45:40 +00001417 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001418 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001419 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001420 CR_r == APFloat::cmpLessThan ||
1421 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001422 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001423 CR_i == APFloat::cmpLessThan ||
1424 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001425 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001426 } else {
John McCalle3027922010-08-25 11:45:40 +00001427 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001428 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1429 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1430 else {
John McCalle3027922010-08-25 11:45:40 +00001431 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001432 "Invalid compex comparison.");
1433 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1434 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1435 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001436 }
1437 }
Mike Stump11289f42009-09-09 15:08:12 +00001438
Anders Carlssonacc79812008-11-16 07:17:21 +00001439 if (LHSTy->isRealFloatingType() &&
1440 RHSTy->isRealFloatingType()) {
1441 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001442
Anders Carlssonacc79812008-11-16 07:17:21 +00001443 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1444 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001445
Anders Carlssonacc79812008-11-16 07:17:21 +00001446 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1447 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001448
Anders Carlssonacc79812008-11-16 07:17:21 +00001449 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001450
Anders Carlssonacc79812008-11-16 07:17:21 +00001451 switch (E->getOpcode()) {
1452 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001453 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001454 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001455 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001456 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001457 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001458 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001459 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001460 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001461 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001462 E);
John McCalle3027922010-08-25 11:45:40 +00001463 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001464 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001465 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001466 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001467 || CR == APFloat::cmpLessThan
1468 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001469 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001470 }
Mike Stump11289f42009-09-09 15:08:12 +00001471
Eli Friedmana38da572009-04-28 19:17:36 +00001472 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001473 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001474 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001475 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1476 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001477
John McCall45d55e42010-05-07 21:00:08 +00001478 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001479 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1480 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001481
Eli Friedman334046a2009-06-14 02:17:33 +00001482 // Reject any bases from the normal codepath; we special-case comparisons
1483 // to null.
1484 if (LHSValue.getLValueBase()) {
1485 if (!E->isEqualityOp())
1486 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001487 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001488 return false;
1489 bool bres;
1490 if (!EvalPointerValueAsBool(LHSValue, bres))
1491 return false;
John McCalle3027922010-08-25 11:45:40 +00001492 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001493 } else if (RHSValue.getLValueBase()) {
1494 if (!E->isEqualityOp())
1495 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001496 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001497 return false;
1498 bool bres;
1499 if (!EvalPointerValueAsBool(RHSValue, bres))
1500 return false;
John McCalle3027922010-08-25 11:45:40 +00001501 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001502 }
Eli Friedman64004332009-03-23 04:38:34 +00001503
John McCalle3027922010-08-25 11:45:40 +00001504 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001505 QualType Type = E->getLHS()->getType();
1506 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001507
Ken Dyck02990832010-01-15 12:37:54 +00001508 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001509 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001510 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001511
Ken Dyck02990832010-01-15 12:37:54 +00001512 CharUnits Diff = LHSValue.getLValueOffset() -
1513 RHSValue.getLValueOffset();
1514 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001515 }
1516 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001517 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001518 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001519 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001520 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1521 }
1522 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001523 }
1524 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001525 if (!LHSTy->isIntegralOrEnumerationType() ||
1526 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001527 // We can't continue from here for non-integral types, and they
1528 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001529 return false;
1530 }
1531
Anders Carlsson9c181652008-07-08 14:35:21 +00001532 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001533 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001534 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001535
Eli Friedman94c25c62009-03-24 01:14:50 +00001536 APValue RHSVal;
1537 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001538 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001539
1540 // Handle cases like (unsigned long)&a + 4.
1541 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001542 CharUnits Offset = Result.getLValueOffset();
1543 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1544 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001545 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001546 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001547 else
Ken Dyck02990832010-01-15 12:37:54 +00001548 Offset -= AdditionalOffset;
1549 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001550 return true;
1551 }
1552
1553 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001554 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001555 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001556 CharUnits Offset = RHSVal.getLValueOffset();
1557 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1558 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001559 return true;
1560 }
1561
1562 // All the following cases expect both operands to be an integer
1563 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001564 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001565
Eli Friedman94c25c62009-03-24 01:14:50 +00001566 APSInt& RHS = RHSVal.getInt();
1567
Anders Carlsson9c181652008-07-08 14:35:21 +00001568 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001569 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001570 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001571 case BO_Mul: return Success(Result.getInt() * RHS, E);
1572 case BO_Add: return Success(Result.getInt() + RHS, E);
1573 case BO_Sub: return Success(Result.getInt() - RHS, E);
1574 case BO_And: return Success(Result.getInt() & RHS, E);
1575 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1576 case BO_Or: return Success(Result.getInt() | RHS, E);
1577 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001578 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001579 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001580 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001581 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001582 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001583 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001584 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001585 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001586 // During constant-folding, a negative shift is an opposite shift.
1587 if (RHS.isSigned() && RHS.isNegative()) {
1588 RHS = -RHS;
1589 goto shift_right;
1590 }
1591
1592 shift_left:
1593 unsigned SA
1594 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001595 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001596 }
John McCalle3027922010-08-25 11:45:40 +00001597 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001598 // During constant-folding, a negative shift is an opposite shift.
1599 if (RHS.isSigned() && RHS.isNegative()) {
1600 RHS = -RHS;
1601 goto shift_left;
1602 }
1603
1604 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001605 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001606 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1607 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001608 }
Mike Stump11289f42009-09-09 15:08:12 +00001609
John McCalle3027922010-08-25 11:45:40 +00001610 case BO_LT: return Success(Result.getInt() < RHS, E);
1611 case BO_GT: return Success(Result.getInt() > RHS, E);
1612 case BO_LE: return Success(Result.getInt() <= RHS, E);
1613 case BO_GE: return Success(Result.getInt() >= RHS, E);
1614 case BO_EQ: return Success(Result.getInt() == RHS, E);
1615 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001616 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001617}
1618
Ken Dyck160146e2010-01-27 17:10:57 +00001619CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001620 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1621 // the result is the size of the referenced type."
1622 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1623 // result shall be the alignment of the referenced type."
1624 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1625 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001626
1627 // __alignof is defined to return the preferred alignment.
1628 return Info.Ctx.toCharUnitsFromBits(
1629 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001630}
1631
Ken Dyck160146e2010-01-27 17:10:57 +00001632CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001633 E = E->IgnoreParens();
1634
1635 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001636 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001637 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001638 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1639 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001640
Chris Lattner68061312009-01-24 21:53:27 +00001641 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001642 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1643 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001644
Chris Lattner24aeeab2009-01-24 21:09:06 +00001645 return GetAlignOfType(E->getType());
1646}
1647
1648
Peter Collingbournee190dee2011-03-11 19:24:49 +00001649/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1650/// a result as the expression's type.
1651bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1652 const UnaryExprOrTypeTraitExpr *E) {
1653 switch(E->getKind()) {
1654 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001655 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001656 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001657 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001658 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001659 }
Eli Friedman64004332009-03-23 04:38:34 +00001660
Peter Collingbournee190dee2011-03-11 19:24:49 +00001661 case UETT_VecStep: {
1662 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001663
Peter Collingbournee190dee2011-03-11 19:24:49 +00001664 if (Ty->isVectorType()) {
1665 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001666
Peter Collingbournee190dee2011-03-11 19:24:49 +00001667 // The vec_step built-in functions that take a 3-component
1668 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1669 if (n == 3)
1670 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001671
Peter Collingbournee190dee2011-03-11 19:24:49 +00001672 return Success(n, E);
1673 } else
1674 return Success(1, E);
1675 }
1676
1677 case UETT_SizeOf: {
1678 QualType SrcTy = E->getTypeOfArgument();
1679 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1680 // the result is the size of the referenced type."
1681 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1682 // result shall be the alignment of the referenced type."
1683 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1684 SrcTy = Ref->getPointeeType();
1685
1686 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1687 // extension.
1688 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1689 return Success(1, E);
1690
1691 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1692 if (!SrcTy->isConstantSizeType())
1693 return false;
1694
1695 // Get information about the size.
1696 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1697 }
1698 }
1699
1700 llvm_unreachable("unknown expr/type trait");
1701 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001702}
1703
Peter Collingbournee9200682011-05-13 03:29:01 +00001704bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001705 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001706 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001707 if (n == 0)
1708 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001709 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001710 for (unsigned i = 0; i != n; ++i) {
1711 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1712 switch (ON.getKind()) {
1713 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001714 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001715 APSInt IdxResult;
1716 if (!EvaluateInteger(Idx, IdxResult, Info))
1717 return false;
1718 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1719 if (!AT)
1720 return false;
1721 CurrentType = AT->getElementType();
1722 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1723 Result += IdxResult.getSExtValue() * ElementSize;
1724 break;
1725 }
1726
1727 case OffsetOfExpr::OffsetOfNode::Field: {
1728 FieldDecl *MemberDecl = ON.getField();
1729 const RecordType *RT = CurrentType->getAs<RecordType>();
1730 if (!RT)
1731 return false;
1732 RecordDecl *RD = RT->getDecl();
1733 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001734 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001735 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001736 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001737 CurrentType = MemberDecl->getType().getNonReferenceType();
1738 break;
1739 }
1740
1741 case OffsetOfExpr::OffsetOfNode::Identifier:
1742 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001743 return false;
1744
1745 case OffsetOfExpr::OffsetOfNode::Base: {
1746 CXXBaseSpecifier *BaseSpec = ON.getBase();
1747 if (BaseSpec->isVirtual())
1748 return false;
1749
1750 // Find the layout of the class whose base we are looking into.
1751 const RecordType *RT = CurrentType->getAs<RecordType>();
1752 if (!RT)
1753 return false;
1754 RecordDecl *RD = RT->getDecl();
1755 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1756
1757 // Find the base class itself.
1758 CurrentType = BaseSpec->getType();
1759 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1760 if (!BaseRT)
1761 return false;
1762
1763 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001764 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001765 break;
1766 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001767 }
1768 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001769 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001770}
1771
Chris Lattnere13042c2008-07-11 19:10:17 +00001772bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001773 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001774 // LNot's operand isn't necessarily an integer, so we handle it specially.
1775 bool bres;
1776 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1777 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001778 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001779 }
1780
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001781 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001782 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001783 return false;
1784
Chris Lattnercdf34e72008-07-11 22:52:41 +00001785 // Get the operand value into 'Result'.
1786 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001787 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001788
Chris Lattnerf09ad162008-07-11 22:15:16 +00001789 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001790 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001791 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1792 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001793 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001794 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001795 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1796 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001797 return true;
John McCalle3027922010-08-25 11:45:40 +00001798 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001799 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001800 return true;
John McCalle3027922010-08-25 11:45:40 +00001801 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001802 if (!Result.isInt()) return false;
1803 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001804 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001805 if (!Result.isInt()) return false;
1806 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001807 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001808}
Mike Stump11289f42009-09-09 15:08:12 +00001809
Chris Lattner477c4be2008-07-12 01:15:53 +00001810/// HandleCast - This is used to evaluate implicit or explicit casts where the
1811/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001812bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1813 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001814 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001815 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001816
Eli Friedmanc757de22011-03-25 00:43:55 +00001817 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001818 case CK_BaseToDerived:
1819 case CK_DerivedToBase:
1820 case CK_UncheckedDerivedToBase:
1821 case CK_Dynamic:
1822 case CK_ToUnion:
1823 case CK_ArrayToPointerDecay:
1824 case CK_FunctionToPointerDecay:
1825 case CK_NullToPointer:
1826 case CK_NullToMemberPointer:
1827 case CK_BaseToDerivedMemberPointer:
1828 case CK_DerivedToBaseMemberPointer:
1829 case CK_ConstructorConversion:
1830 case CK_IntegralToPointer:
1831 case CK_ToVoid:
1832 case CK_VectorSplat:
1833 case CK_IntegralToFloating:
1834 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00001835 case CK_CPointerToObjCPointerCast:
1836 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001837 case CK_AnyPointerToBlockPointerCast:
1838 case CK_ObjCObjectLValueCast:
1839 case CK_FloatingRealToComplex:
1840 case CK_FloatingComplexToReal:
1841 case CK_FloatingComplexCast:
1842 case CK_FloatingComplexToIntegralComplex:
1843 case CK_IntegralRealToComplex:
1844 case CK_IntegralComplexCast:
1845 case CK_IntegralComplexToFloatingComplex:
1846 llvm_unreachable("invalid cast kind for integral value");
1847
Eli Friedman9faf2f92011-03-25 19:07:11 +00001848 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001849 case CK_Dependent:
1850 case CK_GetObjCProperty:
1851 case CK_LValueBitCast:
1852 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00001853 case CK_ARCProduceObject:
1854 case CK_ARCConsumeObject:
1855 case CK_ARCReclaimReturnedObject:
1856 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001857 return false;
1858
1859 case CK_LValueToRValue:
1860 case CK_NoOp:
1861 return Visit(E->getSubExpr());
1862
1863 case CK_MemberPointerToBoolean:
1864 case CK_PointerToBoolean:
1865 case CK_IntegralToBoolean:
1866 case CK_FloatingToBoolean:
1867 case CK_FloatingComplexToBoolean:
1868 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001869 bool BoolResult;
1870 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1871 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001872 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001873 }
1874
Eli Friedmanc757de22011-03-25 00:43:55 +00001875 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001876 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001877 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001878
Eli Friedman742421e2009-02-20 01:15:07 +00001879 if (!Result.isInt()) {
1880 // Only allow casts of lvalues if they are lossless.
1881 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1882 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001883
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001884 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001885 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001886 }
Mike Stump11289f42009-09-09 15:08:12 +00001887
Eli Friedmanc757de22011-03-25 00:43:55 +00001888 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001889 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001890 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001891 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001892
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001893 if (LV.getLValueBase()) {
1894 // Only allow based lvalue casts if they are lossless.
1895 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1896 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001897
John McCall45d55e42010-05-07 21:00:08 +00001898 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001899 return true;
1900 }
1901
Ken Dyck02990832010-01-15 12:37:54 +00001902 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1903 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001904 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001905 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001906
Eli Friedmanc757de22011-03-25 00:43:55 +00001907 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001908 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001909 if (!EvaluateComplex(SubExpr, C, Info))
1910 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001911 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001912 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001913
Eli Friedmanc757de22011-03-25 00:43:55 +00001914 case CK_FloatingToIntegral: {
1915 APFloat F(0.0);
1916 if (!EvaluateFloat(SubExpr, F, Info))
1917 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001918
Eli Friedmanc757de22011-03-25 00:43:55 +00001919 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1920 }
1921 }
Mike Stump11289f42009-09-09 15:08:12 +00001922
Eli Friedmanc757de22011-03-25 00:43:55 +00001923 llvm_unreachable("unknown cast resulting in integral value");
1924 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001925}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001926
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001927bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1928 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001929 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001930 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1931 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1932 return Success(LV.getComplexIntReal(), E);
1933 }
1934
1935 return Visit(E->getSubExpr());
1936}
1937
Eli Friedman4e7a2412009-02-27 04:45:43 +00001938bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001939 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001940 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001941 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1942 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1943 return Success(LV.getComplexIntImag(), E);
1944 }
1945
Eli Friedman4e7a2412009-02-27 04:45:43 +00001946 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1947 Info.EvalResult.HasSideEffects = true;
1948 return Success(0, E);
1949}
1950
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001951bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1952 return Success(E->getPackLength(), E);
1953}
1954
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001955bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1956 return Success(E->getValue(), E);
1957}
1958
Chris Lattner05706e882008-07-11 18:11:29 +00001959//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001960// Float Evaluation
1961//===----------------------------------------------------------------------===//
1962
1963namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001964class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001965 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00001966 APFloat &Result;
1967public:
1968 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001969 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00001970
Peter Collingbournee9200682011-05-13 03:29:01 +00001971 bool Success(const APValue &V, const Expr *e) {
1972 Result = V.getFloat();
1973 return true;
1974 }
1975 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00001976 return false;
1977 }
1978
Richard Smith4ce706a2011-10-11 21:43:33 +00001979 bool ValueInitialization(const Expr *E) {
1980 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
1981 return true;
1982 }
1983
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001984 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001985
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001986 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001987 bool VisitBinaryOperator(const BinaryOperator *E);
1988 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001989 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001990
John McCallb1fb0d32010-05-07 22:08:54 +00001991 bool VisitUnaryReal(const UnaryOperator *E);
1992 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001993
John McCalla2fabff2010-10-09 01:34:31 +00001994 bool VisitDeclRefExpr(const DeclRefExpr *E);
1995
John McCallb1fb0d32010-05-07 22:08:54 +00001996 // FIXME: Missing: array subscript of vector, member of vector,
1997 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001998};
1999} // end anonymous namespace
2000
2001static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002002 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002003 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002004}
2005
Jay Foad39c79802011-01-12 09:06:06 +00002006static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002007 QualType ResultTy,
2008 const Expr *Arg,
2009 bool SNaN,
2010 llvm::APFloat &Result) {
2011 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2012 if (!S) return false;
2013
2014 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2015
2016 llvm::APInt fill;
2017
2018 // Treat empty strings as if they were zero.
2019 if (S->getString().empty())
2020 fill = llvm::APInt(32, 0);
2021 else if (S->getString().getAsInteger(0, fill))
2022 return false;
2023
2024 if (SNaN)
2025 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2026 else
2027 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2028 return true;
2029}
2030
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002031bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002032 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002033 default:
2034 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2035
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002036 case Builtin::BI__builtin_huge_val:
2037 case Builtin::BI__builtin_huge_valf:
2038 case Builtin::BI__builtin_huge_vall:
2039 case Builtin::BI__builtin_inf:
2040 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002041 case Builtin::BI__builtin_infl: {
2042 const llvm::fltSemantics &Sem =
2043 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002044 Result = llvm::APFloat::getInf(Sem);
2045 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002046 }
Mike Stump11289f42009-09-09 15:08:12 +00002047
John McCall16291492010-02-28 13:00:19 +00002048 case Builtin::BI__builtin_nans:
2049 case Builtin::BI__builtin_nansf:
2050 case Builtin::BI__builtin_nansl:
2051 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2052 true, Result);
2053
Chris Lattner0b7282e2008-10-06 06:31:58 +00002054 case Builtin::BI__builtin_nan:
2055 case Builtin::BI__builtin_nanf:
2056 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002057 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002058 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002059 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2060 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002061
2062 case Builtin::BI__builtin_fabs:
2063 case Builtin::BI__builtin_fabsf:
2064 case Builtin::BI__builtin_fabsl:
2065 if (!EvaluateFloat(E->getArg(0), Result, Info))
2066 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002067
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002068 if (Result.isNegative())
2069 Result.changeSign();
2070 return true;
2071
Mike Stump11289f42009-09-09 15:08:12 +00002072 case Builtin::BI__builtin_copysign:
2073 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002074 case Builtin::BI__builtin_copysignl: {
2075 APFloat RHS(0.);
2076 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2077 !EvaluateFloat(E->getArg(1), RHS, Info))
2078 return false;
2079 Result.copySign(RHS);
2080 return true;
2081 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002082 }
2083}
2084
John McCalla2fabff2010-10-09 01:34:31 +00002085bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002086 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2087 return true;
2088
John McCalla2fabff2010-10-09 01:34:31 +00002089 const Decl *D = E->getDecl();
2090 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2091 const VarDecl *VD = cast<VarDecl>(D);
2092
2093 // Require the qualifiers to be const and not volatile.
2094 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2095 if (!T.isConstQualified() || T.isVolatileQualified())
2096 return false;
2097
2098 const Expr *Init = VD->getAnyInitializer();
2099 if (!Init) return false;
2100
2101 if (APValue *V = VD->getEvaluatedValue()) {
2102 if (V->isFloat()) {
2103 Result = V->getFloat();
2104 return true;
2105 }
2106 return false;
2107 }
2108
2109 if (VD->isEvaluatingValue())
2110 return false;
2111
2112 VD->setEvaluatingValue();
2113
2114 Expr::EvalResult InitResult;
2115 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2116 InitResult.Val.isFloat()) {
2117 // Cache the evaluated value in the variable declaration.
2118 Result = InitResult.Val.getFloat();
2119 VD->setEvaluatedValue(InitResult.Val);
2120 return true;
2121 }
2122
2123 VD->setEvaluatedValue(APValue());
2124 return false;
2125}
2126
John McCallb1fb0d32010-05-07 22:08:54 +00002127bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002128 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2129 ComplexValue CV;
2130 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2131 return false;
2132 Result = CV.FloatReal;
2133 return true;
2134 }
2135
2136 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002137}
2138
2139bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002140 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2141 ComplexValue CV;
2142 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2143 return false;
2144 Result = CV.FloatImag;
2145 return true;
2146 }
2147
2148 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2149 Info.EvalResult.HasSideEffects = true;
2150 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2151 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002152 return true;
2153}
2154
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002155bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002156 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002157 return false;
2158
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002159 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2160 return false;
2161
2162 switch (E->getOpcode()) {
2163 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002164 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002165 return true;
John McCalle3027922010-08-25 11:45:40 +00002166 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002167 Result.changeSign();
2168 return true;
2169 }
2170}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002171
Eli Friedman24c01542008-08-22 00:06:13 +00002172bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002173 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002174 if (!EvaluateFloat(E->getRHS(), Result, Info))
2175 return false;
2176
2177 // If we can't evaluate the LHS, it might have side effects;
2178 // conservatively mark it.
2179 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2180 Info.EvalResult.HasSideEffects = true;
2181
2182 return true;
2183 }
2184
Anders Carlssona5df61a2010-10-31 01:21:47 +00002185 // We can't evaluate pointer-to-member operations.
2186 if (E->isPtrMemOp())
2187 return false;
2188
Eli Friedman24c01542008-08-22 00:06:13 +00002189 // FIXME: Diagnostics? I really don't understand how the warnings
2190 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002191 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002192 if (!EvaluateFloat(E->getLHS(), Result, Info))
2193 return false;
2194 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2195 return false;
2196
2197 switch (E->getOpcode()) {
2198 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002199 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002200 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2201 return true;
John McCalle3027922010-08-25 11:45:40 +00002202 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002203 Result.add(RHS, APFloat::rmNearestTiesToEven);
2204 return true;
John McCalle3027922010-08-25 11:45:40 +00002205 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002206 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2207 return true;
John McCalle3027922010-08-25 11:45:40 +00002208 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002209 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2210 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002211 }
2212}
2213
2214bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2215 Result = E->getValue();
2216 return true;
2217}
2218
Peter Collingbournee9200682011-05-13 03:29:01 +00002219bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2220 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002221
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002222 switch (E->getCastKind()) {
2223 default:
2224 return false;
2225
2226 case CK_LValueToRValue:
2227 case CK_NoOp:
2228 return Visit(SubExpr);
2229
2230 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002231 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002232 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002233 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002234 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002235 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002236 return true;
2237 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002238
2239 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002240 if (!Visit(SubExpr))
2241 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002242 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2243 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002244 return true;
2245 }
John McCalld7646252010-11-14 08:17:51 +00002246
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002247 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002248 ComplexValue V;
2249 if (!EvaluateComplex(SubExpr, V, Info))
2250 return false;
2251 Result = V.getComplexFloatReal();
2252 return true;
2253 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002254 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002255
2256 return false;
2257}
2258
Eli Friedman24c01542008-08-22 00:06:13 +00002259//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002260// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002261//===----------------------------------------------------------------------===//
2262
2263namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002264class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002265 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002266 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002267
Anders Carlsson537969c2008-11-16 20:27:53 +00002268public:
John McCall93d91dc2010-05-07 17:22:02 +00002269 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002270 : ExprEvaluatorBaseTy(info), Result(Result) {}
2271
2272 bool Success(const APValue &V, const Expr *e) {
2273 Result.setFrom(V);
2274 return true;
2275 }
2276 bool Error(const Expr *E) {
2277 return false;
2278 }
Mike Stump11289f42009-09-09 15:08:12 +00002279
Anders Carlsson537969c2008-11-16 20:27:53 +00002280 //===--------------------------------------------------------------------===//
2281 // Visitor Methods
2282 //===--------------------------------------------------------------------===//
2283
Peter Collingbournee9200682011-05-13 03:29:01 +00002284 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002285
Peter Collingbournee9200682011-05-13 03:29:01 +00002286 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002287
John McCall93d91dc2010-05-07 17:22:02 +00002288 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002289 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002290 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002291};
2292} // end anonymous namespace
2293
John McCall93d91dc2010-05-07 17:22:02 +00002294static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2295 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002296 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002297 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002298}
2299
Peter Collingbournee9200682011-05-13 03:29:01 +00002300bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2301 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002302
2303 if (SubExpr->getType()->isRealFloatingType()) {
2304 Result.makeComplexFloat();
2305 APFloat &Imag = Result.FloatImag;
2306 if (!EvaluateFloat(SubExpr, Imag, Info))
2307 return false;
2308
2309 Result.FloatReal = APFloat(Imag.getSemantics());
2310 return true;
2311 } else {
2312 assert(SubExpr->getType()->isIntegerType() &&
2313 "Unexpected imaginary literal.");
2314
2315 Result.makeComplexInt();
2316 APSInt &Imag = Result.IntImag;
2317 if (!EvaluateInteger(SubExpr, Imag, Info))
2318 return false;
2319
2320 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2321 return true;
2322 }
2323}
2324
Peter Collingbournee9200682011-05-13 03:29:01 +00002325bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002326
John McCallfcef3cf2010-12-14 17:51:41 +00002327 switch (E->getCastKind()) {
2328 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002329 case CK_BaseToDerived:
2330 case CK_DerivedToBase:
2331 case CK_UncheckedDerivedToBase:
2332 case CK_Dynamic:
2333 case CK_ToUnion:
2334 case CK_ArrayToPointerDecay:
2335 case CK_FunctionToPointerDecay:
2336 case CK_NullToPointer:
2337 case CK_NullToMemberPointer:
2338 case CK_BaseToDerivedMemberPointer:
2339 case CK_DerivedToBaseMemberPointer:
2340 case CK_MemberPointerToBoolean:
2341 case CK_ConstructorConversion:
2342 case CK_IntegralToPointer:
2343 case CK_PointerToIntegral:
2344 case CK_PointerToBoolean:
2345 case CK_ToVoid:
2346 case CK_VectorSplat:
2347 case CK_IntegralCast:
2348 case CK_IntegralToBoolean:
2349 case CK_IntegralToFloating:
2350 case CK_FloatingToIntegral:
2351 case CK_FloatingToBoolean:
2352 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002353 case CK_CPointerToObjCPointerCast:
2354 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002355 case CK_AnyPointerToBlockPointerCast:
2356 case CK_ObjCObjectLValueCast:
2357 case CK_FloatingComplexToReal:
2358 case CK_FloatingComplexToBoolean:
2359 case CK_IntegralComplexToReal:
2360 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002361 case CK_ARCProduceObject:
2362 case CK_ARCConsumeObject:
2363 case CK_ARCReclaimReturnedObject:
2364 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002365 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002366
John McCallfcef3cf2010-12-14 17:51:41 +00002367 case CK_LValueToRValue:
2368 case CK_NoOp:
2369 return Visit(E->getSubExpr());
2370
2371 case CK_Dependent:
2372 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002373 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002374 case CK_UserDefinedConversion:
2375 return false;
2376
2377 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002378 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002379 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002380 return false;
2381
John McCallfcef3cf2010-12-14 17:51:41 +00002382 Result.makeComplexFloat();
2383 Result.FloatImag = APFloat(Real.getSemantics());
2384 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002385 }
2386
John McCallfcef3cf2010-12-14 17:51:41 +00002387 case CK_FloatingComplexCast: {
2388 if (!Visit(E->getSubExpr()))
2389 return false;
2390
2391 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2392 QualType From
2393 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2394
2395 Result.FloatReal
2396 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2397 Result.FloatImag
2398 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2399 return true;
2400 }
2401
2402 case CK_FloatingComplexToIntegralComplex: {
2403 if (!Visit(E->getSubExpr()))
2404 return false;
2405
2406 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2407 QualType From
2408 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2409 Result.makeComplexInt();
2410 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2411 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2412 return true;
2413 }
2414
2415 case CK_IntegralRealToComplex: {
2416 APSInt &Real = Result.IntReal;
2417 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2418 return false;
2419
2420 Result.makeComplexInt();
2421 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2422 return true;
2423 }
2424
2425 case CK_IntegralComplexCast: {
2426 if (!Visit(E->getSubExpr()))
2427 return false;
2428
2429 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2430 QualType From
2431 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2432
2433 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2434 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2435 return true;
2436 }
2437
2438 case CK_IntegralComplexToFloatingComplex: {
2439 if (!Visit(E->getSubExpr()))
2440 return false;
2441
2442 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2443 QualType From
2444 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2445 Result.makeComplexFloat();
2446 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2447 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2448 return true;
2449 }
2450 }
2451
2452 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002453 return false;
2454}
2455
John McCall93d91dc2010-05-07 17:22:02 +00002456bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002457 if (E->getOpcode() == BO_Comma) {
2458 if (!Visit(E->getRHS()))
2459 return false;
2460
2461 // If we can't evaluate the LHS, it might have side effects;
2462 // conservatively mark it.
2463 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2464 Info.EvalResult.HasSideEffects = true;
2465
2466 return true;
2467 }
John McCall93d91dc2010-05-07 17:22:02 +00002468 if (!Visit(E->getLHS()))
2469 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002470
John McCall93d91dc2010-05-07 17:22:02 +00002471 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002472 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002473 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002474
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002475 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2476 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002477 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002478 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002479 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002480 if (Result.isComplexFloat()) {
2481 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2482 APFloat::rmNearestTiesToEven);
2483 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2484 APFloat::rmNearestTiesToEven);
2485 } else {
2486 Result.getComplexIntReal() += RHS.getComplexIntReal();
2487 Result.getComplexIntImag() += RHS.getComplexIntImag();
2488 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002489 break;
John McCalle3027922010-08-25 11:45:40 +00002490 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002491 if (Result.isComplexFloat()) {
2492 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2493 APFloat::rmNearestTiesToEven);
2494 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2495 APFloat::rmNearestTiesToEven);
2496 } else {
2497 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2498 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2499 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002500 break;
John McCalle3027922010-08-25 11:45:40 +00002501 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002502 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002503 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002504 APFloat &LHS_r = LHS.getComplexFloatReal();
2505 APFloat &LHS_i = LHS.getComplexFloatImag();
2506 APFloat &RHS_r = RHS.getComplexFloatReal();
2507 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002508
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002509 APFloat Tmp = LHS_r;
2510 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2511 Result.getComplexFloatReal() = Tmp;
2512 Tmp = LHS_i;
2513 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2514 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2515
2516 Tmp = LHS_r;
2517 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2518 Result.getComplexFloatImag() = Tmp;
2519 Tmp = LHS_i;
2520 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2521 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2522 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002523 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002524 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002525 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2526 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002527 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002528 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2529 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2530 }
2531 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002532 case BO_Div:
2533 if (Result.isComplexFloat()) {
2534 ComplexValue LHS = Result;
2535 APFloat &LHS_r = LHS.getComplexFloatReal();
2536 APFloat &LHS_i = LHS.getComplexFloatImag();
2537 APFloat &RHS_r = RHS.getComplexFloatReal();
2538 APFloat &RHS_i = RHS.getComplexFloatImag();
2539 APFloat &Res_r = Result.getComplexFloatReal();
2540 APFloat &Res_i = Result.getComplexFloatImag();
2541
2542 APFloat Den = RHS_r;
2543 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2544 APFloat Tmp = RHS_i;
2545 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2546 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2547
2548 Res_r = LHS_r;
2549 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2550 Tmp = LHS_i;
2551 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2552 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2553 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2554
2555 Res_i = LHS_i;
2556 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2557 Tmp = LHS_r;
2558 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2559 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2560 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2561 } else {
2562 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2563 // FIXME: what about diagnostics?
2564 return false;
2565 }
2566 ComplexValue LHS = Result;
2567 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2568 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2569 Result.getComplexIntReal() =
2570 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2571 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2572 Result.getComplexIntImag() =
2573 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2574 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2575 }
2576 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002577 }
2578
John McCall93d91dc2010-05-07 17:22:02 +00002579 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002580}
2581
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002582bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2583 // Get the operand value into 'Result'.
2584 if (!Visit(E->getSubExpr()))
2585 return false;
2586
2587 switch (E->getOpcode()) {
2588 default:
2589 // FIXME: what about diagnostics?
2590 return false;
2591 case UO_Extension:
2592 return true;
2593 case UO_Plus:
2594 // The result is always just the subexpr.
2595 return true;
2596 case UO_Minus:
2597 if (Result.isComplexFloat()) {
2598 Result.getComplexFloatReal().changeSign();
2599 Result.getComplexFloatImag().changeSign();
2600 }
2601 else {
2602 Result.getComplexIntReal() = -Result.getComplexIntReal();
2603 Result.getComplexIntImag() = -Result.getComplexIntImag();
2604 }
2605 return true;
2606 case UO_Not:
2607 if (Result.isComplexFloat())
2608 Result.getComplexFloatImag().changeSign();
2609 else
2610 Result.getComplexIntImag() = -Result.getComplexIntImag();
2611 return true;
2612 }
2613}
2614
Anders Carlsson537969c2008-11-16 20:27:53 +00002615//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002616// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002617//===----------------------------------------------------------------------===//
2618
John McCallc07a0c72011-02-17 10:25:35 +00002619static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002620 if (E->getType()->isVectorType()) {
2621 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002622 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002623 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002624 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002625 return false;
John McCallc07a0c72011-02-17 10:25:35 +00002626 if (Info.EvalResult.Val.isLValue() &&
2627 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002628 return false;
John McCall45d55e42010-05-07 21:00:08 +00002629 } else if (E->getType()->hasPointerRepresentation()) {
2630 LValue LV;
2631 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002632 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002633 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002634 return false;
John McCall45d55e42010-05-07 21:00:08 +00002635 LV.moveInto(Info.EvalResult.Val);
2636 } else if (E->getType()->isRealFloatingType()) {
2637 llvm::APFloat F(0.0);
2638 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002639 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002640
John McCall45d55e42010-05-07 21:00:08 +00002641 Info.EvalResult.Val = APValue(F);
2642 } else if (E->getType()->isAnyComplexType()) {
2643 ComplexValue C;
2644 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002645 return false;
John McCall45d55e42010-05-07 21:00:08 +00002646 C.moveInto(Info.EvalResult.Val);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002647 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002648 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002649
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002650 return true;
2651}
2652
John McCallc07a0c72011-02-17 10:25:35 +00002653/// Evaluate - Return true if this is a constant which we can fold using
2654/// any crazy technique (that has nothing to do with language standards) that
2655/// we want to. If this function returns true, it returns the folded constant
2656/// in Result.
2657bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2658 EvalInfo Info(Ctx, Result);
2659 return ::Evaluate(Info, this);
2660}
2661
Jay Foad39c79802011-01-12 09:06:06 +00002662bool Expr::EvaluateAsBooleanCondition(bool &Result,
2663 const ASTContext &Ctx) const {
John McCall1be1c632010-01-05 23:42:56 +00002664 EvalResult Scratch;
2665 EvalInfo Info(Ctx, Scratch);
2666
2667 return HandleConversionToBool(this, Result, Info);
2668}
2669
Richard Smithcaf33902011-10-10 18:28:20 +00002670bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
2671 EvalResult Scratch;
2672 EvalInfo Info(Ctx, Scratch);
2673
2674 return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
2675}
2676
Jay Foad39c79802011-01-12 09:06:06 +00002677bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002678 EvalInfo Info(Ctx, Result);
2679
John McCall45d55e42010-05-07 21:00:08 +00002680 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002681 if (EvaluateLValue(this, LV, Info) &&
2682 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002683 IsGlobalLValue(LV.Base)) {
2684 LV.moveInto(Result.Val);
2685 return true;
2686 }
2687 return false;
2688}
2689
Jay Foad39c79802011-01-12 09:06:06 +00002690bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2691 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002692 EvalInfo Info(Ctx, Result);
2693
2694 LValue LV;
2695 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002696 LV.moveInto(Result.Val);
2697 return true;
2698 }
2699 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002700}
2701
Chris Lattner67d7b922008-11-16 21:24:15 +00002702/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002703/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002704bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002705 EvalResult Result;
2706 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002707}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002708
Jay Foad39c79802011-01-12 09:06:06 +00002709bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002710 Expr::EvalResult Result;
2711 EvalInfo Info(Ctx, Result);
Peter Collingbournee9200682011-05-13 03:29:01 +00002712 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002713}
2714
Richard Smithcaf33902011-10-10 18:28:20 +00002715APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002716 EvalResult EvalResult;
2717 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002718 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002719 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002720 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002721
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002722 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002723}
John McCall864e3962010-05-07 05:32:02 +00002724
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002725 bool Expr::EvalResult::isGlobalLValue() const {
2726 assert(Val.isLValue());
2727 return IsGlobalLValue(Val.getLValueBase());
2728 }
2729
2730
John McCall864e3962010-05-07 05:32:02 +00002731/// isIntegerConstantExpr - this recursive routine will test if an expression is
2732/// an integer constant expression.
2733
2734/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2735/// comma, etc
2736///
2737/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2738/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2739/// cast+dereference.
2740
2741// CheckICE - This function does the fundamental ICE checking: the returned
2742// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2743// Note that to reduce code duplication, this helper does no evaluation
2744// itself; the caller checks whether the expression is evaluatable, and
2745// in the rare cases where CheckICE actually cares about the evaluated
2746// value, it calls into Evalute.
2747//
2748// Meanings of Val:
2749// 0: This expression is an ICE if it can be evaluated by Evaluate.
2750// 1: This expression is not an ICE, but if it isn't evaluated, it's
2751// a legal subexpression for an ICE. This return value is used to handle
2752// the comma operator in C99 mode.
2753// 2: This expression is not an ICE, and is not a legal subexpression for one.
2754
Dan Gohman28ade552010-07-26 21:25:24 +00002755namespace {
2756
John McCall864e3962010-05-07 05:32:02 +00002757struct ICEDiag {
2758 unsigned Val;
2759 SourceLocation Loc;
2760
2761 public:
2762 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2763 ICEDiag() : Val(0) {}
2764};
2765
Dan Gohman28ade552010-07-26 21:25:24 +00002766}
2767
2768static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002769
2770static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2771 Expr::EvalResult EVResult;
2772 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2773 !EVResult.Val.isInt()) {
2774 return ICEDiag(2, E->getLocStart());
2775 }
2776 return NoDiag();
2777}
2778
2779static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2780 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002781 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002782 return ICEDiag(2, E->getLocStart());
2783 }
2784
2785 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002786#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002787#define STMT(Node, Base) case Expr::Node##Class:
2788#define EXPR(Node, Base)
2789#include "clang/AST/StmtNodes.inc"
2790 case Expr::PredefinedExprClass:
2791 case Expr::FloatingLiteralClass:
2792 case Expr::ImaginaryLiteralClass:
2793 case Expr::StringLiteralClass:
2794 case Expr::ArraySubscriptExprClass:
2795 case Expr::MemberExprClass:
2796 case Expr::CompoundAssignOperatorClass:
2797 case Expr::CompoundLiteralExprClass:
2798 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00002799 case Expr::DesignatedInitExprClass:
2800 case Expr::ImplicitValueInitExprClass:
2801 case Expr::ParenListExprClass:
2802 case Expr::VAArgExprClass:
2803 case Expr::AddrLabelExprClass:
2804 case Expr::StmtExprClass:
2805 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002806 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002807 case Expr::CXXDynamicCastExprClass:
2808 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002809 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002810 case Expr::CXXNullPtrLiteralExprClass:
2811 case Expr::CXXThisExprClass:
2812 case Expr::CXXThrowExprClass:
2813 case Expr::CXXNewExprClass:
2814 case Expr::CXXDeleteExprClass:
2815 case Expr::CXXPseudoDestructorExprClass:
2816 case Expr::UnresolvedLookupExprClass:
2817 case Expr::DependentScopeDeclRefExprClass:
2818 case Expr::CXXConstructExprClass:
2819 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002820 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002821 case Expr::CXXTemporaryObjectExprClass:
2822 case Expr::CXXUnresolvedConstructExprClass:
2823 case Expr::CXXDependentScopeMemberExprClass:
2824 case Expr::UnresolvedMemberExprClass:
2825 case Expr::ObjCStringLiteralClass:
2826 case Expr::ObjCEncodeExprClass:
2827 case Expr::ObjCMessageExprClass:
2828 case Expr::ObjCSelectorExprClass:
2829 case Expr::ObjCProtocolExprClass:
2830 case Expr::ObjCIvarRefExprClass:
2831 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002832 case Expr::ObjCIsaExprClass:
2833 case Expr::ShuffleVectorExprClass:
2834 case Expr::BlockExprClass:
2835 case Expr::BlockDeclRefExprClass:
2836 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002837 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002838 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002839 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002840 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002841 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002842 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002843 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00002844 return ICEDiag(2, E->getLocStart());
2845
Sebastian Redl12757ab2011-09-24 17:48:14 +00002846 case Expr::InitListExprClass:
2847 if (Ctx.getLangOptions().CPlusPlus0x) {
2848 const InitListExpr *ILE = cast<InitListExpr>(E);
2849 if (ILE->getNumInits() == 0)
2850 return NoDiag();
2851 if (ILE->getNumInits() == 1)
2852 return CheckICE(ILE->getInit(0), Ctx);
2853 // Fall through for more than 1 expression.
2854 }
2855 return ICEDiag(2, E->getLocStart());
2856
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002857 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002858 case Expr::GNUNullExprClass:
2859 // GCC considers the GNU __null value to be an integral constant expression.
2860 return NoDiag();
2861
John McCall7c454bb2011-07-15 05:09:51 +00002862 case Expr::SubstNonTypeTemplateParmExprClass:
2863 return
2864 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2865
John McCall864e3962010-05-07 05:32:02 +00002866 case Expr::ParenExprClass:
2867 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002868 case Expr::GenericSelectionExprClass:
2869 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002870 case Expr::IntegerLiteralClass:
2871 case Expr::CharacterLiteralClass:
2872 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002873 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002874 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002875 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002876 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002877 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002878 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002879 return NoDiag();
2880 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002881 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002882 const CallExpr *CE = cast<CallExpr>(E);
2883 if (CE->isBuiltinCall(Ctx))
2884 return CheckEvalInICE(E, Ctx);
2885 return ICEDiag(2, E->getLocStart());
2886 }
2887 case Expr::DeclRefExprClass:
2888 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2889 return NoDiag();
2890 if (Ctx.getLangOptions().CPlusPlus &&
2891 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2892 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2893
2894 // Parameter variables are never constants. Without this check,
2895 // getAnyInitializer() can find a default argument, which leads
2896 // to chaos.
2897 if (isa<ParmVarDecl>(D))
2898 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2899
2900 // C++ 7.1.5.1p2
2901 // A variable of non-volatile const-qualified integral or enumeration
2902 // type initialized by an ICE can be used in ICEs.
2903 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2904 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2905 if (Quals.hasVolatile() || !Quals.hasConst())
2906 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2907
2908 // Look for a declaration of this variable that has an initializer.
2909 const VarDecl *ID = 0;
2910 const Expr *Init = Dcl->getAnyInitializer(ID);
2911 if (Init) {
2912 if (ID->isInitKnownICE()) {
2913 // We have already checked whether this subexpression is an
2914 // integral constant expression.
2915 if (ID->isInitICE())
2916 return NoDiag();
2917 else
2918 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2919 }
2920
2921 // It's an ICE whether or not the definition we found is
2922 // out-of-line. See DR 721 and the discussion in Clang PR
2923 // 6206 for details.
2924
2925 if (Dcl->isCheckingICE()) {
2926 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2927 }
2928
2929 Dcl->setCheckingICE();
2930 ICEDiag Result = CheckICE(Init, Ctx);
2931 // Cache the result of the ICE test.
2932 Dcl->setInitKnownICE(Result.Val == 0);
2933 return Result;
2934 }
2935 }
2936 }
2937 return ICEDiag(2, E->getLocStart());
2938 case Expr::UnaryOperatorClass: {
2939 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2940 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002941 case UO_PostInc:
2942 case UO_PostDec:
2943 case UO_PreInc:
2944 case UO_PreDec:
2945 case UO_AddrOf:
2946 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002947 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002948 case UO_Extension:
2949 case UO_LNot:
2950 case UO_Plus:
2951 case UO_Minus:
2952 case UO_Not:
2953 case UO_Real:
2954 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00002955 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002956 }
2957
2958 // OffsetOf falls through here.
2959 }
2960 case Expr::OffsetOfExprClass: {
2961 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2962 // Evaluate matches the proposed gcc behavior for cases like
2963 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2964 // compliance: we should warn earlier for offsetof expressions with
2965 // array subscripts that aren't ICEs, and if the array subscripts
2966 // are ICEs, the value of the offsetof must be an integer constant.
2967 return CheckEvalInICE(E, Ctx);
2968 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002969 case Expr::UnaryExprOrTypeTraitExprClass: {
2970 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2971 if ((Exp->getKind() == UETT_SizeOf) &&
2972 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00002973 return ICEDiag(2, E->getLocStart());
2974 return NoDiag();
2975 }
2976 case Expr::BinaryOperatorClass: {
2977 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2978 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002979 case BO_PtrMemD:
2980 case BO_PtrMemI:
2981 case BO_Assign:
2982 case BO_MulAssign:
2983 case BO_DivAssign:
2984 case BO_RemAssign:
2985 case BO_AddAssign:
2986 case BO_SubAssign:
2987 case BO_ShlAssign:
2988 case BO_ShrAssign:
2989 case BO_AndAssign:
2990 case BO_XorAssign:
2991 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00002992 return ICEDiag(2, E->getLocStart());
2993
John McCalle3027922010-08-25 11:45:40 +00002994 case BO_Mul:
2995 case BO_Div:
2996 case BO_Rem:
2997 case BO_Add:
2998 case BO_Sub:
2999 case BO_Shl:
3000 case BO_Shr:
3001 case BO_LT:
3002 case BO_GT:
3003 case BO_LE:
3004 case BO_GE:
3005 case BO_EQ:
3006 case BO_NE:
3007 case BO_And:
3008 case BO_Xor:
3009 case BO_Or:
3010 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003011 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3012 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003013 if (Exp->getOpcode() == BO_Div ||
3014 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003015 // Evaluate gives an error for undefined Div/Rem, so make sure
3016 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003017 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003018 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003019 if (REval == 0)
3020 return ICEDiag(1, E->getLocStart());
3021 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003022 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003023 if (LEval.isMinSignedValue())
3024 return ICEDiag(1, E->getLocStart());
3025 }
3026 }
3027 }
John McCalle3027922010-08-25 11:45:40 +00003028 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003029 if (Ctx.getLangOptions().C99) {
3030 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3031 // if it isn't evaluated.
3032 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3033 return ICEDiag(1, E->getLocStart());
3034 } else {
3035 // In both C89 and C++, commas in ICEs are illegal.
3036 return ICEDiag(2, E->getLocStart());
3037 }
3038 }
3039 if (LHSResult.Val >= RHSResult.Val)
3040 return LHSResult;
3041 return RHSResult;
3042 }
John McCalle3027922010-08-25 11:45:40 +00003043 case BO_LAnd:
3044 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003045 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003046
3047 // C++0x [expr.const]p2:
3048 // [...] subexpressions of logical AND (5.14), logical OR
3049 // (5.15), and condi- tional (5.16) operations that are not
3050 // evaluated are not considered.
3051 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3052 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003053 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003054 return LHSResult;
3055
3056 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003057 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003058 return LHSResult;
3059 }
3060
John McCall864e3962010-05-07 05:32:02 +00003061 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3062 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3063 // Rare case where the RHS has a comma "side-effect"; we need
3064 // to actually check the condition to see whether the side
3065 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003066 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003067 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003068 return RHSResult;
3069 return NoDiag();
3070 }
3071
3072 if (LHSResult.Val >= RHSResult.Val)
3073 return LHSResult;
3074 return RHSResult;
3075 }
3076 }
3077 }
3078 case Expr::ImplicitCastExprClass:
3079 case Expr::CStyleCastExprClass:
3080 case Expr::CXXFunctionalCastExprClass:
3081 case Expr::CXXStaticCastExprClass:
3082 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003083 case Expr::CXXConstCastExprClass:
3084 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003085 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman76d4e432011-09-29 21:49:34 +00003086 switch (cast<CastExpr>(E)->getCastKind()) {
3087 case CK_LValueToRValue:
3088 case CK_NoOp:
3089 case CK_IntegralToBoolean:
3090 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003091 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003092 default:
3093 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3094 return NoDiag();
3095 return ICEDiag(2, E->getLocStart());
3096 }
John McCall864e3962010-05-07 05:32:02 +00003097 }
John McCallc07a0c72011-02-17 10:25:35 +00003098 case Expr::BinaryConditionalOperatorClass: {
3099 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3100 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3101 if (CommonResult.Val == 2) return CommonResult;
3102 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3103 if (FalseResult.Val == 2) return FalseResult;
3104 if (CommonResult.Val == 1) return CommonResult;
3105 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003106 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003107 return FalseResult;
3108 }
John McCall864e3962010-05-07 05:32:02 +00003109 case Expr::ConditionalOperatorClass: {
3110 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3111 // If the condition (ignoring parens) is a __builtin_constant_p call,
3112 // then only the true side is actually considered in an integer constant
3113 // expression, and it is fully evaluated. This is an important GNU
3114 // extension. See GCC PR38377 for discussion.
3115 if (const CallExpr *CallCE
3116 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3117 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3118 Expr::EvalResult EVResult;
3119 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3120 !EVResult.Val.isInt()) {
3121 return ICEDiag(2, E->getLocStart());
3122 }
3123 return NoDiag();
3124 }
3125 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003126 if (CondResult.Val == 2)
3127 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003128
3129 // C++0x [expr.const]p2:
3130 // subexpressions of [...] conditional (5.16) operations that
3131 // are not evaluated are not considered
3132 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003133 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003134 : false;
3135 ICEDiag TrueResult = NoDiag();
3136 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3137 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3138 ICEDiag FalseResult = NoDiag();
3139 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3140 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3141
John McCall864e3962010-05-07 05:32:02 +00003142 if (TrueResult.Val == 2)
3143 return TrueResult;
3144 if (FalseResult.Val == 2)
3145 return FalseResult;
3146 if (CondResult.Val == 1)
3147 return CondResult;
3148 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3149 return NoDiag();
3150 // Rare case where the diagnostics depend on which side is evaluated
3151 // Note that if we get here, CondResult is 0, and at least one of
3152 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003153 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003154 return FalseResult;
3155 }
3156 return TrueResult;
3157 }
3158 case Expr::CXXDefaultArgExprClass:
3159 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3160 case Expr::ChooseExprClass: {
3161 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3162 }
3163 }
3164
3165 // Silence a GCC warning
3166 return ICEDiag(2, E->getLocStart());
3167}
3168
3169bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3170 SourceLocation *Loc, bool isEvaluated) const {
3171 ICEDiag d = CheckICE(this, Ctx);
3172 if (d.Val != 0) {
3173 if (Loc) *Loc = d.Loc;
3174 return false;
3175 }
3176 EvalResult EvalResult;
3177 if (!Evaluate(EvalResult, Ctx))
3178 llvm_unreachable("ICE cannot be evaluated!");
3179 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3180 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3181 Result = EvalResult.Val.getInt();
3182 return true;
3183}