blob: f108c1a30ebc97dc50b34efd2c68f98bbf27eb17 [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
Richard Smith725810a2011-10-16 21:26:27 +000049 /// EvalStatus - Contains information about the evaluation.
50 Expr::EvalStatus &EvalStatus;
Benjamin Kramer024e6192011-03-04 13:12:48 +000051
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
Richard Smith725810a2011-10-16 21:26:27 +000060 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
61 : Ctx(C), EvalStatus(S) {}
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
Richard Smith725810a2011-10-16 21:26:27 +0000124static bool Evaluate(APValue &Result, 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> {
Richard Smith725810a2011-10-16 21:26:27 +0000267 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000268public:
269
Richard Smith725810a2011-10-16 21:26:27 +0000270 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000271
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) {
Richard Smith725810a2011-10-16 21:26:27 +0000282 if (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) {
Richard Smith725810a2011-10-16 21:26:27 +0000287 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000288 return true;
289 return false;
290 }
291 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000292 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000293 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)
Richard Smith725810a2011-10-16 21:26:27 +0000313 { return Visit(E->getChosenSubExpr(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) {
Richard Smith725810a2011-10-16 21:26:27 +0000324 if (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.
Richard Smith725810a2011-10-16 21:26:27 +0000352 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000353 this->opaqueValue = 0;
354 return;
355 }
John McCallc07a0c72011-02-17 10:25:35 +0000356 }
357
358 bool hasError() const { return opaqueValue == 0; }
359
360 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000361 // FIXME: This will not work for recursive constexpr functions using opaque
362 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000363 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
364 }
365};
366
Mike Stump876387b2009-10-27 22:09:17 +0000367} // end anonymous namespace
368
Eli Friedman9a156e52008-11-12 09:44:48 +0000369//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000370// Generic Evaluation
371//===----------------------------------------------------------------------===//
372namespace {
373
374template <class Derived, typename RetTy=void>
375class ExprEvaluatorBase
376 : public ConstStmtVisitor<Derived, RetTy> {
377private:
378 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
379 return static_cast<Derived*>(this)->Success(V, E);
380 }
381 RetTy DerivedError(const Expr *E) {
382 return static_cast<Derived*>(this)->Error(E);
383 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000384 RetTy DerivedValueInitialization(const Expr *E) {
385 return static_cast<Derived*>(this)->ValueInitialization(E);
386 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000387
388protected:
389 EvalInfo &Info;
390 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
391 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
392
Richard Smith4ce706a2011-10-11 21:43:33 +0000393 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
394
Peter Collingbournee9200682011-05-13 03:29:01 +0000395public:
396 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
397
398 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000399 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000400 }
401 RetTy VisitExpr(const Expr *E) {
402 return DerivedError(E);
403 }
404
405 RetTy VisitParenExpr(const ParenExpr *E)
406 { return StmtVisitorTy::Visit(E->getSubExpr()); }
407 RetTy VisitUnaryExtension(const UnaryOperator *E)
408 { return StmtVisitorTy::Visit(E->getSubExpr()); }
409 RetTy VisitUnaryPlus(const UnaryOperator *E)
410 { return StmtVisitorTy::Visit(E->getSubExpr()); }
411 RetTy VisitChooseExpr(const ChooseExpr *E)
412 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
413 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
414 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000415 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
416 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000417
418 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
419 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
420 if (opaque.hasError())
421 return DerivedError(E);
422
423 bool cond;
424 if (!HandleConversionToBool(E->getCond(), cond, Info))
425 return DerivedError(E);
426
427 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
428 }
429
430 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
431 bool BoolResult;
432 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
433 return DerivedError(E);
434
435 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
436 return StmtVisitorTy::Visit(EvalExpr);
437 }
438
439 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
440 const APValue *value = Info.getOpaqueValue(E);
441 if (!value)
442 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
443 : DerivedError(E));
444 return DerivedSuccess(*value, E);
445 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000446
447 RetTy VisitInitListExpr(const InitListExpr *E) {
448 if (Info.getLangOpts().CPlusPlus0x) {
449 if (E->getNumInits() == 0)
450 return DerivedValueInitialization(E);
451 if (E->getNumInits() == 1)
452 return StmtVisitorTy::Visit(E->getInit(0));
453 }
454 return DerivedError(E);
455 }
456 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
457 return DerivedValueInitialization(E);
458 }
459 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
460 return DerivedValueInitialization(E);
461 }
462
Peter Collingbournee9200682011-05-13 03:29:01 +0000463};
464
465}
466
467//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000468// LValue Evaluation
469//===----------------------------------------------------------------------===//
470namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000471class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000472 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000473 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000474 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000475
Peter Collingbournee9200682011-05-13 03:29:01 +0000476 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000477 Result.Base = E;
478 Result.Offset = CharUnits::Zero();
479 return true;
480 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000481public:
Mike Stump11289f42009-09-09 15:08:12 +0000482
John McCall45d55e42010-05-07 21:00:08 +0000483 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000484 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000485
Peter Collingbournee9200682011-05-13 03:29:01 +0000486 bool Success(const APValue &V, const Expr *E) {
487 Result.setFrom(V);
488 return true;
489 }
490 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000491 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000492 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000493
Peter Collingbournee9200682011-05-13 03:29:01 +0000494 bool VisitDeclRefExpr(const DeclRefExpr *E);
495 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
496 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
497 bool VisitMemberExpr(const MemberExpr *E);
498 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
499 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
500 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
501 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000502
Peter Collingbournee9200682011-05-13 03:29:01 +0000503 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000504 switch (E->getCastKind()) {
505 default:
John McCall45d55e42010-05-07 21:00:08 +0000506 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000507
John McCalle3027922010-08-25 11:45:40 +0000508 case CK_NoOp:
Eli Friedmance3e02a2011-10-11 00:13:24 +0000509 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000510 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000511
512 // FIXME: Support CK_DerivedToBase and friends.
Anders Carlssonde55f642009-10-03 16:30:22 +0000513 }
514 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000515
Eli Friedman449fe542009-03-23 04:56:01 +0000516 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000517
Eli Friedman9a156e52008-11-12 09:44:48 +0000518};
519} // end anonymous namespace
520
John McCall45d55e42010-05-07 21:00:08 +0000521static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000522 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000523}
524
Peter Collingbournee9200682011-05-13 03:29:01 +0000525bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000526 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000527 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000528 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000529 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000530 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000531 // Reference parameters can refer to anything even if they have an
532 // "initializer" in the form of a default argument.
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000533 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000534 // FIXME: Check whether VD might be overridden!
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000535
536 // Check for recursive initializers of references.
537 if (PrevDecl == VD)
538 return Error(E);
539 PrevDecl = VD;
Peter Collingbournee9200682011-05-13 03:29:01 +0000540 if (const Expr *Init = VD->getAnyInitializer())
541 return Visit(Init);
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000542 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000543 }
544
Peter Collingbournee9200682011-05-13 03:29:01 +0000545 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000546}
547
Peter Collingbournee9200682011-05-13 03:29:01 +0000548bool
549LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000550 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000551}
552
Peter Collingbournee9200682011-05-13 03:29:01 +0000553bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000554 QualType Ty;
555 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000556 if (!EvaluatePointer(E->getBase(), Result, Info))
557 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000558 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000559 } else {
John McCall45d55e42010-05-07 21:00:08 +0000560 if (!Visit(E->getBase()))
561 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000562 Ty = E->getBase()->getType();
563 }
564
Peter Collingbournee9200682011-05-13 03:29:01 +0000565 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000566 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000567
Peter Collingbournee9200682011-05-13 03:29:01 +0000568 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000569 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000570 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000571
572 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000573 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000574
Eli Friedmana3c122d2011-07-07 01:54:01 +0000575 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000576 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000577 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000578}
579
Peter Collingbournee9200682011-05-13 03:29:01 +0000580bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000581 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000582 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000583
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000584 APSInt Index;
585 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000586 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000587
Ken Dyck40775002010-01-11 17:06:35 +0000588 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000589 Result.Offset += Index.getSExtValue() * ElementSize;
590 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000591}
Eli Friedman9a156e52008-11-12 09:44:48 +0000592
Peter Collingbournee9200682011-05-13 03:29:01 +0000593bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000594 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000595}
596
Eli Friedman9a156e52008-11-12 09:44:48 +0000597//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000598// Pointer Evaluation
599//===----------------------------------------------------------------------===//
600
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000601namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000602class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000604 LValue &Result;
605
Peter Collingbournee9200682011-05-13 03:29:01 +0000606 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000607 Result.Base = E;
608 Result.Offset = CharUnits::Zero();
609 return true;
610 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000611public:
Mike Stump11289f42009-09-09 15:08:12 +0000612
John McCall45d55e42010-05-07 21:00:08 +0000613 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000614 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000615
Peter Collingbournee9200682011-05-13 03:29:01 +0000616 bool Success(const APValue &V, const Expr *E) {
617 Result.setFrom(V);
618 return true;
619 }
620 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000621 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000622 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000623 bool ValueInitialization(const Expr *E) {
624 return Success((Expr*)0);
625 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000626
John McCall45d55e42010-05-07 21:00:08 +0000627 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000628 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000629 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000630 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000631 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000632 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000633 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000634 bool VisitCallExpr(const CallExpr *E);
635 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000636 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000637 return Success(E);
638 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000639 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000640 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +0000641 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +0000642
Eli Friedman449fe542009-03-23 04:56:01 +0000643 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000644};
Chris Lattner05706e882008-07-11 18:11:29 +0000645} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000646
John McCall45d55e42010-05-07 21:00:08 +0000647static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000648 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000649 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000650}
651
John McCall45d55e42010-05-07 21:00:08 +0000652bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000653 if (E->getOpcode() != BO_Add &&
654 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000655 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000656
Chris Lattner05706e882008-07-11 18:11:29 +0000657 const Expr *PExp = E->getLHS();
658 const Expr *IExp = E->getRHS();
659 if (IExp->getType()->isPointerType())
660 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000661
John McCall45d55e42010-05-07 21:00:08 +0000662 if (!EvaluatePointer(PExp, Result, Info))
663 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000664
John McCall45d55e42010-05-07 21:00:08 +0000665 llvm::APSInt Offset;
666 if (!EvaluateInteger(IExp, Offset, Info))
667 return false;
668 int64_t AdditionalOffset
669 = Offset.isSigned() ? Offset.getSExtValue()
670 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000671
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000672 // Compute the new offset in the appropriate width.
673
674 QualType PointeeType =
675 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000676 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000677
Anders Carlssonef56fba2009-02-19 04:55:58 +0000678 // Explicitly handle GNU void* and function pointer arithmetic extensions.
679 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000680 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000681 else
John McCall45d55e42010-05-07 21:00:08 +0000682 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000683
John McCalle3027922010-08-25 11:45:40 +0000684 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000685 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000686 else
John McCall45d55e42010-05-07 21:00:08 +0000687 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000688
John McCall45d55e42010-05-07 21:00:08 +0000689 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000690}
Eli Friedman9a156e52008-11-12 09:44:48 +0000691
John McCall45d55e42010-05-07 21:00:08 +0000692bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
693 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000694}
Mike Stump11289f42009-09-09 15:08:12 +0000695
Chris Lattner05706e882008-07-11 18:11:29 +0000696
Peter Collingbournee9200682011-05-13 03:29:01 +0000697bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
698 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000699
Eli Friedman847a2bc2009-12-27 05:43:15 +0000700 switch (E->getCastKind()) {
701 default:
702 break;
703
John McCalle3027922010-08-25 11:45:40 +0000704 case CK_NoOp:
705 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +0000706 case CK_CPointerToObjCPointerCast:
707 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +0000708 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000709 return Visit(SubExpr);
710
Anders Carlsson18275092010-10-31 20:41:46 +0000711 case CK_DerivedToBase:
712 case CK_UncheckedDerivedToBase: {
713 LValue BaseLV;
714 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
715 return false;
716
717 // Now figure out the necessary offset to add to the baseLV to get from
718 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000719 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000720
721 QualType Ty = E->getSubExpr()->getType();
722 const CXXRecordDecl *DerivedDecl =
723 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
724
725 for (CastExpr::path_const_iterator PathI = E->path_begin(),
726 PathE = E->path_end(); PathI != PathE; ++PathI) {
727 const CXXBaseSpecifier *Base = *PathI;
728
729 // FIXME: If the base is virtual, we'd need to determine the type of the
730 // most derived class and we don't support that right now.
731 if (Base->isVirtual())
732 return false;
733
734 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
735 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
736
Ken Dyck02155cb2011-01-26 02:17:08 +0000737 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000738 DerivedDecl = BaseDecl;
739 }
740
741 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000742 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000743 return true;
744 }
745
John McCalle84af4e2010-11-13 01:35:44 +0000746 case CK_NullToPointer: {
747 Result.Base = 0;
748 Result.Offset = CharUnits::Zero();
749 return true;
750 }
751
John McCalle3027922010-08-25 11:45:40 +0000752 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000753 APValue Value;
754 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000755 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000756
John McCall45d55e42010-05-07 21:00:08 +0000757 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000758 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000759 Result.Base = 0;
760 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
761 return true;
762 } else {
763 // Cast is of an lvalue, no need to change value.
764 Result.Base = Value.getLValueBase();
765 Result.Offset = Value.getLValueOffset();
766 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000767 }
768 }
John McCalle3027922010-08-25 11:45:40 +0000769 case CK_ArrayToPointerDecay:
770 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000771 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000772 }
773
John McCall45d55e42010-05-07 21:00:08 +0000774 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000775}
Chris Lattner05706e882008-07-11 18:11:29 +0000776
Peter Collingbournee9200682011-05-13 03:29:01 +0000777bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000778 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000779 Builtin::BI__builtin___CFStringMakeConstantString ||
780 E->isBuiltinCall(Info.Ctx) ==
781 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000782 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000783
Peter Collingbournee9200682011-05-13 03:29:01 +0000784 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000785}
Chris Lattner05706e882008-07-11 18:11:29 +0000786
787//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000788// Vector Evaluation
789//===----------------------------------------------------------------------===//
790
791namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000792 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +0000793 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
794 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000795 public:
Mike Stump11289f42009-09-09 15:08:12 +0000796
Richard Smith2d406342011-10-22 21:10:00 +0000797 VectorExprEvaluator(EvalInfo &info, APValue &Result)
798 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +0000799
Richard Smith2d406342011-10-22 21:10:00 +0000800 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
801 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
802 // FIXME: remove this APValue copy.
803 Result = APValue(V.data(), V.size());
804 return true;
805 }
806 bool Success(const APValue &V, const Expr *E) {
807 Result = V;
808 return true;
809 }
810 bool Error(const Expr *E) { return false; }
811 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +0000812
Richard Smith2d406342011-10-22 21:10:00 +0000813 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +0000814 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +0000815 bool VisitCastExpr(const CastExpr* E);
816 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
817 bool VisitInitListExpr(const InitListExpr *E);
818 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000819 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000820 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000821 // shufflevector, ExtVectorElementExpr
822 // (Note that these require implementing conversions
823 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000824 };
825} // end anonymous namespace
826
827static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
828 if (!E->getType()->isVectorType())
829 return false;
Richard Smith2d406342011-10-22 21:10:00 +0000830 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000831}
832
Richard Smith2d406342011-10-22 21:10:00 +0000833bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
834 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000835 QualType EltTy = VTy->getElementType();
836 unsigned NElts = VTy->getNumElements();
837 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000838
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000839 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000840 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000841
Eli Friedmanc757de22011-03-25 00:43:55 +0000842 switch (E->getCastKind()) {
843 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +0000844 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000845 if (SETy->isIntegerType()) {
846 APSInt IntResult;
847 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000848 return Error(E);
849 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +0000850 } else if (SETy->isRealFloatingType()) {
851 APFloat F(0.0);
852 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000853 return Error(E);
854 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +0000855 } else {
Richard Smith2d406342011-10-22 21:10:00 +0000856 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +0000857 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000858
859 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +0000860 SmallVector<APValue, 4> Elts(NElts, Val);
861 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +0000862 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000863 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +0000864 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +0000865 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000866 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000867
Eli Friedmanc757de22011-03-25 00:43:55 +0000868 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +0000869 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +0000870
Eli Friedmanc757de22011-03-25 00:43:55 +0000871 APSInt Init;
872 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000873 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000874
Eli Friedmanc757de22011-03-25 00:43:55 +0000875 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
876 "Vectors must be composed of ints or floats");
877
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000878 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +0000879 for (unsigned i = 0; i != NElts; ++i) {
880 APSInt Tmp = Init.extOrTrunc(EltWidth);
881
882 if (EltTy->isIntegerType())
883 Elts.push_back(APValue(Tmp));
884 else
885 Elts.push_back(APValue(APFloat(Tmp)));
886
887 Init >>= EltWidth;
888 }
Richard Smith2d406342011-10-22 21:10:00 +0000889 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000890 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000891 case CK_LValueToRValue:
892 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000893 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000894 default:
Richard Smith2d406342011-10-22 21:10:00 +0000895 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +0000896 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000897}
898
Richard Smith2d406342011-10-22 21:10:00 +0000899bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000900VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +0000901 return Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000902}
903
Richard Smith2d406342011-10-22 21:10:00 +0000904bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000905VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +0000906 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000907 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000908 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000909
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000910 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000911 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000912
John McCall875679e2010-06-11 17:54:15 +0000913 // If a vector is initialized with a single element, that value
914 // becomes every element of the vector, not just the first.
915 // This is the behavior described in the IBM AltiVec documentation.
916 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +0000917
918 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000919 // vector (OpenCL 6.1.6).
920 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +0000921 return Visit(E->getInit(0));
922
John McCall875679e2010-06-11 17:54:15 +0000923 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000924 if (EltTy->isIntegerType()) {
925 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000926 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000927 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000928 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000929 } else {
930 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000931 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000932 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000933 InitValue = APValue(f);
934 }
935 for (unsigned i = 0; i < NumElements; i++) {
936 Elements.push_back(InitValue);
937 }
938 } else {
939 for (unsigned i = 0; i < NumElements; i++) {
940 if (EltTy->isIntegerType()) {
941 llvm::APSInt sInt(32);
942 if (i < NumInits) {
943 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000944 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000945 } else {
946 sInt = Info.Ctx.MakeIntValue(0, EltTy);
947 }
948 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000949 } else {
John McCall875679e2010-06-11 17:54:15 +0000950 llvm::APFloat f(0.0);
951 if (i < NumInits) {
952 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000953 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000954 } else {
955 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
956 }
957 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000958 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000959 }
960 }
Richard Smith2d406342011-10-22 21:10:00 +0000961 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000962}
963
Richard Smith2d406342011-10-22 21:10:00 +0000964bool
965VectorExprEvaluator::ValueInitialization(const Expr *E) {
966 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000967 QualType EltTy = VT->getElementType();
968 APValue ZeroElement;
969 if (EltTy->isIntegerType())
970 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
971 else
972 ZeroElement =
973 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
974
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000975 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +0000976 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000977}
978
Richard Smith2d406342011-10-22 21:10:00 +0000979bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000980 APValue Scratch;
981 if (!Evaluate(Scratch, Info, E->getSubExpr()))
982 Info.EvalStatus.HasSideEffects = true;
Richard Smith2d406342011-10-22 21:10:00 +0000983 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000984}
985
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000986//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000987// Integer Evaluation
988//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000989
990namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000991class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000992 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000993 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000994public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000995 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000996 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000997
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000998 bool Success(const llvm::APSInt &SI, const Expr *E) {
999 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001000 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001001 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001002 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001003 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001004 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001005 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001006 return true;
1007 }
1008
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001009 bool Success(const llvm::APInt &I, 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 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001013 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001014 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001015 Result.getInt().setIsUnsigned(
1016 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001017 return true;
1018 }
1019
1020 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001021 assert(E->getType()->isIntegralOrEnumerationType() &&
1022 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001023 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001024 return true;
1025 }
1026
Ken Dyckdbc01912011-03-11 02:13:43 +00001027 bool Success(CharUnits Size, const Expr *E) {
1028 return Success(Size.getQuantity(), E);
1029 }
1030
1031
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001032 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001033 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001034 if (Info.EvalStatus.Diag == 0) {
1035 Info.EvalStatus.DiagLoc = L;
1036 Info.EvalStatus.Diag = D;
1037 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001038 }
Chris Lattner99415702008-07-12 00:14:42 +00001039 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001040 }
Mike Stump11289f42009-09-09 15:08:12 +00001041
Peter Collingbournee9200682011-05-13 03:29:01 +00001042 bool Success(const APValue &V, const Expr *E) {
1043 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001044 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001045 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001046 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001047 }
Mike Stump11289f42009-09-09 15:08:12 +00001048
Richard Smith4ce706a2011-10-11 21:43:33 +00001049 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1050
Peter Collingbournee9200682011-05-13 03:29:01 +00001051 //===--------------------------------------------------------------------===//
1052 // Visitor Methods
1053 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001054
Chris Lattner7174bf32008-07-12 00:38:25 +00001055 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001056 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001057 }
1058 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001059 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001060 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001061
1062 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1063 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001064 if (CheckReferencedDecl(E, E->getDecl()))
1065 return true;
1066
1067 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001068 }
1069 bool VisitMemberExpr(const MemberExpr *E) {
1070 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1071 // Conservatively assume a MemberExpr will have side-effects
Richard Smith725810a2011-10-16 21:26:27 +00001072 Info.EvalStatus.HasSideEffects = true;
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001073 return true;
1074 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001075
1076 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001077 }
1078
Peter Collingbournee9200682011-05-13 03:29:01 +00001079 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001080 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001081 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001082 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001083
Peter Collingbournee9200682011-05-13 03:29:01 +00001084 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001085 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001086
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001087 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001088 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001089 }
Mike Stump11289f42009-09-09 15:08:12 +00001090
Richard Smith4ce706a2011-10-11 21:43:33 +00001091 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001092 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001093 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001094 }
1095
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001096 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001097 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001098 }
1099
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001100 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1101 return Success(E->getValue(), E);
1102 }
1103
John Wiegley6242b6a2011-04-28 00:16:57 +00001104 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1105 return Success(E->getValue(), E);
1106 }
1107
John Wiegleyf9f65842011-04-25 06:54:41 +00001108 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1109 return Success(E->getValue(), E);
1110 }
1111
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001112 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001113 bool VisitUnaryImag(const UnaryOperator *E);
1114
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001115 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001116 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001117
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001118private:
Ken Dyck160146e2010-01-27 17:10:57 +00001119 CharUnits GetAlignOfExpr(const Expr *E);
1120 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001121 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001122 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001123 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001124};
Chris Lattner05706e882008-07-11 18:11:29 +00001125} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001126
Daniel Dunbarce399542009-02-20 18:22:23 +00001127static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001128 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001129 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001130}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001131
Daniel Dunbarce399542009-02-20 18:22:23 +00001132static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001133 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001134
Daniel Dunbarce399542009-02-20 18:22:23 +00001135 APValue Val;
1136 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1137 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001138 Result = Val.getInt();
1139 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001140}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001141
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001142bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001143 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001144 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001145 // Check for signedness/width mismatches between E type and ECD value.
1146 bool SameSign = (ECD->getInitVal().isSigned()
1147 == E->getType()->isSignedIntegerOrEnumerationType());
1148 bool SameWidth = (ECD->getInitVal().getBitWidth()
1149 == Info.Ctx.getIntWidth(E->getType()));
1150 if (SameSign && SameWidth)
1151 return Success(ECD->getInitVal(), E);
1152 else {
1153 // Get rid of mismatch (otherwise Success assertions will fail)
1154 // by computing a new value matching the type of E.
1155 llvm::APSInt Val = ECD->getInitVal();
1156 if (!SameSign)
1157 Val.setIsSigned(!ECD->getInitVal().isSigned());
1158 if (!SameWidth)
1159 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1160 return Success(Val, E);
1161 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001162 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001163
1164 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001165 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001166 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1167 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001168
1169 if (isa<ParmVarDecl>(D))
Peter Collingbournee9200682011-05-13 03:29:01 +00001170 return false;
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001171
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001172 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001173 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001174 if (APValue *V = VD->getEvaluatedValue()) {
1175 if (V->isInt())
1176 return Success(V->getInt(), E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001177 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001178 }
1179
1180 if (VD->isEvaluatingValue())
Peter Collingbournee9200682011-05-13 03:29:01 +00001181 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001182
1183 VD->setEvaluatingValue();
1184
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001185 Expr::EvalResult EResult;
Richard Smith725810a2011-10-16 21:26:27 +00001186 // FIXME: Produce a diagnostic if the initializer isn't a constant
1187 // expression.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001188 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1189 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001190 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001191 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001192 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001193 return true;
1194 }
1195
Eli Friedman1d6fb162009-12-03 20:31:57 +00001196 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001197 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001198 }
1199 }
1200
Chris Lattner7174bf32008-07-12 00:38:25 +00001201 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001202 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001203}
1204
Chris Lattner86ee2862008-10-06 06:40:35 +00001205/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1206/// as GCC.
1207static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1208 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001209 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001210 enum gcc_type_class {
1211 no_type_class = -1,
1212 void_type_class, integer_type_class, char_type_class,
1213 enumeral_type_class, boolean_type_class,
1214 pointer_type_class, reference_type_class, offset_type_class,
1215 real_type_class, complex_type_class,
1216 function_type_class, method_type_class,
1217 record_type_class, union_type_class,
1218 array_type_class, string_type_class,
1219 lang_type_class
1220 };
Mike Stump11289f42009-09-09 15:08:12 +00001221
1222 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001223 // ideal, however it is what gcc does.
1224 if (E->getNumArgs() == 0)
1225 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001226
Chris Lattner86ee2862008-10-06 06:40:35 +00001227 QualType ArgTy = E->getArg(0)->getType();
1228 if (ArgTy->isVoidType())
1229 return void_type_class;
1230 else if (ArgTy->isEnumeralType())
1231 return enumeral_type_class;
1232 else if (ArgTy->isBooleanType())
1233 return boolean_type_class;
1234 else if (ArgTy->isCharType())
1235 return string_type_class; // gcc doesn't appear to use char_type_class
1236 else if (ArgTy->isIntegerType())
1237 return integer_type_class;
1238 else if (ArgTy->isPointerType())
1239 return pointer_type_class;
1240 else if (ArgTy->isReferenceType())
1241 return reference_type_class;
1242 else if (ArgTy->isRealType())
1243 return real_type_class;
1244 else if (ArgTy->isComplexType())
1245 return complex_type_class;
1246 else if (ArgTy->isFunctionType())
1247 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001248 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001249 return record_type_class;
1250 else if (ArgTy->isUnionType())
1251 return union_type_class;
1252 else if (ArgTy->isArrayType())
1253 return array_type_class;
1254 else if (ArgTy->isUnionType())
1255 return union_type_class;
1256 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001257 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001258 return -1;
1259}
1260
John McCall95007602010-05-10 23:27:23 +00001261/// Retrieves the "underlying object type" of the given expression,
1262/// as used by __builtin_object_size.
1263QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1264 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1265 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1266 return VD->getType();
1267 } else if (isa<CompoundLiteralExpr>(E)) {
1268 return E->getType();
1269 }
1270
1271 return QualType();
1272}
1273
Peter Collingbournee9200682011-05-13 03:29:01 +00001274bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001275 // TODO: Perhaps we should let LLVM lower this?
1276 LValue Base;
1277 if (!EvaluatePointer(E->getArg(0), Base, Info))
1278 return false;
1279
1280 // If we can prove the base is null, lower to zero now.
1281 const Expr *LVBase = Base.getLValueBase();
1282 if (!LVBase) return Success(0, E);
1283
1284 QualType T = GetObjectType(LVBase);
1285 if (T.isNull() ||
1286 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001287 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001288 T->isVariablyModifiedType() ||
1289 T->isDependentType())
1290 return false;
1291
1292 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1293 CharUnits Offset = Base.getLValueOffset();
1294
1295 if (!Offset.isNegative() && Offset <= Size)
1296 Size -= Offset;
1297 else
1298 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001299 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001300}
1301
Peter Collingbournee9200682011-05-13 03:29:01 +00001302bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001303 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001304 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001305 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001306
1307 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001308 if (TryEvaluateBuiltinObjectSize(E))
1309 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001310
Eric Christopher99469702010-01-19 22:58:35 +00001311 // If evaluating the argument has side-effects we can't determine
1312 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001313 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001314 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001315 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001316 return Success(0, E);
1317 }
Mike Stump876387b2009-10-27 22:09:17 +00001318
Mike Stump722cedf2009-10-26 18:35:08 +00001319 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1320 }
1321
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001322 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001323 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001324
Anders Carlsson4c76e932008-11-24 04:21:33 +00001325 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001326 // __builtin_constant_p always has one operand: it returns true if that
1327 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001328 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001329
1330 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001331 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001332 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001333 return Success(Operand, E);
1334 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001335
1336 case Builtin::BI__builtin_expect:
1337 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001338
1339 case Builtin::BIstrlen:
1340 case Builtin::BI__builtin_strlen:
1341 // As an extension, we support strlen() and __builtin_strlen() as constant
1342 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001343 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001344 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1345 // The string literal may have embedded null characters. Find the first
1346 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001347 StringRef Str = S->getString();
1348 StringRef::size_type Pos = Str.find(0);
1349 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001350 Str = Str.substr(0, Pos);
1351
1352 return Success(Str.size(), E);
1353 }
1354
1355 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001356
1357 case Builtin::BI__atomic_is_lock_free: {
1358 APSInt SizeVal;
1359 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1360 return false;
1361
1362 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1363 // of two less than the maximum inline atomic width, we know it is
1364 // lock-free. If the size isn't a power of two, or greater than the
1365 // maximum alignment where we promote atomics, we know it is not lock-free
1366 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1367 // the answer can only be determined at runtime; for example, 16-byte
1368 // atomics have lock-free implementations on some, but not all,
1369 // x86-64 processors.
1370
1371 // Check power-of-two.
1372 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1373 if (!Size.isPowerOfTwo())
1374#if 0
1375 // FIXME: Suppress this folding until the ABI for the promotion width
1376 // settles.
1377 return Success(0, E);
1378#else
1379 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1380#endif
1381
1382#if 0
1383 // Check against promotion width.
1384 // FIXME: Suppress this folding until the ABI for the promotion width
1385 // settles.
1386 unsigned PromoteWidthBits =
1387 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1388 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1389 return Success(0, E);
1390#endif
1391
1392 // Check against inlining width.
1393 unsigned InlineWidthBits =
1394 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1395 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1396 return Success(1, E);
1397
1398 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1399 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001400 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001401}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001402
Chris Lattnere13042c2008-07-11 19:10:17 +00001403bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001404 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001405 if (!Visit(E->getRHS()))
1406 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001407
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001408 // If we can't evaluate the LHS, it might have side effects;
1409 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00001410 APValue Scratch;
1411 if (!Evaluate(Scratch, Info, E->getLHS()))
1412 Info.EvalStatus.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001413
Anders Carlsson564730a2008-12-01 02:07:06 +00001414 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001415 }
1416
1417 if (E->isLogicalOp()) {
1418 // These need to be handled specially because the operands aren't
1419 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001420 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001421
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001422 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001423 // We were able to evaluate the LHS, see if we can get away with not
1424 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001425 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001426 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001427
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001428 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001429 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001430 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001431 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001432 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001433 }
1434 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001435 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001436 // We can't evaluate the LHS; however, sometimes the result
1437 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001438 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1439 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001440 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001441 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001442 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001443
1444 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001445 }
1446 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001447 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001448
Eli Friedman5a332ea2008-11-13 06:09:17 +00001449 return false;
1450 }
1451
Anders Carlssonacc79812008-11-16 07:17:21 +00001452 QualType LHSTy = E->getLHS()->getType();
1453 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001454
1455 if (LHSTy->isAnyComplexType()) {
1456 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001457 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001458
1459 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1460 return false;
1461
1462 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1463 return false;
1464
1465 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001466 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001467 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001468 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001469 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1470
John McCalle3027922010-08-25 11:45:40 +00001471 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001472 return Success((CR_r == APFloat::cmpEqual &&
1473 CR_i == APFloat::cmpEqual), E);
1474 else {
John McCalle3027922010-08-25 11:45:40 +00001475 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001476 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001477 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001478 CR_r == APFloat::cmpLessThan ||
1479 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001480 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001481 CR_i == APFloat::cmpLessThan ||
1482 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001483 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001484 } else {
John McCalle3027922010-08-25 11:45:40 +00001485 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001486 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1487 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1488 else {
John McCalle3027922010-08-25 11:45:40 +00001489 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001490 "Invalid compex comparison.");
1491 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1492 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1493 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001494 }
1495 }
Mike Stump11289f42009-09-09 15:08:12 +00001496
Anders Carlssonacc79812008-11-16 07:17:21 +00001497 if (LHSTy->isRealFloatingType() &&
1498 RHSTy->isRealFloatingType()) {
1499 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001500
Anders Carlssonacc79812008-11-16 07:17:21 +00001501 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1502 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001503
Anders Carlssonacc79812008-11-16 07:17:21 +00001504 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1505 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001506
Anders Carlssonacc79812008-11-16 07:17:21 +00001507 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001508
Anders Carlssonacc79812008-11-16 07:17:21 +00001509 switch (E->getOpcode()) {
1510 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001511 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001512 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001513 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001514 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001515 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001516 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001517 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001518 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001519 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001520 E);
John McCalle3027922010-08-25 11:45:40 +00001521 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001522 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001523 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001524 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001525 || CR == APFloat::cmpLessThan
1526 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001527 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001528 }
Mike Stump11289f42009-09-09 15:08:12 +00001529
Eli Friedmana38da572009-04-28 19:17:36 +00001530 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001531 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001532 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001533 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1534 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001535
John McCall45d55e42010-05-07 21:00:08 +00001536 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001537 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1538 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001539
Eli Friedman334046a2009-06-14 02:17:33 +00001540 // Reject any bases from the normal codepath; we special-case comparisons
1541 // to null.
1542 if (LHSValue.getLValueBase()) {
1543 if (!E->isEqualityOp())
1544 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001545 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001546 return false;
1547 bool bres;
1548 if (!EvalPointerValueAsBool(LHSValue, bres))
1549 return false;
John McCalle3027922010-08-25 11:45:40 +00001550 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001551 } else if (RHSValue.getLValueBase()) {
1552 if (!E->isEqualityOp())
1553 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001554 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001555 return false;
1556 bool bres;
1557 if (!EvalPointerValueAsBool(RHSValue, bres))
1558 return false;
John McCalle3027922010-08-25 11:45:40 +00001559 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001560 }
Eli Friedman64004332009-03-23 04:38:34 +00001561
John McCalle3027922010-08-25 11:45:40 +00001562 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001563 QualType Type = E->getLHS()->getType();
1564 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001565
Ken Dyck02990832010-01-15 12:37:54 +00001566 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001567 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001568 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001569
Ken Dyck02990832010-01-15 12:37:54 +00001570 CharUnits Diff = LHSValue.getLValueOffset() -
1571 RHSValue.getLValueOffset();
1572 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001573 }
1574 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001575 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001576 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001577 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001578 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1579 }
1580 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001581 }
1582 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001583 if (!LHSTy->isIntegralOrEnumerationType() ||
1584 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001585 // We can't continue from here for non-integral types, and they
1586 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001587 return false;
1588 }
1589
Anders Carlsson9c181652008-07-08 14:35:21 +00001590 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001591 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001592 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001593
Eli Friedman94c25c62009-03-24 01:14:50 +00001594 APValue RHSVal;
1595 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001596 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001597
1598 // Handle cases like (unsigned long)&a + 4.
1599 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001600 CharUnits Offset = Result.getLValueOffset();
1601 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1602 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001603 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001604 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001605 else
Ken Dyck02990832010-01-15 12:37:54 +00001606 Offset -= AdditionalOffset;
1607 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001608 return true;
1609 }
1610
1611 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001612 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001613 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001614 CharUnits Offset = RHSVal.getLValueOffset();
1615 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1616 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001617 return true;
1618 }
1619
1620 // All the following cases expect both operands to be an integer
1621 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001622 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001623
Eli Friedman94c25c62009-03-24 01:14:50 +00001624 APSInt& RHS = RHSVal.getInt();
1625
Anders Carlsson9c181652008-07-08 14:35:21 +00001626 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001627 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001628 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001629 case BO_Mul: return Success(Result.getInt() * RHS, E);
1630 case BO_Add: return Success(Result.getInt() + RHS, E);
1631 case BO_Sub: return Success(Result.getInt() - RHS, E);
1632 case BO_And: return Success(Result.getInt() & RHS, E);
1633 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1634 case BO_Or: return Success(Result.getInt() | RHS, E);
1635 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001636 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001637 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001638 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001639 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001640 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001641 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001642 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001643 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001644 // During constant-folding, a negative shift is an opposite shift.
1645 if (RHS.isSigned() && RHS.isNegative()) {
1646 RHS = -RHS;
1647 goto shift_right;
1648 }
1649
1650 shift_left:
1651 unsigned SA
1652 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001653 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001654 }
John McCalle3027922010-08-25 11:45:40 +00001655 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001656 // During constant-folding, a negative shift is an opposite shift.
1657 if (RHS.isSigned() && RHS.isNegative()) {
1658 RHS = -RHS;
1659 goto shift_left;
1660 }
1661
1662 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001663 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001664 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1665 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001666 }
Mike Stump11289f42009-09-09 15:08:12 +00001667
John McCalle3027922010-08-25 11:45:40 +00001668 case BO_LT: return Success(Result.getInt() < RHS, E);
1669 case BO_GT: return Success(Result.getInt() > RHS, E);
1670 case BO_LE: return Success(Result.getInt() <= RHS, E);
1671 case BO_GE: return Success(Result.getInt() >= RHS, E);
1672 case BO_EQ: return Success(Result.getInt() == RHS, E);
1673 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001674 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001675}
1676
Ken Dyck160146e2010-01-27 17:10:57 +00001677CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001678 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1679 // the result is the size of the referenced type."
1680 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1681 // result shall be the alignment of the referenced type."
1682 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1683 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001684
1685 // __alignof is defined to return the preferred alignment.
1686 return Info.Ctx.toCharUnitsFromBits(
1687 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001688}
1689
Ken Dyck160146e2010-01-27 17:10:57 +00001690CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001691 E = E->IgnoreParens();
1692
1693 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001694 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001695 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001696 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1697 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001698
Chris Lattner68061312009-01-24 21:53:27 +00001699 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001700 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1701 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001702
Chris Lattner24aeeab2009-01-24 21:09:06 +00001703 return GetAlignOfType(E->getType());
1704}
1705
1706
Peter Collingbournee190dee2011-03-11 19:24:49 +00001707/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1708/// a result as the expression's type.
1709bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1710 const UnaryExprOrTypeTraitExpr *E) {
1711 switch(E->getKind()) {
1712 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001713 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001714 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001715 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001716 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001717 }
Eli Friedman64004332009-03-23 04:38:34 +00001718
Peter Collingbournee190dee2011-03-11 19:24:49 +00001719 case UETT_VecStep: {
1720 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001721
Peter Collingbournee190dee2011-03-11 19:24:49 +00001722 if (Ty->isVectorType()) {
1723 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001724
Peter Collingbournee190dee2011-03-11 19:24:49 +00001725 // The vec_step built-in functions that take a 3-component
1726 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1727 if (n == 3)
1728 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001729
Peter Collingbournee190dee2011-03-11 19:24:49 +00001730 return Success(n, E);
1731 } else
1732 return Success(1, E);
1733 }
1734
1735 case UETT_SizeOf: {
1736 QualType SrcTy = E->getTypeOfArgument();
1737 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1738 // the result is the size of the referenced type."
1739 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1740 // result shall be the alignment of the referenced type."
1741 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1742 SrcTy = Ref->getPointeeType();
1743
1744 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1745 // extension.
1746 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1747 return Success(1, E);
1748
1749 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1750 if (!SrcTy->isConstantSizeType())
1751 return false;
1752
1753 // Get information about the size.
1754 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1755 }
1756 }
1757
1758 llvm_unreachable("unknown expr/type trait");
1759 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001760}
1761
Peter Collingbournee9200682011-05-13 03:29:01 +00001762bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001763 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001764 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001765 if (n == 0)
1766 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001767 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001768 for (unsigned i = 0; i != n; ++i) {
1769 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1770 switch (ON.getKind()) {
1771 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001772 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001773 APSInt IdxResult;
1774 if (!EvaluateInteger(Idx, IdxResult, Info))
1775 return false;
1776 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1777 if (!AT)
1778 return false;
1779 CurrentType = AT->getElementType();
1780 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1781 Result += IdxResult.getSExtValue() * ElementSize;
1782 break;
1783 }
1784
1785 case OffsetOfExpr::OffsetOfNode::Field: {
1786 FieldDecl *MemberDecl = ON.getField();
1787 const RecordType *RT = CurrentType->getAs<RecordType>();
1788 if (!RT)
1789 return false;
1790 RecordDecl *RD = RT->getDecl();
1791 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001792 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001793 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001794 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001795 CurrentType = MemberDecl->getType().getNonReferenceType();
1796 break;
1797 }
1798
1799 case OffsetOfExpr::OffsetOfNode::Identifier:
1800 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001801 return false;
1802
1803 case OffsetOfExpr::OffsetOfNode::Base: {
1804 CXXBaseSpecifier *BaseSpec = ON.getBase();
1805 if (BaseSpec->isVirtual())
1806 return false;
1807
1808 // Find the layout of the class whose base we are looking into.
1809 const RecordType *RT = CurrentType->getAs<RecordType>();
1810 if (!RT)
1811 return false;
1812 RecordDecl *RD = RT->getDecl();
1813 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1814
1815 // Find the base class itself.
1816 CurrentType = BaseSpec->getType();
1817 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1818 if (!BaseRT)
1819 return false;
1820
1821 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001822 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001823 break;
1824 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001825 }
1826 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001827 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001828}
1829
Chris Lattnere13042c2008-07-11 19:10:17 +00001830bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001831 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001832 // LNot's operand isn't necessarily an integer, so we handle it specially.
1833 bool bres;
1834 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1835 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001836 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001837 }
1838
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001839 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001840 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001841 return false;
1842
Chris Lattnercdf34e72008-07-11 22:52:41 +00001843 // Get the operand value into 'Result'.
1844 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001845 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001846
Chris Lattnerf09ad162008-07-11 22:15:16 +00001847 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001848 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001849 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1850 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001851 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001852 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001853 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1854 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001855 return true;
John McCalle3027922010-08-25 11:45:40 +00001856 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001857 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001858 return true;
John McCalle3027922010-08-25 11:45:40 +00001859 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001860 if (!Result.isInt()) return false;
1861 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001862 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001863 if (!Result.isInt()) return false;
1864 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001865 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001866}
Mike Stump11289f42009-09-09 15:08:12 +00001867
Chris Lattner477c4be2008-07-12 01:15:53 +00001868/// HandleCast - This is used to evaluate implicit or explicit casts where the
1869/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001870bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1871 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001872 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001873 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001874
Eli Friedmanc757de22011-03-25 00:43:55 +00001875 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001876 case CK_BaseToDerived:
1877 case CK_DerivedToBase:
1878 case CK_UncheckedDerivedToBase:
1879 case CK_Dynamic:
1880 case CK_ToUnion:
1881 case CK_ArrayToPointerDecay:
1882 case CK_FunctionToPointerDecay:
1883 case CK_NullToPointer:
1884 case CK_NullToMemberPointer:
1885 case CK_BaseToDerivedMemberPointer:
1886 case CK_DerivedToBaseMemberPointer:
1887 case CK_ConstructorConversion:
1888 case CK_IntegralToPointer:
1889 case CK_ToVoid:
1890 case CK_VectorSplat:
1891 case CK_IntegralToFloating:
1892 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00001893 case CK_CPointerToObjCPointerCast:
1894 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001895 case CK_AnyPointerToBlockPointerCast:
1896 case CK_ObjCObjectLValueCast:
1897 case CK_FloatingRealToComplex:
1898 case CK_FloatingComplexToReal:
1899 case CK_FloatingComplexCast:
1900 case CK_FloatingComplexToIntegralComplex:
1901 case CK_IntegralRealToComplex:
1902 case CK_IntegralComplexCast:
1903 case CK_IntegralComplexToFloatingComplex:
1904 llvm_unreachable("invalid cast kind for integral value");
1905
Eli Friedman9faf2f92011-03-25 19:07:11 +00001906 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001907 case CK_Dependent:
1908 case CK_GetObjCProperty:
1909 case CK_LValueBitCast:
1910 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00001911 case CK_ARCProduceObject:
1912 case CK_ARCConsumeObject:
1913 case CK_ARCReclaimReturnedObject:
1914 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001915 return false;
1916
1917 case CK_LValueToRValue:
1918 case CK_NoOp:
1919 return Visit(E->getSubExpr());
1920
1921 case CK_MemberPointerToBoolean:
1922 case CK_PointerToBoolean:
1923 case CK_IntegralToBoolean:
1924 case CK_FloatingToBoolean:
1925 case CK_FloatingComplexToBoolean:
1926 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001927 bool BoolResult;
1928 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1929 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001930 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001931 }
1932
Eli Friedmanc757de22011-03-25 00:43:55 +00001933 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001934 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001935 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001936
Eli Friedman742421e2009-02-20 01:15:07 +00001937 if (!Result.isInt()) {
1938 // Only allow casts of lvalues if they are lossless.
1939 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1940 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001941
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001942 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001943 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001944 }
Mike Stump11289f42009-09-09 15:08:12 +00001945
Eli Friedmanc757de22011-03-25 00:43:55 +00001946 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001947 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001948 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001949 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001950
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001951 if (LV.getLValueBase()) {
1952 // Only allow based lvalue casts if they are lossless.
1953 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1954 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001955
John McCall45d55e42010-05-07 21:00:08 +00001956 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001957 return true;
1958 }
1959
Ken Dyck02990832010-01-15 12:37:54 +00001960 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1961 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001962 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001963 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001964
Eli Friedmanc757de22011-03-25 00:43:55 +00001965 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001966 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001967 if (!EvaluateComplex(SubExpr, C, Info))
1968 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001969 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001970 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001971
Eli Friedmanc757de22011-03-25 00:43:55 +00001972 case CK_FloatingToIntegral: {
1973 APFloat F(0.0);
1974 if (!EvaluateFloat(SubExpr, F, Info))
1975 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001976
Eli Friedmanc757de22011-03-25 00:43:55 +00001977 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1978 }
1979 }
Mike Stump11289f42009-09-09 15:08:12 +00001980
Eli Friedmanc757de22011-03-25 00:43:55 +00001981 llvm_unreachable("unknown cast resulting in integral value");
1982 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001983}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001984
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001985bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1986 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001987 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001988 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1989 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1990 return Success(LV.getComplexIntReal(), E);
1991 }
1992
1993 return Visit(E->getSubExpr());
1994}
1995
Eli Friedman4e7a2412009-02-27 04:45:43 +00001996bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001997 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001998 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001999 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2000 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2001 return Success(LV.getComplexIntImag(), E);
2002 }
2003
Richard Smith725810a2011-10-16 21:26:27 +00002004 APValue Scratch;
2005 if (!Evaluate(Scratch, Info, E->getSubExpr()))
2006 Info.EvalStatus.HasSideEffects = true;
Eli Friedman4e7a2412009-02-27 04:45:43 +00002007 return Success(0, E);
2008}
2009
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002010bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2011 return Success(E->getPackLength(), E);
2012}
2013
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002014bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2015 return Success(E->getValue(), E);
2016}
2017
Chris Lattner05706e882008-07-11 18:11:29 +00002018//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002019// Float Evaluation
2020//===----------------------------------------------------------------------===//
2021
2022namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002023class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002024 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002025 APFloat &Result;
2026public:
2027 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002028 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002029
Peter Collingbournee9200682011-05-13 03:29:01 +00002030 bool Success(const APValue &V, const Expr *e) {
2031 Result = V.getFloat();
2032 return true;
2033 }
2034 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002035 return false;
2036 }
2037
Richard Smith4ce706a2011-10-11 21:43:33 +00002038 bool ValueInitialization(const Expr *E) {
2039 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2040 return true;
2041 }
2042
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002043 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002044
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002045 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002046 bool VisitBinaryOperator(const BinaryOperator *E);
2047 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002048 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002049
John McCallb1fb0d32010-05-07 22:08:54 +00002050 bool VisitUnaryReal(const UnaryOperator *E);
2051 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002052
John McCalla2fabff2010-10-09 01:34:31 +00002053 bool VisitDeclRefExpr(const DeclRefExpr *E);
2054
John McCallb1fb0d32010-05-07 22:08:54 +00002055 // FIXME: Missing: array subscript of vector, member of vector,
2056 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002057};
2058} // end anonymous namespace
2059
2060static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002061 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002062 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002063}
2064
Jay Foad39c79802011-01-12 09:06:06 +00002065static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002066 QualType ResultTy,
2067 const Expr *Arg,
2068 bool SNaN,
2069 llvm::APFloat &Result) {
2070 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2071 if (!S) return false;
2072
2073 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2074
2075 llvm::APInt fill;
2076
2077 // Treat empty strings as if they were zero.
2078 if (S->getString().empty())
2079 fill = llvm::APInt(32, 0);
2080 else if (S->getString().getAsInteger(0, fill))
2081 return false;
2082
2083 if (SNaN)
2084 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2085 else
2086 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2087 return true;
2088}
2089
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002090bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002091 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002092 default:
2093 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2094
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002095 case Builtin::BI__builtin_huge_val:
2096 case Builtin::BI__builtin_huge_valf:
2097 case Builtin::BI__builtin_huge_vall:
2098 case Builtin::BI__builtin_inf:
2099 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002100 case Builtin::BI__builtin_infl: {
2101 const llvm::fltSemantics &Sem =
2102 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002103 Result = llvm::APFloat::getInf(Sem);
2104 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002105 }
Mike Stump11289f42009-09-09 15:08:12 +00002106
John McCall16291492010-02-28 13:00:19 +00002107 case Builtin::BI__builtin_nans:
2108 case Builtin::BI__builtin_nansf:
2109 case Builtin::BI__builtin_nansl:
2110 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2111 true, Result);
2112
Chris Lattner0b7282e2008-10-06 06:31:58 +00002113 case Builtin::BI__builtin_nan:
2114 case Builtin::BI__builtin_nanf:
2115 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002116 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002117 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002118 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2119 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002120
2121 case Builtin::BI__builtin_fabs:
2122 case Builtin::BI__builtin_fabsf:
2123 case Builtin::BI__builtin_fabsl:
2124 if (!EvaluateFloat(E->getArg(0), Result, Info))
2125 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002126
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002127 if (Result.isNegative())
2128 Result.changeSign();
2129 return true;
2130
Mike Stump11289f42009-09-09 15:08:12 +00002131 case Builtin::BI__builtin_copysign:
2132 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002133 case Builtin::BI__builtin_copysignl: {
2134 APFloat RHS(0.);
2135 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2136 !EvaluateFloat(E->getArg(1), RHS, Info))
2137 return false;
2138 Result.copySign(RHS);
2139 return true;
2140 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002141 }
2142}
2143
John McCalla2fabff2010-10-09 01:34:31 +00002144bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002145 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2146 return true;
2147
John McCalla2fabff2010-10-09 01:34:31 +00002148 const Decl *D = E->getDecl();
2149 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2150 const VarDecl *VD = cast<VarDecl>(D);
2151
2152 // Require the qualifiers to be const and not volatile.
2153 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2154 if (!T.isConstQualified() || T.isVolatileQualified())
2155 return false;
2156
2157 const Expr *Init = VD->getAnyInitializer();
2158 if (!Init) return false;
2159
2160 if (APValue *V = VD->getEvaluatedValue()) {
2161 if (V->isFloat()) {
2162 Result = V->getFloat();
2163 return true;
2164 }
2165 return false;
2166 }
2167
2168 if (VD->isEvaluatingValue())
2169 return false;
2170
2171 VD->setEvaluatingValue();
2172
2173 Expr::EvalResult InitResult;
2174 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2175 InitResult.Val.isFloat()) {
2176 // Cache the evaluated value in the variable declaration.
2177 Result = InitResult.Val.getFloat();
2178 VD->setEvaluatedValue(InitResult.Val);
2179 return true;
2180 }
2181
2182 VD->setEvaluatedValue(APValue());
2183 return false;
2184}
2185
John McCallb1fb0d32010-05-07 22:08:54 +00002186bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002187 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2188 ComplexValue CV;
2189 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2190 return false;
2191 Result = CV.FloatReal;
2192 return true;
2193 }
2194
2195 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002196}
2197
2198bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002199 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2200 ComplexValue CV;
2201 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2202 return false;
2203 Result = CV.FloatImag;
2204 return true;
2205 }
2206
Richard Smith725810a2011-10-16 21:26:27 +00002207 APValue Scratch;
2208 if (!Evaluate(Scratch, Info, E->getSubExpr()))
2209 Info.EvalStatus.HasSideEffects = true;
Eli Friedman95719532010-08-14 20:52:13 +00002210 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2211 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002212 return true;
2213}
2214
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002215bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002216 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002217 return false;
2218
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002219 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2220 return false;
2221
2222 switch (E->getOpcode()) {
2223 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002224 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002225 return true;
John McCalle3027922010-08-25 11:45:40 +00002226 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002227 Result.changeSign();
2228 return true;
2229 }
2230}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002231
Eli Friedman24c01542008-08-22 00:06:13 +00002232bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002233 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002234 if (!EvaluateFloat(E->getRHS(), Result, Info))
2235 return false;
2236
2237 // If we can't evaluate the LHS, it might have side effects;
2238 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00002239 APValue Scratch;
2240 if (!Evaluate(Scratch, Info, E->getLHS()))
2241 Info.EvalStatus.HasSideEffects = true;
Eli Friedman141fbf32009-11-16 04:25:37 +00002242
2243 return true;
2244 }
2245
Anders Carlssona5df61a2010-10-31 01:21:47 +00002246 // We can't evaluate pointer-to-member operations.
2247 if (E->isPtrMemOp())
2248 return false;
2249
Eli Friedman24c01542008-08-22 00:06:13 +00002250 // FIXME: Diagnostics? I really don't understand how the warnings
2251 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002252 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002253 if (!EvaluateFloat(E->getLHS(), Result, Info))
2254 return false;
2255 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2256 return false;
2257
2258 switch (E->getOpcode()) {
2259 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002260 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002261 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2262 return true;
John McCalle3027922010-08-25 11:45:40 +00002263 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002264 Result.add(RHS, APFloat::rmNearestTiesToEven);
2265 return true;
John McCalle3027922010-08-25 11:45:40 +00002266 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002267 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2268 return true;
John McCalle3027922010-08-25 11:45:40 +00002269 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002270 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2271 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002272 }
2273}
2274
2275bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2276 Result = E->getValue();
2277 return true;
2278}
2279
Peter Collingbournee9200682011-05-13 03:29:01 +00002280bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2281 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002282
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002283 switch (E->getCastKind()) {
2284 default:
2285 return false;
2286
2287 case CK_LValueToRValue:
2288 case CK_NoOp:
2289 return Visit(SubExpr);
2290
2291 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002292 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002293 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002294 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002295 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002296 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002297 return true;
2298 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002299
2300 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002301 if (!Visit(SubExpr))
2302 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002303 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2304 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002305 return true;
2306 }
John McCalld7646252010-11-14 08:17:51 +00002307
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002308 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002309 ComplexValue V;
2310 if (!EvaluateComplex(SubExpr, V, Info))
2311 return false;
2312 Result = V.getComplexFloatReal();
2313 return true;
2314 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002315 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002316
2317 return false;
2318}
2319
Eli Friedman24c01542008-08-22 00:06:13 +00002320//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002321// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002322//===----------------------------------------------------------------------===//
2323
2324namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002325class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002326 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002327 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002328
Anders Carlsson537969c2008-11-16 20:27:53 +00002329public:
John McCall93d91dc2010-05-07 17:22:02 +00002330 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002331 : ExprEvaluatorBaseTy(info), Result(Result) {}
2332
2333 bool Success(const APValue &V, const Expr *e) {
2334 Result.setFrom(V);
2335 return true;
2336 }
2337 bool Error(const Expr *E) {
2338 return false;
2339 }
Mike Stump11289f42009-09-09 15:08:12 +00002340
Anders Carlsson537969c2008-11-16 20:27:53 +00002341 //===--------------------------------------------------------------------===//
2342 // Visitor Methods
2343 //===--------------------------------------------------------------------===//
2344
Peter Collingbournee9200682011-05-13 03:29:01 +00002345 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002346
Peter Collingbournee9200682011-05-13 03:29:01 +00002347 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002348
John McCall93d91dc2010-05-07 17:22:02 +00002349 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002350 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002351 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002352};
2353} // end anonymous namespace
2354
John McCall93d91dc2010-05-07 17:22:02 +00002355static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2356 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002357 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002358 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002359}
2360
Peter Collingbournee9200682011-05-13 03:29:01 +00002361bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2362 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002363
2364 if (SubExpr->getType()->isRealFloatingType()) {
2365 Result.makeComplexFloat();
2366 APFloat &Imag = Result.FloatImag;
2367 if (!EvaluateFloat(SubExpr, Imag, Info))
2368 return false;
2369
2370 Result.FloatReal = APFloat(Imag.getSemantics());
2371 return true;
2372 } else {
2373 assert(SubExpr->getType()->isIntegerType() &&
2374 "Unexpected imaginary literal.");
2375
2376 Result.makeComplexInt();
2377 APSInt &Imag = Result.IntImag;
2378 if (!EvaluateInteger(SubExpr, Imag, Info))
2379 return false;
2380
2381 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2382 return true;
2383 }
2384}
2385
Peter Collingbournee9200682011-05-13 03:29:01 +00002386bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002387
John McCallfcef3cf2010-12-14 17:51:41 +00002388 switch (E->getCastKind()) {
2389 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002390 case CK_BaseToDerived:
2391 case CK_DerivedToBase:
2392 case CK_UncheckedDerivedToBase:
2393 case CK_Dynamic:
2394 case CK_ToUnion:
2395 case CK_ArrayToPointerDecay:
2396 case CK_FunctionToPointerDecay:
2397 case CK_NullToPointer:
2398 case CK_NullToMemberPointer:
2399 case CK_BaseToDerivedMemberPointer:
2400 case CK_DerivedToBaseMemberPointer:
2401 case CK_MemberPointerToBoolean:
2402 case CK_ConstructorConversion:
2403 case CK_IntegralToPointer:
2404 case CK_PointerToIntegral:
2405 case CK_PointerToBoolean:
2406 case CK_ToVoid:
2407 case CK_VectorSplat:
2408 case CK_IntegralCast:
2409 case CK_IntegralToBoolean:
2410 case CK_IntegralToFloating:
2411 case CK_FloatingToIntegral:
2412 case CK_FloatingToBoolean:
2413 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002414 case CK_CPointerToObjCPointerCast:
2415 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002416 case CK_AnyPointerToBlockPointerCast:
2417 case CK_ObjCObjectLValueCast:
2418 case CK_FloatingComplexToReal:
2419 case CK_FloatingComplexToBoolean:
2420 case CK_IntegralComplexToReal:
2421 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002422 case CK_ARCProduceObject:
2423 case CK_ARCConsumeObject:
2424 case CK_ARCReclaimReturnedObject:
2425 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002426 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002427
John McCallfcef3cf2010-12-14 17:51:41 +00002428 case CK_LValueToRValue:
2429 case CK_NoOp:
2430 return Visit(E->getSubExpr());
2431
2432 case CK_Dependent:
2433 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002434 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002435 case CK_UserDefinedConversion:
2436 return false;
2437
2438 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002439 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002440 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002441 return false;
2442
John McCallfcef3cf2010-12-14 17:51:41 +00002443 Result.makeComplexFloat();
2444 Result.FloatImag = APFloat(Real.getSemantics());
2445 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002446 }
2447
John McCallfcef3cf2010-12-14 17:51:41 +00002448 case CK_FloatingComplexCast: {
2449 if (!Visit(E->getSubExpr()))
2450 return false;
2451
2452 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2453 QualType From
2454 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2455
2456 Result.FloatReal
2457 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2458 Result.FloatImag
2459 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2460 return true;
2461 }
2462
2463 case CK_FloatingComplexToIntegralComplex: {
2464 if (!Visit(E->getSubExpr()))
2465 return false;
2466
2467 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2468 QualType From
2469 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2470 Result.makeComplexInt();
2471 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2472 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2473 return true;
2474 }
2475
2476 case CK_IntegralRealToComplex: {
2477 APSInt &Real = Result.IntReal;
2478 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2479 return false;
2480
2481 Result.makeComplexInt();
2482 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2483 return true;
2484 }
2485
2486 case CK_IntegralComplexCast: {
2487 if (!Visit(E->getSubExpr()))
2488 return false;
2489
2490 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2491 QualType From
2492 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2493
2494 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2495 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2496 return true;
2497 }
2498
2499 case CK_IntegralComplexToFloatingComplex: {
2500 if (!Visit(E->getSubExpr()))
2501 return false;
2502
2503 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2504 QualType From
2505 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2506 Result.makeComplexFloat();
2507 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2508 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2509 return true;
2510 }
2511 }
2512
2513 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002514 return false;
2515}
2516
John McCall93d91dc2010-05-07 17:22:02 +00002517bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002518 if (E->getOpcode() == BO_Comma) {
2519 if (!Visit(E->getRHS()))
2520 return false;
2521
2522 // If we can't evaluate the LHS, it might have side effects;
2523 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00002524 APValue Scratch;
2525 if (!Evaluate(Scratch, Info, E->getLHS()))
2526 Info.EvalStatus.HasSideEffects = true;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002527
2528 return true;
2529 }
John McCall93d91dc2010-05-07 17:22:02 +00002530 if (!Visit(E->getLHS()))
2531 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002532
John McCall93d91dc2010-05-07 17:22:02 +00002533 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002534 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002535 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002536
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002537 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2538 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002539 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002540 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002541 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002542 if (Result.isComplexFloat()) {
2543 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2544 APFloat::rmNearestTiesToEven);
2545 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2546 APFloat::rmNearestTiesToEven);
2547 } else {
2548 Result.getComplexIntReal() += RHS.getComplexIntReal();
2549 Result.getComplexIntImag() += RHS.getComplexIntImag();
2550 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002551 break;
John McCalle3027922010-08-25 11:45:40 +00002552 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002553 if (Result.isComplexFloat()) {
2554 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2555 APFloat::rmNearestTiesToEven);
2556 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2557 APFloat::rmNearestTiesToEven);
2558 } else {
2559 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2560 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2561 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002562 break;
John McCalle3027922010-08-25 11:45:40 +00002563 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002564 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002565 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002566 APFloat &LHS_r = LHS.getComplexFloatReal();
2567 APFloat &LHS_i = LHS.getComplexFloatImag();
2568 APFloat &RHS_r = RHS.getComplexFloatReal();
2569 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002570
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002571 APFloat Tmp = LHS_r;
2572 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2573 Result.getComplexFloatReal() = Tmp;
2574 Tmp = LHS_i;
2575 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2576 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2577
2578 Tmp = LHS_r;
2579 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2580 Result.getComplexFloatImag() = Tmp;
2581 Tmp = LHS_i;
2582 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2583 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2584 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002585 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002586 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002587 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2588 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002589 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002590 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2591 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2592 }
2593 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002594 case BO_Div:
2595 if (Result.isComplexFloat()) {
2596 ComplexValue LHS = Result;
2597 APFloat &LHS_r = LHS.getComplexFloatReal();
2598 APFloat &LHS_i = LHS.getComplexFloatImag();
2599 APFloat &RHS_r = RHS.getComplexFloatReal();
2600 APFloat &RHS_i = RHS.getComplexFloatImag();
2601 APFloat &Res_r = Result.getComplexFloatReal();
2602 APFloat &Res_i = Result.getComplexFloatImag();
2603
2604 APFloat Den = RHS_r;
2605 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2606 APFloat Tmp = RHS_i;
2607 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2608 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2609
2610 Res_r = LHS_r;
2611 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2612 Tmp = LHS_i;
2613 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2614 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2615 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2616
2617 Res_i = LHS_i;
2618 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2619 Tmp = LHS_r;
2620 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2621 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2622 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2623 } else {
2624 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2625 // FIXME: what about diagnostics?
2626 return false;
2627 }
2628 ComplexValue LHS = Result;
2629 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2630 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2631 Result.getComplexIntReal() =
2632 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2633 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2634 Result.getComplexIntImag() =
2635 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2636 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2637 }
2638 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002639 }
2640
John McCall93d91dc2010-05-07 17:22:02 +00002641 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002642}
2643
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002644bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2645 // Get the operand value into 'Result'.
2646 if (!Visit(E->getSubExpr()))
2647 return false;
2648
2649 switch (E->getOpcode()) {
2650 default:
2651 // FIXME: what about diagnostics?
2652 return false;
2653 case UO_Extension:
2654 return true;
2655 case UO_Plus:
2656 // The result is always just the subexpr.
2657 return true;
2658 case UO_Minus:
2659 if (Result.isComplexFloat()) {
2660 Result.getComplexFloatReal().changeSign();
2661 Result.getComplexFloatImag().changeSign();
2662 }
2663 else {
2664 Result.getComplexIntReal() = -Result.getComplexIntReal();
2665 Result.getComplexIntImag() = -Result.getComplexIntImag();
2666 }
2667 return true;
2668 case UO_Not:
2669 if (Result.isComplexFloat())
2670 Result.getComplexFloatImag().changeSign();
2671 else
2672 Result.getComplexIntImag() = -Result.getComplexIntImag();
2673 return true;
2674 }
2675}
2676
Anders Carlsson537969c2008-11-16 20:27:53 +00002677//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002678// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002679//===----------------------------------------------------------------------===//
2680
Richard Smith725810a2011-10-16 21:26:27 +00002681static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002682 if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002683 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002684 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002685 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002686 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002687 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002688 if (Result.isLValue() &&
2689 !IsGlobalLValue(Result.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002690 return false;
John McCall45d55e42010-05-07 21:00:08 +00002691 } else if (E->getType()->hasPointerRepresentation()) {
2692 LValue LV;
2693 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002694 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002695 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002696 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002697 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002698 } else if (E->getType()->isRealFloatingType()) {
2699 llvm::APFloat F(0.0);
2700 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002701 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002702
Richard Smith725810a2011-10-16 21:26:27 +00002703 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00002704 } else if (E->getType()->isAnyComplexType()) {
2705 ComplexValue C;
2706 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002707 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002708 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002709 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002710 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002711
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002712 return true;
2713}
2714
John McCallc07a0c72011-02-17 10:25:35 +00002715/// Evaluate - Return true if this is a constant which we can fold using
2716/// any crazy technique (that has nothing to do with language standards) that
2717/// we want to. If this function returns true, it returns the folded constant
2718/// in Result.
2719bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2720 EvalInfo Info(Ctx, Result);
Richard Smith725810a2011-10-16 21:26:27 +00002721 return ::Evaluate(Result.Val, Info, this);
John McCallc07a0c72011-02-17 10:25:35 +00002722}
2723
Jay Foad39c79802011-01-12 09:06:06 +00002724bool Expr::EvaluateAsBooleanCondition(bool &Result,
2725 const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002726 EvalStatus Scratch;
John McCall1be1c632010-01-05 23:42:56 +00002727 EvalInfo Info(Ctx, Scratch);
2728
2729 return HandleConversionToBool(this, Result, Info);
2730}
2731
Richard Smithcaf33902011-10-10 18:28:20 +00002732bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002733 EvalStatus Scratch;
Richard Smithcaf33902011-10-10 18:28:20 +00002734 EvalInfo Info(Ctx, Scratch);
2735
2736 return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
2737}
2738
Jay Foad39c79802011-01-12 09:06:06 +00002739bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002740 EvalInfo Info(Ctx, Result);
2741
John McCall45d55e42010-05-07 21:00:08 +00002742 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002743 if (EvaluateLValue(this, LV, Info) &&
2744 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002745 IsGlobalLValue(LV.Base)) {
2746 LV.moveInto(Result.Val);
2747 return true;
2748 }
2749 return false;
2750}
2751
Jay Foad39c79802011-01-12 09:06:06 +00002752bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2753 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002754 EvalInfo Info(Ctx, Result);
2755
2756 LValue LV;
2757 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002758 LV.moveInto(Result.Val);
2759 return true;
2760 }
2761 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002762}
2763
Chris Lattner67d7b922008-11-16 21:24:15 +00002764/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002765/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002766bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002767 EvalResult Result;
2768 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002769}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002770
Jay Foad39c79802011-01-12 09:06:06 +00002771bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002772 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002773}
2774
Richard Smithcaf33902011-10-10 18:28:20 +00002775APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002776 EvalResult EvalResult;
2777 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002778 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002779 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002780 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002781
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002782 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002783}
John McCall864e3962010-05-07 05:32:02 +00002784
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002785 bool Expr::EvalResult::isGlobalLValue() const {
2786 assert(Val.isLValue());
2787 return IsGlobalLValue(Val.getLValueBase());
2788 }
2789
2790
John McCall864e3962010-05-07 05:32:02 +00002791/// isIntegerConstantExpr - this recursive routine will test if an expression is
2792/// an integer constant expression.
2793
2794/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2795/// comma, etc
2796///
2797/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2798/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2799/// cast+dereference.
2800
2801// CheckICE - This function does the fundamental ICE checking: the returned
2802// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2803// Note that to reduce code duplication, this helper does no evaluation
2804// itself; the caller checks whether the expression is evaluatable, and
2805// in the rare cases where CheckICE actually cares about the evaluated
2806// value, it calls into Evalute.
2807//
2808// Meanings of Val:
2809// 0: This expression is an ICE if it can be evaluated by Evaluate.
2810// 1: This expression is not an ICE, but if it isn't evaluated, it's
2811// a legal subexpression for an ICE. This return value is used to handle
2812// the comma operator in C99 mode.
2813// 2: This expression is not an ICE, and is not a legal subexpression for one.
2814
Dan Gohman28ade552010-07-26 21:25:24 +00002815namespace {
2816
John McCall864e3962010-05-07 05:32:02 +00002817struct ICEDiag {
2818 unsigned Val;
2819 SourceLocation Loc;
2820
2821 public:
2822 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2823 ICEDiag() : Val(0) {}
2824};
2825
Dan Gohman28ade552010-07-26 21:25:24 +00002826}
2827
2828static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002829
2830static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2831 Expr::EvalResult EVResult;
2832 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2833 !EVResult.Val.isInt()) {
2834 return ICEDiag(2, E->getLocStart());
2835 }
2836 return NoDiag();
2837}
2838
2839static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2840 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002841 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002842 return ICEDiag(2, E->getLocStart());
2843 }
2844
2845 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002846#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002847#define STMT(Node, Base) case Expr::Node##Class:
2848#define EXPR(Node, Base)
2849#include "clang/AST/StmtNodes.inc"
2850 case Expr::PredefinedExprClass:
2851 case Expr::FloatingLiteralClass:
2852 case Expr::ImaginaryLiteralClass:
2853 case Expr::StringLiteralClass:
2854 case Expr::ArraySubscriptExprClass:
2855 case Expr::MemberExprClass:
2856 case Expr::CompoundAssignOperatorClass:
2857 case Expr::CompoundLiteralExprClass:
2858 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00002859 case Expr::DesignatedInitExprClass:
2860 case Expr::ImplicitValueInitExprClass:
2861 case Expr::ParenListExprClass:
2862 case Expr::VAArgExprClass:
2863 case Expr::AddrLabelExprClass:
2864 case Expr::StmtExprClass:
2865 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002866 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002867 case Expr::CXXDynamicCastExprClass:
2868 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002869 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002870 case Expr::CXXNullPtrLiteralExprClass:
2871 case Expr::CXXThisExprClass:
2872 case Expr::CXXThrowExprClass:
2873 case Expr::CXXNewExprClass:
2874 case Expr::CXXDeleteExprClass:
2875 case Expr::CXXPseudoDestructorExprClass:
2876 case Expr::UnresolvedLookupExprClass:
2877 case Expr::DependentScopeDeclRefExprClass:
2878 case Expr::CXXConstructExprClass:
2879 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002880 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002881 case Expr::CXXTemporaryObjectExprClass:
2882 case Expr::CXXUnresolvedConstructExprClass:
2883 case Expr::CXXDependentScopeMemberExprClass:
2884 case Expr::UnresolvedMemberExprClass:
2885 case Expr::ObjCStringLiteralClass:
2886 case Expr::ObjCEncodeExprClass:
2887 case Expr::ObjCMessageExprClass:
2888 case Expr::ObjCSelectorExprClass:
2889 case Expr::ObjCProtocolExprClass:
2890 case Expr::ObjCIvarRefExprClass:
2891 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002892 case Expr::ObjCIsaExprClass:
2893 case Expr::ShuffleVectorExprClass:
2894 case Expr::BlockExprClass:
2895 case Expr::BlockDeclRefExprClass:
2896 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002897 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002898 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002899 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002900 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002901 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002902 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002903 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00002904 return ICEDiag(2, E->getLocStart());
2905
Sebastian Redl12757ab2011-09-24 17:48:14 +00002906 case Expr::InitListExprClass:
2907 if (Ctx.getLangOptions().CPlusPlus0x) {
2908 const InitListExpr *ILE = cast<InitListExpr>(E);
2909 if (ILE->getNumInits() == 0)
2910 return NoDiag();
2911 if (ILE->getNumInits() == 1)
2912 return CheckICE(ILE->getInit(0), Ctx);
2913 // Fall through for more than 1 expression.
2914 }
2915 return ICEDiag(2, E->getLocStart());
2916
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002917 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002918 case Expr::GNUNullExprClass:
2919 // GCC considers the GNU __null value to be an integral constant expression.
2920 return NoDiag();
2921
John McCall7c454bb2011-07-15 05:09:51 +00002922 case Expr::SubstNonTypeTemplateParmExprClass:
2923 return
2924 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2925
John McCall864e3962010-05-07 05:32:02 +00002926 case Expr::ParenExprClass:
2927 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002928 case Expr::GenericSelectionExprClass:
2929 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002930 case Expr::IntegerLiteralClass:
2931 case Expr::CharacterLiteralClass:
2932 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002933 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002934 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002935 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002936 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002937 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002938 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002939 return NoDiag();
2940 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002941 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002942 const CallExpr *CE = cast<CallExpr>(E);
2943 if (CE->isBuiltinCall(Ctx))
2944 return CheckEvalInICE(E, Ctx);
2945 return ICEDiag(2, E->getLocStart());
2946 }
2947 case Expr::DeclRefExprClass:
2948 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2949 return NoDiag();
2950 if (Ctx.getLangOptions().CPlusPlus &&
2951 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2952 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2953
2954 // Parameter variables are never constants. Without this check,
2955 // getAnyInitializer() can find a default argument, which leads
2956 // to chaos.
2957 if (isa<ParmVarDecl>(D))
2958 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2959
2960 // C++ 7.1.5.1p2
2961 // A variable of non-volatile const-qualified integral or enumeration
2962 // type initialized by an ICE can be used in ICEs.
2963 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2964 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2965 if (Quals.hasVolatile() || !Quals.hasConst())
2966 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2967
2968 // Look for a declaration of this variable that has an initializer.
2969 const VarDecl *ID = 0;
2970 const Expr *Init = Dcl->getAnyInitializer(ID);
2971 if (Init) {
2972 if (ID->isInitKnownICE()) {
2973 // We have already checked whether this subexpression is an
2974 // integral constant expression.
2975 if (ID->isInitICE())
2976 return NoDiag();
2977 else
2978 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2979 }
2980
2981 // It's an ICE whether or not the definition we found is
2982 // out-of-line. See DR 721 and the discussion in Clang PR
2983 // 6206 for details.
2984
2985 if (Dcl->isCheckingICE()) {
2986 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2987 }
2988
2989 Dcl->setCheckingICE();
2990 ICEDiag Result = CheckICE(Init, Ctx);
2991 // Cache the result of the ICE test.
2992 Dcl->setInitKnownICE(Result.Val == 0);
2993 return Result;
2994 }
2995 }
2996 }
2997 return ICEDiag(2, E->getLocStart());
2998 case Expr::UnaryOperatorClass: {
2999 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3000 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003001 case UO_PostInc:
3002 case UO_PostDec:
3003 case UO_PreInc:
3004 case UO_PreDec:
3005 case UO_AddrOf:
3006 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00003007 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003008 case UO_Extension:
3009 case UO_LNot:
3010 case UO_Plus:
3011 case UO_Minus:
3012 case UO_Not:
3013 case UO_Real:
3014 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003015 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003016 }
3017
3018 // OffsetOf falls through here.
3019 }
3020 case Expr::OffsetOfExprClass: {
3021 // Note that per C99, offsetof must be an ICE. And AFAIK, using
3022 // Evaluate matches the proposed gcc behavior for cases like
3023 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
3024 // compliance: we should warn earlier for offsetof expressions with
3025 // array subscripts that aren't ICEs, and if the array subscripts
3026 // are ICEs, the value of the offsetof must be an integer constant.
3027 return CheckEvalInICE(E, Ctx);
3028 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003029 case Expr::UnaryExprOrTypeTraitExprClass: {
3030 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3031 if ((Exp->getKind() == UETT_SizeOf) &&
3032 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003033 return ICEDiag(2, E->getLocStart());
3034 return NoDiag();
3035 }
3036 case Expr::BinaryOperatorClass: {
3037 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3038 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003039 case BO_PtrMemD:
3040 case BO_PtrMemI:
3041 case BO_Assign:
3042 case BO_MulAssign:
3043 case BO_DivAssign:
3044 case BO_RemAssign:
3045 case BO_AddAssign:
3046 case BO_SubAssign:
3047 case BO_ShlAssign:
3048 case BO_ShrAssign:
3049 case BO_AndAssign:
3050 case BO_XorAssign:
3051 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00003052 return ICEDiag(2, E->getLocStart());
3053
John McCalle3027922010-08-25 11:45:40 +00003054 case BO_Mul:
3055 case BO_Div:
3056 case BO_Rem:
3057 case BO_Add:
3058 case BO_Sub:
3059 case BO_Shl:
3060 case BO_Shr:
3061 case BO_LT:
3062 case BO_GT:
3063 case BO_LE:
3064 case BO_GE:
3065 case BO_EQ:
3066 case BO_NE:
3067 case BO_And:
3068 case BO_Xor:
3069 case BO_Or:
3070 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003071 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3072 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003073 if (Exp->getOpcode() == BO_Div ||
3074 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003075 // Evaluate gives an error for undefined Div/Rem, so make sure
3076 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003077 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003078 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003079 if (REval == 0)
3080 return ICEDiag(1, E->getLocStart());
3081 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003082 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003083 if (LEval.isMinSignedValue())
3084 return ICEDiag(1, E->getLocStart());
3085 }
3086 }
3087 }
John McCalle3027922010-08-25 11:45:40 +00003088 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003089 if (Ctx.getLangOptions().C99) {
3090 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3091 // if it isn't evaluated.
3092 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3093 return ICEDiag(1, E->getLocStart());
3094 } else {
3095 // In both C89 and C++, commas in ICEs are illegal.
3096 return ICEDiag(2, E->getLocStart());
3097 }
3098 }
3099 if (LHSResult.Val >= RHSResult.Val)
3100 return LHSResult;
3101 return RHSResult;
3102 }
John McCalle3027922010-08-25 11:45:40 +00003103 case BO_LAnd:
3104 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003105 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003106
3107 // C++0x [expr.const]p2:
3108 // [...] subexpressions of logical AND (5.14), logical OR
3109 // (5.15), and condi- tional (5.16) operations that are not
3110 // evaluated are not considered.
3111 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3112 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003113 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003114 return LHSResult;
3115
3116 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003117 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003118 return LHSResult;
3119 }
3120
John McCall864e3962010-05-07 05:32:02 +00003121 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3122 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3123 // Rare case where the RHS has a comma "side-effect"; we need
3124 // to actually check the condition to see whether the side
3125 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003126 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003127 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003128 return RHSResult;
3129 return NoDiag();
3130 }
3131
3132 if (LHSResult.Val >= RHSResult.Val)
3133 return LHSResult;
3134 return RHSResult;
3135 }
3136 }
3137 }
3138 case Expr::ImplicitCastExprClass:
3139 case Expr::CStyleCastExprClass:
3140 case Expr::CXXFunctionalCastExprClass:
3141 case Expr::CXXStaticCastExprClass:
3142 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003143 case Expr::CXXConstCastExprClass:
3144 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003145 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman76d4e432011-09-29 21:49:34 +00003146 switch (cast<CastExpr>(E)->getCastKind()) {
3147 case CK_LValueToRValue:
3148 case CK_NoOp:
3149 case CK_IntegralToBoolean:
3150 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003151 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003152 default:
3153 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3154 return NoDiag();
3155 return ICEDiag(2, E->getLocStart());
3156 }
John McCall864e3962010-05-07 05:32:02 +00003157 }
John McCallc07a0c72011-02-17 10:25:35 +00003158 case Expr::BinaryConditionalOperatorClass: {
3159 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3160 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3161 if (CommonResult.Val == 2) return CommonResult;
3162 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3163 if (FalseResult.Val == 2) return FalseResult;
3164 if (CommonResult.Val == 1) return CommonResult;
3165 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003166 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003167 return FalseResult;
3168 }
John McCall864e3962010-05-07 05:32:02 +00003169 case Expr::ConditionalOperatorClass: {
3170 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3171 // If the condition (ignoring parens) is a __builtin_constant_p call,
3172 // then only the true side is actually considered in an integer constant
3173 // expression, and it is fully evaluated. This is an important GNU
3174 // extension. See GCC PR38377 for discussion.
3175 if (const CallExpr *CallCE
3176 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3177 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3178 Expr::EvalResult EVResult;
3179 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3180 !EVResult.Val.isInt()) {
3181 return ICEDiag(2, E->getLocStart());
3182 }
3183 return NoDiag();
3184 }
3185 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003186 if (CondResult.Val == 2)
3187 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003188
3189 // C++0x [expr.const]p2:
3190 // subexpressions of [...] conditional (5.16) operations that
3191 // are not evaluated are not considered
3192 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003193 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003194 : false;
3195 ICEDiag TrueResult = NoDiag();
3196 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3197 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3198 ICEDiag FalseResult = NoDiag();
3199 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3200 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3201
John McCall864e3962010-05-07 05:32:02 +00003202 if (TrueResult.Val == 2)
3203 return TrueResult;
3204 if (FalseResult.Val == 2)
3205 return FalseResult;
3206 if (CondResult.Val == 1)
3207 return CondResult;
3208 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3209 return NoDiag();
3210 // Rare case where the diagnostics depend on which side is evaluated
3211 // Note that if we get here, CondResult is 0, and at least one of
3212 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003213 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003214 return FalseResult;
3215 }
3216 return TrueResult;
3217 }
3218 case Expr::CXXDefaultArgExprClass:
3219 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3220 case Expr::ChooseExprClass: {
3221 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3222 }
3223 }
3224
3225 // Silence a GCC warning
3226 return ICEDiag(2, E->getLocStart());
3227}
3228
3229bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3230 SourceLocation *Loc, bool isEvaluated) const {
3231 ICEDiag d = CheckICE(this, Ctx);
3232 if (d.Val != 0) {
3233 if (Loc) *Loc = d.Loc;
3234 return false;
3235 }
3236 EvalResult EvalResult;
3237 if (!Evaluate(EvalResult, Ctx))
3238 llvm_unreachable("ICE cannot be evaluated!");
3239 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3240 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3241 Result = EvalResult.Val.getInt();
3242 return true;
3243}