blob: d59d79ec69be1b538645b61d2762c55f85e6627a [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
Richard Smith11562c52011-10-28 17:51:58 +0000151 if (isa<MemberExpr>(E))
152 return false;
153
John McCall95007602010-05-10 23:27:23 +0000154 return true;
155}
156
Richard Smith11562c52011-10-28 17:51:58 +0000157static bool EvalPointerValueAsBool(const LValue &Value, bool &Result) {
John McCall45d55e42010-05-07 21:00:08 +0000158 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000159
John McCalleb3e4f32010-05-07 21:34:32 +0000160 // A null base expression indicates a null pointer. These are always
161 // evaluatable, and they are false unless the offset is zero.
162 if (!Base) {
163 Result = !Value.Offset.isZero();
164 return true;
165 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000166
John McCall95007602010-05-10 23:27:23 +0000167 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000168 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000169
John McCalleb3e4f32010-05-07 21:34:32 +0000170 // We have a non-null base expression. These are generally known to
171 // be true, but if it'a decl-ref to a weak symbol it can be null at
172 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000173 Result = true;
174
175 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000176 if (!DeclRef)
177 return true;
178
John McCalleb3e4f32010-05-07 21:34:32 +0000179 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000180 const ValueDecl* Decl = DeclRef->getDecl();
181 if (Decl->hasAttr<WeakAttr>() ||
182 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000183 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000184 return false;
185
Eli Friedman334046a2009-06-14 02:17:33 +0000186 return true;
187}
188
Richard Smith11562c52011-10-28 17:51:58 +0000189static bool HandleConversionToBool(const APValue &Val, bool &Result) {
190 switch (Val.getKind()) {
191 case APValue::Uninitialized:
192 return false;
193 case APValue::Int:
194 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +0000195 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000196 case APValue::Float:
197 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +0000198 return true;
Richard Smith11562c52011-10-28 17:51:58 +0000199 case APValue::ComplexInt:
200 Result = Val.getComplexIntReal().getBoolValue() ||
201 Val.getComplexIntImag().getBoolValue();
202 return true;
203 case APValue::ComplexFloat:
204 Result = !Val.getComplexFloatReal().isZero() ||
205 !Val.getComplexFloatImag().isZero();
206 return true;
207 case APValue::LValue:
208 {
209 LValue PointerResult;
210 PointerResult.setFrom(Val);
211 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000212 }
Richard Smith11562c52011-10-28 17:51:58 +0000213 case APValue::Vector:
214 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000215 }
216
Richard Smith11562c52011-10-28 17:51:58 +0000217 llvm_unreachable("unknown APValue kind");
218}
219
220static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
221 EvalInfo &Info) {
222 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
223 APValue Val;
224 if (!Evaluate(Val, Info, E))
225 return false;
226 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +0000227}
228
Mike Stump11289f42009-09-09 15:08:12 +0000229static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000230 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000231 unsigned DestWidth = Ctx.getIntWidth(DestType);
232 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000233 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000234
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000235 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000236 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000237 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000238 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
239 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000240}
241
Mike Stump11289f42009-09-09 15:08:12 +0000242static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000243 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000244 bool ignored;
245 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000246 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000247 APFloat::rmNearestTiesToEven, &ignored);
248 return Result;
249}
250
Mike Stump11289f42009-09-09 15:08:12 +0000251static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000252 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000253 unsigned DestWidth = Ctx.getIntWidth(DestType);
254 APSInt Result = Value;
255 // Figure out if this is a truncate, extend or noop cast.
256 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000257 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000258 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000259 return Result;
260}
261
Mike Stump11289f42009-09-09 15:08:12 +0000262static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000263 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000264
265 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
266 Result.convertFromAPInt(Value, Value.isSigned(),
267 APFloat::rmNearestTiesToEven);
268 return Result;
269}
270
Richard Smith27908702011-10-24 17:54:18 +0000271/// Try to evaluate the initializer for a variable declaration.
272static APValue *EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD) {
Richard Smith11562c52011-10-28 17:51:58 +0000273 // FIXME: If this is a parameter to an active constexpr function call, perform
274 // substitution now.
Richard Smith27908702011-10-24 17:54:18 +0000275 if (isa<ParmVarDecl>(VD))
276 return 0;
277
278 const Expr *Init = VD->getAnyInitializer();
279 if (!Init)
280 return 0;
281
282 if (APValue *V = VD->getEvaluatedValue())
283 return V;
284
285 if (VD->isEvaluatingValue())
286 return 0;
287
288 VD->setEvaluatingValue();
289
Richard Smith27908702011-10-24 17:54:18 +0000290 Expr::EvalResult EResult;
Richard Smith11562c52011-10-28 17:51:58 +0000291 EvalInfo InitInfo(Info.Ctx, EResult);
292 // FIXME: The caller will need to know whether the value was a constant
293 // expression. If not, we should propagate up a diagnostic.
294 if (Evaluate(EResult.Val, InitInfo, Init))
Richard Smith27908702011-10-24 17:54:18 +0000295 VD->setEvaluatedValue(EResult.Val);
296 else
297 VD->setEvaluatedValue(APValue());
298
299 return VD->getEvaluatedValue();
300}
301
Richard Smith11562c52011-10-28 17:51:58 +0000302static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +0000303 Qualifiers Quals = T.getQualifiers();
304 return Quals.hasConst() && !Quals.hasVolatile();
305}
306
Richard Smith11562c52011-10-28 17:51:58 +0000307bool HandleLValueToRValueConversion(EvalInfo &Info, QualType Type,
308 const LValue &LVal, APValue &RVal) {
309 const Expr *Base = LVal.Base;
310
311 // FIXME: Indirection through a null pointer deserves a diagnostic.
312 if (!Base)
313 return false;
314
315 // FIXME: Support accessing subobjects of objects of literal types. A simple
316 // byte offset is insufficient for C++11 semantics: we need to know how the
317 // reference was formed (which union member was named, for instance).
318 // FIXME: Support subobjects of StringLiteral and PredefinedExpr.
319 if (!LVal.Offset.isZero())
320 return false;
321
322 const Decl *D = 0;
323
324 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
325 // If the lvalue has been cast to some other type, don't try to read it.
326 // FIXME: Could simulate a bitcast here.
327 if (!Info.Ctx.hasSameUnqualifiedType(Type, DRE->getType()))
328 return false;
329 D = DRE->getDecl();
330 }
331
332 // FIXME: Static data members accessed via a MemberExpr are represented as
333 // that MemberExpr. We should use the Decl directly instead.
334 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
335 if (!Info.Ctx.hasSameUnqualifiedType(Type, ME->getType()))
336 return false;
337 D = ME->getMemberDecl();
338 assert(!isa<FieldDecl>(D) && "shouldn't see fields here");
339 }
340
341 if (D) {
342 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
343 // In C++11, constexpr, non-volatile variables initialized with constant
344 // expressions are constant expressions too.
345 // In C, such things can also be folded, although they are not ICEs.
346 //
347 // FIXME: Allow folding any const variable of literal type initialized with
348 // a constant expression. For now, we only allow variables with integral and
349 // floating types to be folded.
350 const VarDecl *VD = dyn_cast<VarDecl>(D);
351 if (!VD || !IsConstNonVolatile(VD->getType()) ||
352 (!Type->isIntegralOrEnumerationType() && !Type->isRealFloatingType()))
353 return false;
354
355 APValue *V = EvaluateVarDeclInit(Info, VD);
356 if (!V || V->isUninit())
357 return false;
358
359 if (!VD->getAnyInitializer()->isLValue()) {
360 RVal = *V;
361 return true;
362 }
363
364 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
365 // conversion. This happens when the declaration and the lvalue should be
366 // considered synonymous, for instance when initializing an array of char
367 // from a string literal. Continue as if the initializer lvalue was the
368 // value we were originally given.
369 Base = V->getLValueBase();
370 if (!V->getLValueOffset().isZero())
371 return false;
372 }
373
374 // FIXME: C++11: Support MaterializeTemporaryExpr in LValueExprEvaluator and
375 // here.
376
377 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
378 // initializer until now for such expressions. Such an expression can't be
379 // an ICE in C, so this only matters for fold.
380 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
381 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
382 return Evaluate(RVal, Info, CLE->getInitializer());
383 }
384
385 return false;
386}
387
Mike Stump876387b2009-10-27 22:09:17 +0000388namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000389class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000390 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000391 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000392public:
393
Richard Smith725810a2011-10-16 21:26:27 +0000394 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000395
396 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000397 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000398 return true;
399 }
400
Peter Collingbournee9200682011-05-13 03:29:01 +0000401 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
402 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000403 return Visit(E->getResultExpr());
404 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000405 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000406 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000407 return true;
408 return false;
409 }
John McCall31168b02011-06-15 23:02:42 +0000410 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000411 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000412 return true;
413 return false;
414 }
415 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000416 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000417 return true;
418 return false;
419 }
420
Mike Stump876387b2009-10-27 22:09:17 +0000421 // We don't want to evaluate BlockExprs multiple times, as they generate
422 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000423 bool VisitBlockExpr(const BlockExpr *E) { return true; }
424 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
425 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000426 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000427 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
428 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
429 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
430 bool VisitStringLiteral(const StringLiteral *E) { return false; }
431 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
432 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000433 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000434 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000435 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000436 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000437 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000438 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
439 bool VisitBinAssign(const BinaryOperator *E) { return true; }
440 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
441 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000442 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000443 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
444 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
445 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
446 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
447 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000448 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000449 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000450 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000451 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000452 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000453
454 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000455 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000456 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
457 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000458 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000459 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000460 return false;
461 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000462
Peter Collingbournee9200682011-05-13 03:29:01 +0000463 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000464};
465
John McCallc07a0c72011-02-17 10:25:35 +0000466class OpaqueValueEvaluation {
467 EvalInfo &info;
468 OpaqueValueExpr *opaqueValue;
469
470public:
471 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
472 Expr *value)
473 : info(info), opaqueValue(opaqueValue) {
474
475 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000476 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000477 this->opaqueValue = 0;
478 return;
479 }
John McCallc07a0c72011-02-17 10:25:35 +0000480 }
481
482 bool hasError() const { return opaqueValue == 0; }
483
484 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000485 // FIXME: This will not work for recursive constexpr functions using opaque
486 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000487 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
488 }
489};
490
Mike Stump876387b2009-10-27 22:09:17 +0000491} // end anonymous namespace
492
Eli Friedman9a156e52008-11-12 09:44:48 +0000493//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000494// Generic Evaluation
495//===----------------------------------------------------------------------===//
496namespace {
497
498template <class Derived, typename RetTy=void>
499class ExprEvaluatorBase
500 : public ConstStmtVisitor<Derived, RetTy> {
501private:
502 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
503 return static_cast<Derived*>(this)->Success(V, E);
504 }
505 RetTy DerivedError(const Expr *E) {
506 return static_cast<Derived*>(this)->Error(E);
507 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000508 RetTy DerivedValueInitialization(const Expr *E) {
509 return static_cast<Derived*>(this)->ValueInitialization(E);
510 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000511
512protected:
513 EvalInfo &Info;
514 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
515 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
516
Richard Smith4ce706a2011-10-11 21:43:33 +0000517 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
518
Peter Collingbournee9200682011-05-13 03:29:01 +0000519public:
520 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
521
522 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000523 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000524 }
525 RetTy VisitExpr(const Expr *E) {
526 return DerivedError(E);
527 }
528
529 RetTy VisitParenExpr(const ParenExpr *E)
530 { return StmtVisitorTy::Visit(E->getSubExpr()); }
531 RetTy VisitUnaryExtension(const UnaryOperator *E)
532 { return StmtVisitorTy::Visit(E->getSubExpr()); }
533 RetTy VisitUnaryPlus(const UnaryOperator *E)
534 { return StmtVisitorTy::Visit(E->getSubExpr()); }
535 RetTy VisitChooseExpr(const ChooseExpr *E)
536 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
537 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
538 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000539 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
540 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000541
542 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
543 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
544 if (opaque.hasError())
545 return DerivedError(E);
546
547 bool cond;
Richard Smith11562c52011-10-28 17:51:58 +0000548 if (!EvaluateAsBooleanCondition(E->getCond(), cond, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000549 return DerivedError(E);
550
551 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
552 }
553
554 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
555 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +0000556 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info))
Peter Collingbournee9200682011-05-13 03:29:01 +0000557 return DerivedError(E);
558
Richard Smith11562c52011-10-28 17:51:58 +0000559 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
Peter Collingbournee9200682011-05-13 03:29:01 +0000560 return StmtVisitorTy::Visit(EvalExpr);
561 }
562
563 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
564 const APValue *value = Info.getOpaqueValue(E);
565 if (!value)
566 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
567 : DerivedError(E));
568 return DerivedSuccess(*value, E);
569 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000570
Richard Smith11562c52011-10-28 17:51:58 +0000571 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
572 return StmtVisitorTy::Visit(E->getInitializer());
573 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000574 RetTy VisitInitListExpr(const InitListExpr *E) {
575 if (Info.getLangOpts().CPlusPlus0x) {
576 if (E->getNumInits() == 0)
577 return DerivedValueInitialization(E);
578 if (E->getNumInits() == 1)
579 return StmtVisitorTy::Visit(E->getInit(0));
580 }
581 return DerivedError(E);
582 }
583 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
584 return DerivedValueInitialization(E);
585 }
586 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
587 return DerivedValueInitialization(E);
588 }
589
Richard Smith11562c52011-10-28 17:51:58 +0000590 RetTy VisitCastExpr(const CastExpr *E) {
591 switch (E->getCastKind()) {
592 default:
593 break;
594
595 case CK_NoOp:
596 return StmtVisitorTy::Visit(E->getSubExpr());
597
598 case CK_LValueToRValue: {
599 LValue LVal;
600 if (EvaluateLValue(E->getSubExpr(), LVal, Info)) {
601 APValue RVal;
602 if (HandleLValueToRValueConversion(Info, E->getType(), LVal, RVal))
603 return DerivedSuccess(RVal, E);
604 }
605 break;
606 }
607 }
608
609 return DerivedError(E);
610 }
611
Richard Smith4a678122011-10-24 18:44:57 +0000612 /// Visit a value which is evaluated, but whose value is ignored.
613 void VisitIgnoredValue(const Expr *E) {
614 APValue Scratch;
615 if (!Evaluate(Scratch, Info, E))
616 Info.EvalStatus.HasSideEffects = true;
617 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000618};
619
620}
621
622//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000623// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +0000624//
625// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
626// function designators (in C), decl references to void objects (in C), and
627// temporaries (if building with -Wno-address-of-temporary).
628//
629// LValue evaluation produces values comprising a base expression of one of the
630// following types:
631// * DeclRefExpr
632// * MemberExpr for a static member
633// * CompoundLiteralExpr in C
634// * StringLiteral
635// * PredefinedExpr
636// * ObjCEncodeExpr
637// * AddrLabelExpr
638// * BlockExpr
639// * CallExpr for a MakeStringConstant builtin
640// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +0000641//===----------------------------------------------------------------------===//
642namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000643class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000644 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000645 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000646 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000647
Peter Collingbournee9200682011-05-13 03:29:01 +0000648 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000649 Result.Base = E;
650 Result.Offset = CharUnits::Zero();
651 return true;
652 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000653public:
Mike Stump11289f42009-09-09 15:08:12 +0000654
John McCall45d55e42010-05-07 21:00:08 +0000655 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000656 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000657
Peter Collingbournee9200682011-05-13 03:29:01 +0000658 bool Success(const APValue &V, const Expr *E) {
659 Result.setFrom(V);
660 return true;
661 }
662 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000663 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000664 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000665
Richard Smith11562c52011-10-28 17:51:58 +0000666 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
667
Peter Collingbournee9200682011-05-13 03:29:01 +0000668 bool VisitDeclRefExpr(const DeclRefExpr *E);
669 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
670 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
671 bool VisitMemberExpr(const MemberExpr *E);
672 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
673 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
674 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
675 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000676
Peter Collingbournee9200682011-05-13 03:29:01 +0000677 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000678 switch (E->getCastKind()) {
679 default:
Richard Smith11562c52011-10-28 17:51:58 +0000680 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000681
Eli Friedmance3e02a2011-10-11 00:13:24 +0000682 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000683 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000684
Richard Smith11562c52011-10-28 17:51:58 +0000685 // FIXME: Support CK_DerivedToBase and CK_UncheckedDerivedToBase.
686 // Reuse PointerExprEvaluator::VisitCastExpr for these.
Anders Carlssonde55f642009-10-03 16:30:22 +0000687 }
688 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000689
Eli Friedman449fe542009-03-23 04:56:01 +0000690 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000691
Eli Friedman9a156e52008-11-12 09:44:48 +0000692};
693} // end anonymous namespace
694
Richard Smith11562c52011-10-28 17:51:58 +0000695/// Evaluate an expression as an lvalue. This can be legitimately called on
696/// expressions which are not glvalues, in a few cases:
697/// * function designators in C,
698/// * "extern void" objects,
699/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +0000700static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000701 assert((E->isGLValue() || E->getType()->isFunctionType() ||
702 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
703 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +0000704 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000705}
706
Peter Collingbournee9200682011-05-13 03:29:01 +0000707bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000708 if (isa<FunctionDecl>(E->getDecl()))
John McCall45d55e42010-05-07 21:00:08 +0000709 return Success(E);
Richard Smith11562c52011-10-28 17:51:58 +0000710 if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl()))
711 return VisitVarDecl(E, VD);
712 return Error(E);
713}
Richard Smith733237d2011-10-24 23:14:33 +0000714
Richard Smith11562c52011-10-28 17:51:58 +0000715bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
716 if (!VD->getType()->isReferenceType())
717 return Success(E);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000718
Richard Smith11562c52011-10-28 17:51:58 +0000719 APValue *V = EvaluateVarDeclInit(Info, VD);
720 if (V && !V->isUninit())
721 return Success(*V, E);
722
723 return Error(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000724}
725
Peter Collingbournee9200682011-05-13 03:29:01 +0000726bool
727LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000728 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
729 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
730 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +0000731 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000732}
733
Peter Collingbournee9200682011-05-13 03:29:01 +0000734bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000735 // Handle static data members.
736 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
737 VisitIgnoredValue(E->getBase());
738 return VisitVarDecl(E, VD);
739 }
740
Eli Friedman9a156e52008-11-12 09:44:48 +0000741 QualType Ty;
742 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000743 if (!EvaluatePointer(E->getBase(), Result, Info))
744 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000745 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000746 } else {
John McCall45d55e42010-05-07 21:00:08 +0000747 if (!Visit(E->getBase()))
748 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000749 Ty = E->getBase()->getType();
750 }
751
Peter Collingbournee9200682011-05-13 03:29:01 +0000752 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000753 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000754
Peter Collingbournee9200682011-05-13 03:29:01 +0000755 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000756 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000757 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000758
759 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000760 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000761
Eli Friedmana3c122d2011-07-07 01:54:01 +0000762 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000763 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000764 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000765}
766
Peter Collingbournee9200682011-05-13 03:29:01 +0000767bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +0000768 // FIXME: Deal with vectors as array subscript bases.
769 if (E->getBase()->getType()->isVectorType())
770 return false;
771
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000772 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000773 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000774
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000775 APSInt Index;
776 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000777 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000778
Ken Dyck40775002010-01-11 17:06:35 +0000779 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000780 Result.Offset += Index.getSExtValue() * ElementSize;
781 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000782}
Eli Friedman9a156e52008-11-12 09:44:48 +0000783
Peter Collingbournee9200682011-05-13 03:29:01 +0000784bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000785 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000786}
787
Eli Friedman9a156e52008-11-12 09:44:48 +0000788//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000789// Pointer Evaluation
790//===----------------------------------------------------------------------===//
791
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000792namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000793class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000794 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000795 LValue &Result;
796
Peter Collingbournee9200682011-05-13 03:29:01 +0000797 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000798 Result.Base = E;
799 Result.Offset = CharUnits::Zero();
800 return true;
801 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000802public:
Mike Stump11289f42009-09-09 15:08:12 +0000803
John McCall45d55e42010-05-07 21:00:08 +0000804 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000805 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000806
Peter Collingbournee9200682011-05-13 03:29:01 +0000807 bool Success(const APValue &V, const Expr *E) {
808 Result.setFrom(V);
809 return true;
810 }
811 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000812 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000813 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000814 bool ValueInitialization(const Expr *E) {
815 return Success((Expr*)0);
816 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000817
John McCall45d55e42010-05-07 21:00:08 +0000818 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000819 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000820 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000821 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000822 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000823 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000824 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000825 bool VisitCallExpr(const CallExpr *E);
826 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000827 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000828 return Success(E);
829 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000830 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000831 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +0000832 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +0000833
Eli Friedman449fe542009-03-23 04:56:01 +0000834 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000835};
Chris Lattner05706e882008-07-11 18:11:29 +0000836} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000837
John McCall45d55e42010-05-07 21:00:08 +0000838static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +0000839 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000840 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000841}
842
John McCall45d55e42010-05-07 21:00:08 +0000843bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000844 if (E->getOpcode() != BO_Add &&
845 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000846 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000847
Chris Lattner05706e882008-07-11 18:11:29 +0000848 const Expr *PExp = E->getLHS();
849 const Expr *IExp = E->getRHS();
850 if (IExp->getType()->isPointerType())
851 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000852
John McCall45d55e42010-05-07 21:00:08 +0000853 if (!EvaluatePointer(PExp, Result, Info))
854 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000855
John McCall45d55e42010-05-07 21:00:08 +0000856 llvm::APSInt Offset;
857 if (!EvaluateInteger(IExp, Offset, Info))
858 return false;
859 int64_t AdditionalOffset
860 = Offset.isSigned() ? Offset.getSExtValue()
861 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000862
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000863 // Compute the new offset in the appropriate width.
864
865 QualType PointeeType =
866 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000867 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000868
Anders Carlssonef56fba2009-02-19 04:55:58 +0000869 // Explicitly handle GNU void* and function pointer arithmetic extensions.
870 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000871 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000872 else
John McCall45d55e42010-05-07 21:00:08 +0000873 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000874
John McCalle3027922010-08-25 11:45:40 +0000875 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000876 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000877 else
John McCall45d55e42010-05-07 21:00:08 +0000878 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000879
John McCall45d55e42010-05-07 21:00:08 +0000880 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000881}
Eli Friedman9a156e52008-11-12 09:44:48 +0000882
John McCall45d55e42010-05-07 21:00:08 +0000883bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
884 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000885}
Mike Stump11289f42009-09-09 15:08:12 +0000886
Chris Lattner05706e882008-07-11 18:11:29 +0000887
Peter Collingbournee9200682011-05-13 03:29:01 +0000888bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
889 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000890
Eli Friedman847a2bc2009-12-27 05:43:15 +0000891 switch (E->getCastKind()) {
892 default:
893 break;
894
John McCalle3027922010-08-25 11:45:40 +0000895 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +0000896 case CK_CPointerToObjCPointerCast:
897 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +0000898 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000899 return Visit(SubExpr);
900
Anders Carlsson18275092010-10-31 20:41:46 +0000901 case CK_DerivedToBase:
902 case CK_UncheckedDerivedToBase: {
903 LValue BaseLV;
904 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
905 return false;
906
907 // Now figure out the necessary offset to add to the baseLV to get from
908 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000909 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000910
911 QualType Ty = E->getSubExpr()->getType();
912 const CXXRecordDecl *DerivedDecl =
913 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
914
915 for (CastExpr::path_const_iterator PathI = E->path_begin(),
916 PathE = E->path_end(); PathI != PathE; ++PathI) {
917 const CXXBaseSpecifier *Base = *PathI;
918
919 // FIXME: If the base is virtual, we'd need to determine the type of the
920 // most derived class and we don't support that right now.
921 if (Base->isVirtual())
922 return false;
923
924 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
925 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
926
Ken Dyck02155cb2011-01-26 02:17:08 +0000927 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000928 DerivedDecl = BaseDecl;
929 }
930
931 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000932 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000933 return true;
934 }
935
John McCalle84af4e2010-11-13 01:35:44 +0000936 case CK_NullToPointer: {
937 Result.Base = 0;
938 Result.Offset = CharUnits::Zero();
939 return true;
940 }
941
John McCalle3027922010-08-25 11:45:40 +0000942 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000943 APValue Value;
944 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000945 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000946
John McCall45d55e42010-05-07 21:00:08 +0000947 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000948 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000949 Result.Base = 0;
950 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
951 return true;
952 } else {
953 // Cast is of an lvalue, no need to change value.
954 Result.Base = Value.getLValueBase();
955 Result.Offset = Value.getLValueOffset();
956 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000957 }
958 }
John McCalle3027922010-08-25 11:45:40 +0000959 case CK_ArrayToPointerDecay:
960 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000961 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000962 }
963
Richard Smith11562c52011-10-28 17:51:58 +0000964 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +0000965}
Chris Lattner05706e882008-07-11 18:11:29 +0000966
Peter Collingbournee9200682011-05-13 03:29:01 +0000967bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000968 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000969 Builtin::BI__builtin___CFStringMakeConstantString ||
970 E->isBuiltinCall(Info.Ctx) ==
971 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000972 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000973
Peter Collingbournee9200682011-05-13 03:29:01 +0000974 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000975}
Chris Lattner05706e882008-07-11 18:11:29 +0000976
977//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000978// Vector Evaluation
979//===----------------------------------------------------------------------===//
980
981namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000982 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +0000983 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
984 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000985 public:
Mike Stump11289f42009-09-09 15:08:12 +0000986
Richard Smith2d406342011-10-22 21:10:00 +0000987 VectorExprEvaluator(EvalInfo &info, APValue &Result)
988 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +0000989
Richard Smith2d406342011-10-22 21:10:00 +0000990 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
991 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
992 // FIXME: remove this APValue copy.
993 Result = APValue(V.data(), V.size());
994 return true;
995 }
996 bool Success(const APValue &V, const Expr *E) {
997 Result = V;
998 return true;
999 }
1000 bool Error(const Expr *E) { return false; }
1001 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00001002
Richard Smith2d406342011-10-22 21:10:00 +00001003 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00001004 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00001005 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00001006 bool VisitInitListExpr(const InitListExpr *E);
1007 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001008 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00001009 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00001010 // shufflevector, ExtVectorElementExpr
1011 // (Note that these require implementing conversions
1012 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001013 };
1014} // end anonymous namespace
1015
1016static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001017 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00001018 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001019}
1020
Richard Smith2d406342011-10-22 21:10:00 +00001021bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
1022 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001023 QualType EltTy = VTy->getElementType();
1024 unsigned NElts = VTy->getNumElements();
1025 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +00001026
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001027 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00001028 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001029
Eli Friedmanc757de22011-03-25 00:43:55 +00001030 switch (E->getCastKind()) {
1031 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00001032 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00001033 if (SETy->isIntegerType()) {
1034 APSInt IntResult;
1035 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001036 return Error(E);
1037 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00001038 } else if (SETy->isRealFloatingType()) {
1039 APFloat F(0.0);
1040 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001041 return Error(E);
1042 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00001043 } else {
Richard Smith2d406342011-10-22 21:10:00 +00001044 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001045 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001046
1047 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00001048 SmallVector<APValue, 4> Elts(NElts, Val);
1049 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00001050 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001051 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +00001052 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +00001053 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +00001054 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001055
Eli Friedmanc757de22011-03-25 00:43:55 +00001056 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +00001057 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +00001058
Eli Friedmanc757de22011-03-25 00:43:55 +00001059 APSInt Init;
1060 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001061 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001062
Eli Friedmanc757de22011-03-25 00:43:55 +00001063 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
1064 "Vectors must be composed of ints or floats");
1065
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001066 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +00001067 for (unsigned i = 0; i != NElts; ++i) {
1068 APSInt Tmp = Init.extOrTrunc(EltWidth);
1069
1070 if (EltTy->isIntegerType())
1071 Elts.push_back(APValue(Tmp));
1072 else
1073 Elts.push_back(APValue(APFloat(Tmp)));
1074
1075 Init >>= EltWidth;
1076 }
Richard Smith2d406342011-10-22 21:10:00 +00001077 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +00001078 }
Eli Friedmanc757de22011-03-25 00:43:55 +00001079 default:
Richard Smith11562c52011-10-28 17:51:58 +00001080 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00001081 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001082}
1083
Richard Smith2d406342011-10-22 21:10:00 +00001084bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001085VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00001086 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001087 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00001088 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00001089
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001090 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001091 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001092
John McCall875679e2010-06-11 17:54:15 +00001093 // If a vector is initialized with a single element, that value
1094 // becomes every element of the vector, not just the first.
1095 // This is the behavior described in the IBM AltiVec documentation.
1096 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +00001097
1098 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +00001099 // vector (OpenCL 6.1.6).
1100 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +00001101 return Visit(E->getInit(0));
1102
John McCall875679e2010-06-11 17:54:15 +00001103 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001104 if (EltTy->isIntegerType()) {
1105 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +00001106 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001107 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001108 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001109 } else {
1110 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +00001111 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001112 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001113 InitValue = APValue(f);
1114 }
1115 for (unsigned i = 0; i < NumElements; i++) {
1116 Elements.push_back(InitValue);
1117 }
1118 } else {
1119 for (unsigned i = 0; i < NumElements; i++) {
1120 if (EltTy->isIntegerType()) {
1121 llvm::APSInt sInt(32);
1122 if (i < NumInits) {
1123 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001124 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001125 } else {
1126 sInt = Info.Ctx.MakeIntValue(0, EltTy);
1127 }
1128 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +00001129 } else {
John McCall875679e2010-06-11 17:54:15 +00001130 llvm::APFloat f(0.0);
1131 if (i < NumInits) {
1132 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +00001133 return Error(E);
John McCall875679e2010-06-11 17:54:15 +00001134 } else {
1135 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
1136 }
1137 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +00001138 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001139 }
1140 }
Richard Smith2d406342011-10-22 21:10:00 +00001141 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001142}
1143
Richard Smith2d406342011-10-22 21:10:00 +00001144bool
1145VectorExprEvaluator::ValueInitialization(const Expr *E) {
1146 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001147 QualType EltTy = VT->getElementType();
1148 APValue ZeroElement;
1149 if (EltTy->isIntegerType())
1150 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1151 else
1152 ZeroElement =
1153 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1154
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001155 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001156 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001157}
1158
Richard Smith2d406342011-10-22 21:10:00 +00001159bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00001160 VisitIgnoredValue(E->getSubExpr());
Richard Smith2d406342011-10-22 21:10:00 +00001161 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001162}
1163
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001164//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001165// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00001166//
1167// As a GNU extension, we support casting pointers to sufficiently-wide integer
1168// types and back in constant folding. Integer values are thus represented
1169// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00001170//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001171
1172namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001173class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001174 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001175 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001176public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001177 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001178 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001179
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001180 bool Success(const llvm::APSInt &SI, const Expr *E) {
1181 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001182 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001183 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001184 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001185 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001186 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001187 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001188 return true;
1189 }
1190
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001191 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001192 assert(E->getType()->isIntegralOrEnumerationType() &&
1193 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001194 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001195 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001196 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001197 Result.getInt().setIsUnsigned(
1198 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001199 return true;
1200 }
1201
1202 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001203 assert(E->getType()->isIntegralOrEnumerationType() &&
1204 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001205 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001206 return true;
1207 }
1208
Ken Dyckdbc01912011-03-11 02:13:43 +00001209 bool Success(CharUnits Size, const Expr *E) {
1210 return Success(Size.getQuantity(), E);
1211 }
1212
1213
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001214 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001215 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001216 if (Info.EvalStatus.Diag == 0) {
1217 Info.EvalStatus.DiagLoc = L;
1218 Info.EvalStatus.Diag = D;
1219 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001220 }
Chris Lattner99415702008-07-12 00:14:42 +00001221 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001222 }
Mike Stump11289f42009-09-09 15:08:12 +00001223
Peter Collingbournee9200682011-05-13 03:29:01 +00001224 bool Success(const APValue &V, const Expr *E) {
1225 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001226 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001227 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001228 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
Richard Smith4ce706a2011-10-11 21:43:33 +00001231 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1232
Peter Collingbournee9200682011-05-13 03:29:01 +00001233 //===--------------------------------------------------------------------===//
1234 // Visitor Methods
1235 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001236
Chris Lattner7174bf32008-07-12 00:38:25 +00001237 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001238 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001239 }
1240 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001241 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001242 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001243
1244 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1245 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001246 if (CheckReferencedDecl(E, E->getDecl()))
1247 return true;
1248
1249 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001250 }
1251 bool VisitMemberExpr(const MemberExpr *E) {
1252 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00001253 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001254 return true;
1255 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001256
1257 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001258 }
1259
Peter Collingbournee9200682011-05-13 03:29:01 +00001260 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001261 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001262 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001263 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001264
Peter Collingbournee9200682011-05-13 03:29:01 +00001265 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001266 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001267
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001268 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001269 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001270 }
Mike Stump11289f42009-09-09 15:08:12 +00001271
Richard Smith4ce706a2011-10-11 21:43:33 +00001272 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001273 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001274 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001275 }
1276
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001277 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001278 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001279 }
1280
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001281 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1282 return Success(E->getValue(), E);
1283 }
1284
John Wiegley6242b6a2011-04-28 00:16:57 +00001285 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1286 return Success(E->getValue(), E);
1287 }
1288
John Wiegleyf9f65842011-04-25 06:54:41 +00001289 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1290 return Success(E->getValue(), E);
1291 }
1292
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001293 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001294 bool VisitUnaryImag(const UnaryOperator *E);
1295
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001296 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001297 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001298
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001299private:
Ken Dyck160146e2010-01-27 17:10:57 +00001300 CharUnits GetAlignOfExpr(const Expr *E);
1301 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001302 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001303 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001304 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001305};
Chris Lattner05706e882008-07-11 18:11:29 +00001306} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001307
Richard Smith11562c52011-10-28 17:51:58 +00001308/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
1309/// produce either the integer value or a pointer.
1310///
1311/// GCC has a heinous extension which folds casts between pointer types and
1312/// pointer-sized integral types. We support this by allowing the evaluation of
1313/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
1314/// Some simple arithmetic on such values is supported (they are treated much
1315/// like char*).
Daniel Dunbarce399542009-02-20 18:22:23 +00001316static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00001317 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001318 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001319}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001320
Daniel Dunbarce399542009-02-20 18:22:23 +00001321static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
1322 APValue Val;
1323 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1324 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001325 Result = Val.getInt();
1326 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001327}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001328
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001329bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001330 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001331 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001332 // Check for signedness/width mismatches between E type and ECD value.
1333 bool SameSign = (ECD->getInitVal().isSigned()
1334 == E->getType()->isSignedIntegerOrEnumerationType());
1335 bool SameWidth = (ECD->getInitVal().getBitWidth()
1336 == Info.Ctx.getIntWidth(E->getType()));
1337 if (SameSign && SameWidth)
1338 return Success(ECD->getInitVal(), E);
1339 else {
1340 // Get rid of mismatch (otherwise Success assertions will fail)
1341 // by computing a new value matching the type of E.
1342 llvm::APSInt Val = ECD->getInitVal();
1343 if (!SameSign)
1344 Val.setIsSigned(!ECD->getInitVal().isSigned());
1345 if (!SameWidth)
1346 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1347 return Success(Val, E);
1348 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001349 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001350 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001351}
1352
Chris Lattner86ee2862008-10-06 06:40:35 +00001353/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1354/// as GCC.
1355static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1356 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001357 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001358 enum gcc_type_class {
1359 no_type_class = -1,
1360 void_type_class, integer_type_class, char_type_class,
1361 enumeral_type_class, boolean_type_class,
1362 pointer_type_class, reference_type_class, offset_type_class,
1363 real_type_class, complex_type_class,
1364 function_type_class, method_type_class,
1365 record_type_class, union_type_class,
1366 array_type_class, string_type_class,
1367 lang_type_class
1368 };
Mike Stump11289f42009-09-09 15:08:12 +00001369
1370 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001371 // ideal, however it is what gcc does.
1372 if (E->getNumArgs() == 0)
1373 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001374
Chris Lattner86ee2862008-10-06 06:40:35 +00001375 QualType ArgTy = E->getArg(0)->getType();
1376 if (ArgTy->isVoidType())
1377 return void_type_class;
1378 else if (ArgTy->isEnumeralType())
1379 return enumeral_type_class;
1380 else if (ArgTy->isBooleanType())
1381 return boolean_type_class;
1382 else if (ArgTy->isCharType())
1383 return string_type_class; // gcc doesn't appear to use char_type_class
1384 else if (ArgTy->isIntegerType())
1385 return integer_type_class;
1386 else if (ArgTy->isPointerType())
1387 return pointer_type_class;
1388 else if (ArgTy->isReferenceType())
1389 return reference_type_class;
1390 else if (ArgTy->isRealType())
1391 return real_type_class;
1392 else if (ArgTy->isComplexType())
1393 return complex_type_class;
1394 else if (ArgTy->isFunctionType())
1395 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001396 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001397 return record_type_class;
1398 else if (ArgTy->isUnionType())
1399 return union_type_class;
1400 else if (ArgTy->isArrayType())
1401 return array_type_class;
1402 else if (ArgTy->isUnionType())
1403 return union_type_class;
1404 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001405 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001406 return -1;
1407}
1408
John McCall95007602010-05-10 23:27:23 +00001409/// Retrieves the "underlying object type" of the given expression,
1410/// as used by __builtin_object_size.
1411QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1412 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1413 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1414 return VD->getType();
1415 } else if (isa<CompoundLiteralExpr>(E)) {
1416 return E->getType();
1417 }
1418
1419 return QualType();
1420}
1421
Peter Collingbournee9200682011-05-13 03:29:01 +00001422bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001423 // TODO: Perhaps we should let LLVM lower this?
1424 LValue Base;
1425 if (!EvaluatePointer(E->getArg(0), Base, Info))
1426 return false;
1427
1428 // If we can prove the base is null, lower to zero now.
1429 const Expr *LVBase = Base.getLValueBase();
1430 if (!LVBase) return Success(0, E);
1431
1432 QualType T = GetObjectType(LVBase);
1433 if (T.isNull() ||
1434 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001435 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001436 T->isVariablyModifiedType() ||
1437 T->isDependentType())
1438 return false;
1439
1440 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1441 CharUnits Offset = Base.getLValueOffset();
1442
1443 if (!Offset.isNegative() && Offset <= Size)
1444 Size -= Offset;
1445 else
1446 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001447 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001448}
1449
Peter Collingbournee9200682011-05-13 03:29:01 +00001450bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001451 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001452 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001453 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001454
1455 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001456 if (TryEvaluateBuiltinObjectSize(E))
1457 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001458
Eric Christopher99469702010-01-19 22:58:35 +00001459 // If evaluating the argument has side-effects we can't determine
1460 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001461 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001462 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001463 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001464 return Success(0, E);
1465 }
Mike Stump876387b2009-10-27 22:09:17 +00001466
Mike Stump722cedf2009-10-26 18:35:08 +00001467 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1468 }
1469
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001470 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001471 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001472
Anders Carlsson4c76e932008-11-24 04:21:33 +00001473 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001474 // __builtin_constant_p always has one operand: it returns true if that
1475 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001476 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001477
1478 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001479 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001480 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001481 return Success(Operand, E);
1482 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001483
1484 case Builtin::BI__builtin_expect:
1485 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001486
1487 case Builtin::BIstrlen:
1488 case Builtin::BI__builtin_strlen:
1489 // As an extension, we support strlen() and __builtin_strlen() as constant
1490 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001491 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001492 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1493 // The string literal may have embedded null characters. Find the first
1494 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001495 StringRef Str = S->getString();
1496 StringRef::size_type Pos = Str.find(0);
1497 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001498 Str = Str.substr(0, Pos);
1499
1500 return Success(Str.size(), E);
1501 }
1502
1503 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001504
1505 case Builtin::BI__atomic_is_lock_free: {
1506 APSInt SizeVal;
1507 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1508 return false;
1509
1510 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1511 // of two less than the maximum inline atomic width, we know it is
1512 // lock-free. If the size isn't a power of two, or greater than the
1513 // maximum alignment where we promote atomics, we know it is not lock-free
1514 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1515 // the answer can only be determined at runtime; for example, 16-byte
1516 // atomics have lock-free implementations on some, but not all,
1517 // x86-64 processors.
1518
1519 // Check power-of-two.
1520 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1521 if (!Size.isPowerOfTwo())
1522#if 0
1523 // FIXME: Suppress this folding until the ABI for the promotion width
1524 // settles.
1525 return Success(0, E);
1526#else
1527 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1528#endif
1529
1530#if 0
1531 // Check against promotion width.
1532 // FIXME: Suppress this folding until the ABI for the promotion width
1533 // settles.
1534 unsigned PromoteWidthBits =
1535 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1536 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1537 return Success(0, E);
1538#endif
1539
1540 // Check against inlining width.
1541 unsigned InlineWidthBits =
1542 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1543 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1544 return Success(1, E);
1545
1546 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1547 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001548 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001549}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001550
Chris Lattnere13042c2008-07-11 19:10:17 +00001551bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith11562c52011-10-28 17:51:58 +00001552 if (E->isAssignmentOp())
1553 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
1554
John McCalle3027922010-08-25 11:45:40 +00001555 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00001556 VisitIgnoredValue(E->getLHS());
1557 return Visit(E->getRHS());
Eli Friedman5a332ea2008-11-13 06:09:17 +00001558 }
1559
1560 if (E->isLogicalOp()) {
1561 // These need to be handled specially because the operands aren't
1562 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001563 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001564
Richard Smith11562c52011-10-28 17:51:58 +00001565 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001566 // We were able to evaluate the LHS, see if we can get away with not
1567 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001568 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001569 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001570
Richard Smith11562c52011-10-28 17:51:58 +00001571 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001572 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001573 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001574 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001575 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001576 }
1577 } else {
Richard Smith11562c52011-10-28 17:51:58 +00001578 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001579 // We can't evaluate the LHS; however, sometimes the result
1580 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001581 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1582 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001583 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001584 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001585 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001586
1587 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001588 }
1589 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001590 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001591
Eli Friedman5a332ea2008-11-13 06:09:17 +00001592 return false;
1593 }
1594
Anders Carlssonacc79812008-11-16 07:17:21 +00001595 QualType LHSTy = E->getLHS()->getType();
1596 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001597
1598 if (LHSTy->isAnyComplexType()) {
1599 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001600 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001601
1602 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1603 return false;
1604
1605 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1606 return false;
1607
1608 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001609 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001610 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001611 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001612 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1613
John McCalle3027922010-08-25 11:45:40 +00001614 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001615 return Success((CR_r == APFloat::cmpEqual &&
1616 CR_i == APFloat::cmpEqual), E);
1617 else {
John McCalle3027922010-08-25 11:45:40 +00001618 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001619 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001620 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001621 CR_r == APFloat::cmpLessThan ||
1622 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001623 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001624 CR_i == APFloat::cmpLessThan ||
1625 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001626 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001627 } else {
John McCalle3027922010-08-25 11:45:40 +00001628 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001629 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1630 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1631 else {
John McCalle3027922010-08-25 11:45:40 +00001632 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001633 "Invalid compex comparison.");
1634 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1635 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1636 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001637 }
1638 }
Mike Stump11289f42009-09-09 15:08:12 +00001639
Anders Carlssonacc79812008-11-16 07:17:21 +00001640 if (LHSTy->isRealFloatingType() &&
1641 RHSTy->isRealFloatingType()) {
1642 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001643
Anders Carlssonacc79812008-11-16 07:17:21 +00001644 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1645 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001646
Anders Carlssonacc79812008-11-16 07:17:21 +00001647 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1648 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001649
Anders Carlssonacc79812008-11-16 07:17:21 +00001650 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001651
Anders Carlssonacc79812008-11-16 07:17:21 +00001652 switch (E->getOpcode()) {
1653 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001654 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001655 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001656 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001657 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001658 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001659 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001660 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001661 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001662 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001663 E);
John McCalle3027922010-08-25 11:45:40 +00001664 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001665 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001666 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001667 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001668 || CR == APFloat::cmpLessThan
1669 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001670 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001671 }
Mike Stump11289f42009-09-09 15:08:12 +00001672
Eli Friedmana38da572009-04-28 19:17:36 +00001673 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001674 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001675 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001676 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1677 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001678
John McCall45d55e42010-05-07 21:00:08 +00001679 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001680 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1681 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001682
Eli Friedman334046a2009-06-14 02:17:33 +00001683 // Reject any bases from the normal codepath; we special-case comparisons
1684 // to null.
1685 if (LHSValue.getLValueBase()) {
1686 if (!E->isEqualityOp())
1687 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001688 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001689 return false;
1690 bool bres;
1691 if (!EvalPointerValueAsBool(LHSValue, bres))
1692 return false;
John McCalle3027922010-08-25 11:45:40 +00001693 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001694 } else if (RHSValue.getLValueBase()) {
1695 if (!E->isEqualityOp())
1696 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001697 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001698 return false;
1699 bool bres;
1700 if (!EvalPointerValueAsBool(RHSValue, bres))
1701 return false;
John McCalle3027922010-08-25 11:45:40 +00001702 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001703 }
Eli Friedman64004332009-03-23 04:38:34 +00001704
John McCalle3027922010-08-25 11:45:40 +00001705 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001706 QualType Type = E->getLHS()->getType();
1707 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001708
Ken Dyck02990832010-01-15 12:37:54 +00001709 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001710 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001711 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001712
Ken Dyck02990832010-01-15 12:37:54 +00001713 CharUnits Diff = LHSValue.getLValueOffset() -
1714 RHSValue.getLValueOffset();
1715 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001716 }
1717 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001718 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001719 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001720 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001721 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1722 }
1723 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001724 }
1725 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001726 if (!LHSTy->isIntegralOrEnumerationType() ||
1727 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001728 // We can't continue from here for non-integral types, and they
1729 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001730 return false;
1731 }
1732
Anders Carlsson9c181652008-07-08 14:35:21 +00001733 // The LHS of a constant expr is always evaluated and needed.
Richard Smith11562c52011-10-28 17:51:58 +00001734 APValue LHSVal;
1735 if (!EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info))
Chris Lattner99415702008-07-12 00:14:42 +00001736 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001737
Richard Smith11562c52011-10-28 17:51:58 +00001738 if (!Visit(E->getRHS()))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001739 return false;
Richard Smith11562c52011-10-28 17:51:58 +00001740 APValue &RHSVal = Result;
Eli Friedman94c25c62009-03-24 01:14:50 +00001741
1742 // Handle cases like (unsigned long)&a + 4.
Richard Smith11562c52011-10-28 17:51:58 +00001743 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
1744 CharUnits Offset = LHSVal.getLValueOffset();
Ken Dyck02990832010-01-15 12:37:54 +00001745 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1746 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001747 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001748 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001749 else
Ken Dyck02990832010-01-15 12:37:54 +00001750 Offset -= AdditionalOffset;
Richard Smith11562c52011-10-28 17:51:58 +00001751 Result = APValue(LHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001752 return true;
1753 }
1754
1755 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001756 if (E->getOpcode() == BO_Add &&
Richard Smith11562c52011-10-28 17:51:58 +00001757 RHSVal.isLValue() && LHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001758 CharUnits Offset = RHSVal.getLValueOffset();
Richard Smith11562c52011-10-28 17:51:58 +00001759 Offset += CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Ken Dyck02990832010-01-15 12:37:54 +00001760 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001761 return true;
1762 }
1763
1764 // All the following cases expect both operands to be an integer
Richard Smith11562c52011-10-28 17:51:58 +00001765 if (!LHSVal.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001766 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001767
Richard Smith11562c52011-10-28 17:51:58 +00001768 APSInt &LHS = LHSVal.getInt();
1769 APSInt &RHS = RHSVal.getInt();
Eli Friedman94c25c62009-03-24 01:14:50 +00001770
Anders Carlsson9c181652008-07-08 14:35:21 +00001771 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001772 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001773 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
Richard Smith11562c52011-10-28 17:51:58 +00001774 case BO_Mul: return Success(LHS * RHS, E);
1775 case BO_Add: return Success(LHS + RHS, E);
1776 case BO_Sub: return Success(LHS - RHS, E);
1777 case BO_And: return Success(LHS & RHS, E);
1778 case BO_Xor: return Success(LHS ^ RHS, E);
1779 case BO_Or: return Success(LHS | RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001780 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001781 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001782 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00001783 return Success(LHS / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001784 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001785 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001786 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Richard Smith11562c52011-10-28 17:51:58 +00001787 return Success(LHS % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001788 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001789 // During constant-folding, a negative shift is an opposite shift.
1790 if (RHS.isSigned() && RHS.isNegative()) {
1791 RHS = -RHS;
1792 goto shift_right;
1793 }
1794
1795 shift_left:
1796 unsigned SA
Richard Smith11562c52011-10-28 17:51:58 +00001797 = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1798 return Success(LHS << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001799 }
John McCalle3027922010-08-25 11:45:40 +00001800 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001801 // During constant-folding, a negative shift is an opposite shift.
1802 if (RHS.isSigned() && RHS.isNegative()) {
1803 RHS = -RHS;
1804 goto shift_left;
1805 }
1806
1807 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001808 unsigned SA =
Richard Smith11562c52011-10-28 17:51:58 +00001809 (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1810 return Success(LHS >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001811 }
Mike Stump11289f42009-09-09 15:08:12 +00001812
Richard Smith11562c52011-10-28 17:51:58 +00001813 case BO_LT: return Success(LHS < RHS, E);
1814 case BO_GT: return Success(LHS > RHS, E);
1815 case BO_LE: return Success(LHS <= RHS, E);
1816 case BO_GE: return Success(LHS >= RHS, E);
1817 case BO_EQ: return Success(LHS == RHS, E);
1818 case BO_NE: return Success(LHS != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001819 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001820}
1821
Ken Dyck160146e2010-01-27 17:10:57 +00001822CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001823 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1824 // the result is the size of the referenced type."
1825 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1826 // result shall be the alignment of the referenced type."
1827 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1828 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001829
1830 // __alignof is defined to return the preferred alignment.
1831 return Info.Ctx.toCharUnitsFromBits(
1832 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001833}
1834
Ken Dyck160146e2010-01-27 17:10:57 +00001835CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001836 E = E->IgnoreParens();
1837
1838 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001839 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001840 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001841 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1842 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001843
Chris Lattner68061312009-01-24 21:53:27 +00001844 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001845 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1846 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001847
Chris Lattner24aeeab2009-01-24 21:09:06 +00001848 return GetAlignOfType(E->getType());
1849}
1850
1851
Peter Collingbournee190dee2011-03-11 19:24:49 +00001852/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1853/// a result as the expression's type.
1854bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1855 const UnaryExprOrTypeTraitExpr *E) {
1856 switch(E->getKind()) {
1857 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001858 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001859 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001860 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001861 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001862 }
Eli Friedman64004332009-03-23 04:38:34 +00001863
Peter Collingbournee190dee2011-03-11 19:24:49 +00001864 case UETT_VecStep: {
1865 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001866
Peter Collingbournee190dee2011-03-11 19:24:49 +00001867 if (Ty->isVectorType()) {
1868 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001869
Peter Collingbournee190dee2011-03-11 19:24:49 +00001870 // The vec_step built-in functions that take a 3-component
1871 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1872 if (n == 3)
1873 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001874
Peter Collingbournee190dee2011-03-11 19:24:49 +00001875 return Success(n, E);
1876 } else
1877 return Success(1, E);
1878 }
1879
1880 case UETT_SizeOf: {
1881 QualType SrcTy = E->getTypeOfArgument();
1882 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1883 // the result is the size of the referenced type."
1884 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1885 // result shall be the alignment of the referenced type."
1886 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1887 SrcTy = Ref->getPointeeType();
1888
1889 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1890 // extension.
1891 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1892 return Success(1, E);
1893
1894 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1895 if (!SrcTy->isConstantSizeType())
1896 return false;
1897
1898 // Get information about the size.
1899 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1900 }
1901 }
1902
1903 llvm_unreachable("unknown expr/type trait");
1904 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001905}
1906
Peter Collingbournee9200682011-05-13 03:29:01 +00001907bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001908 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001909 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001910 if (n == 0)
1911 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001912 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001913 for (unsigned i = 0; i != n; ++i) {
1914 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1915 switch (ON.getKind()) {
1916 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001917 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001918 APSInt IdxResult;
1919 if (!EvaluateInteger(Idx, IdxResult, Info))
1920 return false;
1921 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1922 if (!AT)
1923 return false;
1924 CurrentType = AT->getElementType();
1925 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1926 Result += IdxResult.getSExtValue() * ElementSize;
1927 break;
1928 }
1929
1930 case OffsetOfExpr::OffsetOfNode::Field: {
1931 FieldDecl *MemberDecl = ON.getField();
1932 const RecordType *RT = CurrentType->getAs<RecordType>();
1933 if (!RT)
1934 return false;
1935 RecordDecl *RD = RT->getDecl();
1936 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001937 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001938 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001939 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001940 CurrentType = MemberDecl->getType().getNonReferenceType();
1941 break;
1942 }
1943
1944 case OffsetOfExpr::OffsetOfNode::Identifier:
1945 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001946 return false;
1947
1948 case OffsetOfExpr::OffsetOfNode::Base: {
1949 CXXBaseSpecifier *BaseSpec = ON.getBase();
1950 if (BaseSpec->isVirtual())
1951 return false;
1952
1953 // Find the layout of the class whose base we are looking into.
1954 const RecordType *RT = CurrentType->getAs<RecordType>();
1955 if (!RT)
1956 return false;
1957 RecordDecl *RD = RT->getDecl();
1958 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1959
1960 // Find the base class itself.
1961 CurrentType = BaseSpec->getType();
1962 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1963 if (!BaseRT)
1964 return false;
1965
1966 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001967 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001968 break;
1969 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001970 }
1971 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001972 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001973}
1974
Chris Lattnere13042c2008-07-11 19:10:17 +00001975bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001976 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001977 // LNot's operand isn't necessarily an integer, so we handle it specially.
1978 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00001979 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00001980 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001981 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001982 }
1983
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001984 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001985 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001986 return false;
1987
Richard Smith11562c52011-10-28 17:51:58 +00001988 // Get the operand value.
1989 APValue Val;
1990 if (!Evaluate(Val, Info, E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001991 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001992
Chris Lattnerf09ad162008-07-11 22:15:16 +00001993 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001994 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001995 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1996 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001997 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001998 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001999 // FIXME: Should extension allow i-c-e extension expressions in its scope?
2000 // If so, we could clear the diagnostic ID.
Richard Smith11562c52011-10-28 17:51:58 +00002001 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002002 case UO_Plus:
Richard Smith11562c52011-10-28 17:51:58 +00002003 // The result is just the value.
2004 return Success(Val, E);
John McCalle3027922010-08-25 11:45:40 +00002005 case UO_Minus:
Richard Smith11562c52011-10-28 17:51:58 +00002006 if (!Val.isInt()) return false;
2007 return Success(-Val.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00002008 case UO_Not:
Richard Smith11562c52011-10-28 17:51:58 +00002009 if (!Val.isInt()) return false;
2010 return Success(~Val.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00002011 }
Anders Carlsson9c181652008-07-08 14:35:21 +00002012}
Mike Stump11289f42009-09-09 15:08:12 +00002013
Chris Lattner477c4be2008-07-12 01:15:53 +00002014/// HandleCast - This is used to evaluate implicit or explicit casts where the
2015/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00002016bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
2017 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002018 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00002019 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00002020
Eli Friedmanc757de22011-03-25 00:43:55 +00002021 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00002022 case CK_BaseToDerived:
2023 case CK_DerivedToBase:
2024 case CK_UncheckedDerivedToBase:
2025 case CK_Dynamic:
2026 case CK_ToUnion:
2027 case CK_ArrayToPointerDecay:
2028 case CK_FunctionToPointerDecay:
2029 case CK_NullToPointer:
2030 case CK_NullToMemberPointer:
2031 case CK_BaseToDerivedMemberPointer:
2032 case CK_DerivedToBaseMemberPointer:
2033 case CK_ConstructorConversion:
2034 case CK_IntegralToPointer:
2035 case CK_ToVoid:
2036 case CK_VectorSplat:
2037 case CK_IntegralToFloating:
2038 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002039 case CK_CPointerToObjCPointerCast:
2040 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002041 case CK_AnyPointerToBlockPointerCast:
2042 case CK_ObjCObjectLValueCast:
2043 case CK_FloatingRealToComplex:
2044 case CK_FloatingComplexToReal:
2045 case CK_FloatingComplexCast:
2046 case CK_FloatingComplexToIntegralComplex:
2047 case CK_IntegralRealToComplex:
2048 case CK_IntegralComplexCast:
2049 case CK_IntegralComplexToFloatingComplex:
2050 llvm_unreachable("invalid cast kind for integral value");
2051
Eli Friedman9faf2f92011-03-25 19:07:11 +00002052 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00002053 case CK_Dependent:
2054 case CK_GetObjCProperty:
2055 case CK_LValueBitCast:
2056 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00002057 case CK_ARCProduceObject:
2058 case CK_ARCConsumeObject:
2059 case CK_ARCReclaimReturnedObject:
2060 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00002061 return false;
2062
2063 case CK_LValueToRValue:
2064 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002065 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00002066
2067 case CK_MemberPointerToBoolean:
2068 case CK_PointerToBoolean:
2069 case CK_IntegralToBoolean:
2070 case CK_FloatingToBoolean:
2071 case CK_FloatingComplexToBoolean:
2072 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002073 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00002074 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002075 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00002076 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002077 }
2078
Eli Friedmanc757de22011-03-25 00:43:55 +00002079 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00002080 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00002081 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002082
Eli Friedman742421e2009-02-20 01:15:07 +00002083 if (!Result.isInt()) {
2084 // Only allow casts of lvalues if they are lossless.
2085 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
2086 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002087
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002088 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00002089 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00002090 }
Mike Stump11289f42009-09-09 15:08:12 +00002091
Eli Friedmanc757de22011-03-25 00:43:55 +00002092 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00002093 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00002094 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00002095 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002096
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002097 if (LV.getLValueBase()) {
2098 // Only allow based lvalue casts if they are lossless.
2099 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
2100 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00002101
John McCall45d55e42010-05-07 21:00:08 +00002102 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002103 return true;
2104 }
2105
Ken Dyck02990832010-01-15 12:37:54 +00002106 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
2107 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00002108 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002109 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002110
Eli Friedmanc757de22011-03-25 00:43:55 +00002111 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00002112 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002113 if (!EvaluateComplex(SubExpr, C, Info))
2114 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00002115 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00002116 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00002117
Eli Friedmanc757de22011-03-25 00:43:55 +00002118 case CK_FloatingToIntegral: {
2119 APFloat F(0.0);
2120 if (!EvaluateFloat(SubExpr, F, Info))
2121 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00002122
Eli Friedmanc757de22011-03-25 00:43:55 +00002123 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
2124 }
2125 }
Mike Stump11289f42009-09-09 15:08:12 +00002126
Eli Friedmanc757de22011-03-25 00:43:55 +00002127 llvm_unreachable("unknown cast resulting in integral value");
2128 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00002129}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002130
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002131bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2132 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002133 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002134 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2135 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2136 return Success(LV.getComplexIntReal(), E);
2137 }
2138
2139 return Visit(E->getSubExpr());
2140}
2141
Eli Friedman4e7a2412009-02-27 04:45:43 +00002142bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002143 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002144 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002145 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2146 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2147 return Success(LV.getComplexIntImag(), E);
2148 }
2149
Richard Smith4a678122011-10-24 18:44:57 +00002150 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00002151 return Success(0, E);
2152}
2153
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002154bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2155 return Success(E->getPackLength(), E);
2156}
2157
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002158bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2159 return Success(E->getValue(), E);
2160}
2161
Chris Lattner05706e882008-07-11 18:11:29 +00002162//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002163// Float Evaluation
2164//===----------------------------------------------------------------------===//
2165
2166namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002167class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002168 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002169 APFloat &Result;
2170public:
2171 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002172 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002173
Peter Collingbournee9200682011-05-13 03:29:01 +00002174 bool Success(const APValue &V, const Expr *e) {
2175 Result = V.getFloat();
2176 return true;
2177 }
2178 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002179 return false;
2180 }
2181
Richard Smith4ce706a2011-10-11 21:43:33 +00002182 bool ValueInitialization(const Expr *E) {
2183 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2184 return true;
2185 }
2186
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002187 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002188
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002189 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002190 bool VisitBinaryOperator(const BinaryOperator *E);
2191 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002192 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002193
John McCallb1fb0d32010-05-07 22:08:54 +00002194 bool VisitUnaryReal(const UnaryOperator *E);
2195 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002196
John McCallb1fb0d32010-05-07 22:08:54 +00002197 // FIXME: Missing: array subscript of vector, member of vector,
2198 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002199};
2200} // end anonymous namespace
2201
2202static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002203 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002204 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002205}
2206
Jay Foad39c79802011-01-12 09:06:06 +00002207static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002208 QualType ResultTy,
2209 const Expr *Arg,
2210 bool SNaN,
2211 llvm::APFloat &Result) {
2212 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2213 if (!S) return false;
2214
2215 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2216
2217 llvm::APInt fill;
2218
2219 // Treat empty strings as if they were zero.
2220 if (S->getString().empty())
2221 fill = llvm::APInt(32, 0);
2222 else if (S->getString().getAsInteger(0, fill))
2223 return false;
2224
2225 if (SNaN)
2226 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2227 else
2228 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2229 return true;
2230}
2231
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002232bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002233 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002234 default:
2235 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2236
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002237 case Builtin::BI__builtin_huge_val:
2238 case Builtin::BI__builtin_huge_valf:
2239 case Builtin::BI__builtin_huge_vall:
2240 case Builtin::BI__builtin_inf:
2241 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002242 case Builtin::BI__builtin_infl: {
2243 const llvm::fltSemantics &Sem =
2244 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002245 Result = llvm::APFloat::getInf(Sem);
2246 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
John McCall16291492010-02-28 13:00:19 +00002249 case Builtin::BI__builtin_nans:
2250 case Builtin::BI__builtin_nansf:
2251 case Builtin::BI__builtin_nansl:
2252 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2253 true, Result);
2254
Chris Lattner0b7282e2008-10-06 06:31:58 +00002255 case Builtin::BI__builtin_nan:
2256 case Builtin::BI__builtin_nanf:
2257 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002258 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002259 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002260 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2261 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002262
2263 case Builtin::BI__builtin_fabs:
2264 case Builtin::BI__builtin_fabsf:
2265 case Builtin::BI__builtin_fabsl:
2266 if (!EvaluateFloat(E->getArg(0), Result, Info))
2267 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002268
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002269 if (Result.isNegative())
2270 Result.changeSign();
2271 return true;
2272
Mike Stump11289f42009-09-09 15:08:12 +00002273 case Builtin::BI__builtin_copysign:
2274 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002275 case Builtin::BI__builtin_copysignl: {
2276 APFloat RHS(0.);
2277 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2278 !EvaluateFloat(E->getArg(1), RHS, Info))
2279 return false;
2280 Result.copySign(RHS);
2281 return true;
2282 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002283 }
2284}
2285
John McCallb1fb0d32010-05-07 22:08:54 +00002286bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002287 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2288 ComplexValue CV;
2289 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2290 return false;
2291 Result = CV.FloatReal;
2292 return true;
2293 }
2294
2295 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002296}
2297
2298bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002299 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2300 ComplexValue CV;
2301 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2302 return false;
2303 Result = CV.FloatImag;
2304 return true;
2305 }
2306
Richard Smith4a678122011-10-24 18:44:57 +00002307 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00002308 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2309 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002310 return true;
2311}
2312
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002313bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002314 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002315 return false;
2316
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002317 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2318 return false;
2319
2320 switch (E->getOpcode()) {
2321 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002322 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002323 return true;
John McCalle3027922010-08-25 11:45:40 +00002324 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002325 Result.changeSign();
2326 return true;
2327 }
2328}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002329
Eli Friedman24c01542008-08-22 00:06:13 +00002330bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002331 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002332 VisitIgnoredValue(E->getLHS());
2333 return Visit(E->getRHS());
Eli Friedman141fbf32009-11-16 04:25:37 +00002334 }
2335
Anders Carlssona5df61a2010-10-31 01:21:47 +00002336 // We can't evaluate pointer-to-member operations.
2337 if (E->isPtrMemOp())
2338 return false;
2339
Eli Friedman24c01542008-08-22 00:06:13 +00002340 // FIXME: Diagnostics? I really don't understand how the warnings
2341 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002342 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002343 if (!EvaluateFloat(E->getLHS(), Result, Info))
2344 return false;
2345 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2346 return false;
2347
2348 switch (E->getOpcode()) {
2349 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002350 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002351 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2352 return true;
John McCalle3027922010-08-25 11:45:40 +00002353 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002354 Result.add(RHS, APFloat::rmNearestTiesToEven);
2355 return true;
John McCalle3027922010-08-25 11:45:40 +00002356 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002357 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2358 return true;
John McCalle3027922010-08-25 11:45:40 +00002359 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002360 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2361 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002362 }
2363}
2364
2365bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2366 Result = E->getValue();
2367 return true;
2368}
2369
Peter Collingbournee9200682011-05-13 03:29:01 +00002370bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2371 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002372
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002373 switch (E->getCastKind()) {
2374 default:
Richard Smith11562c52011-10-28 17:51:58 +00002375 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002376
2377 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002378 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002379 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002380 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002381 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002382 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002383 return true;
2384 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002385
2386 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002387 if (!Visit(SubExpr))
2388 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002389 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2390 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002391 return true;
2392 }
John McCalld7646252010-11-14 08:17:51 +00002393
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002394 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002395 ComplexValue V;
2396 if (!EvaluateComplex(SubExpr, V, Info))
2397 return false;
2398 Result = V.getComplexFloatReal();
2399 return true;
2400 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002401 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002402
2403 return false;
2404}
2405
Eli Friedman24c01542008-08-22 00:06:13 +00002406//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002407// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002408//===----------------------------------------------------------------------===//
2409
2410namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002411class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002412 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002413 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002414
Anders Carlsson537969c2008-11-16 20:27:53 +00002415public:
John McCall93d91dc2010-05-07 17:22:02 +00002416 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002417 : ExprEvaluatorBaseTy(info), Result(Result) {}
2418
2419 bool Success(const APValue &V, const Expr *e) {
2420 Result.setFrom(V);
2421 return true;
2422 }
2423 bool Error(const Expr *E) {
2424 return false;
2425 }
Mike Stump11289f42009-09-09 15:08:12 +00002426
Anders Carlsson537969c2008-11-16 20:27:53 +00002427 //===--------------------------------------------------------------------===//
2428 // Visitor Methods
2429 //===--------------------------------------------------------------------===//
2430
Peter Collingbournee9200682011-05-13 03:29:01 +00002431 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002432
Peter Collingbournee9200682011-05-13 03:29:01 +00002433 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002434
John McCall93d91dc2010-05-07 17:22:02 +00002435 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002436 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002437 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002438};
2439} // end anonymous namespace
2440
John McCall93d91dc2010-05-07 17:22:02 +00002441static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2442 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002443 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002444 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002445}
2446
Peter Collingbournee9200682011-05-13 03:29:01 +00002447bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2448 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002449
2450 if (SubExpr->getType()->isRealFloatingType()) {
2451 Result.makeComplexFloat();
2452 APFloat &Imag = Result.FloatImag;
2453 if (!EvaluateFloat(SubExpr, Imag, Info))
2454 return false;
2455
2456 Result.FloatReal = APFloat(Imag.getSemantics());
2457 return true;
2458 } else {
2459 assert(SubExpr->getType()->isIntegerType() &&
2460 "Unexpected imaginary literal.");
2461
2462 Result.makeComplexInt();
2463 APSInt &Imag = Result.IntImag;
2464 if (!EvaluateInteger(SubExpr, Imag, Info))
2465 return false;
2466
2467 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2468 return true;
2469 }
2470}
2471
Peter Collingbournee9200682011-05-13 03:29:01 +00002472bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002473
John McCallfcef3cf2010-12-14 17:51:41 +00002474 switch (E->getCastKind()) {
2475 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002476 case CK_BaseToDerived:
2477 case CK_DerivedToBase:
2478 case CK_UncheckedDerivedToBase:
2479 case CK_Dynamic:
2480 case CK_ToUnion:
2481 case CK_ArrayToPointerDecay:
2482 case CK_FunctionToPointerDecay:
2483 case CK_NullToPointer:
2484 case CK_NullToMemberPointer:
2485 case CK_BaseToDerivedMemberPointer:
2486 case CK_DerivedToBaseMemberPointer:
2487 case CK_MemberPointerToBoolean:
2488 case CK_ConstructorConversion:
2489 case CK_IntegralToPointer:
2490 case CK_PointerToIntegral:
2491 case CK_PointerToBoolean:
2492 case CK_ToVoid:
2493 case CK_VectorSplat:
2494 case CK_IntegralCast:
2495 case CK_IntegralToBoolean:
2496 case CK_IntegralToFloating:
2497 case CK_FloatingToIntegral:
2498 case CK_FloatingToBoolean:
2499 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002500 case CK_CPointerToObjCPointerCast:
2501 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002502 case CK_AnyPointerToBlockPointerCast:
2503 case CK_ObjCObjectLValueCast:
2504 case CK_FloatingComplexToReal:
2505 case CK_FloatingComplexToBoolean:
2506 case CK_IntegralComplexToReal:
2507 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002508 case CK_ARCProduceObject:
2509 case CK_ARCConsumeObject:
2510 case CK_ARCReclaimReturnedObject:
2511 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002512 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002513
John McCallfcef3cf2010-12-14 17:51:41 +00002514 case CK_LValueToRValue:
2515 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00002516 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00002517
2518 case CK_Dependent:
2519 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002520 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002521 case CK_UserDefinedConversion:
2522 return false;
2523
2524 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002525 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002526 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002527 return false;
2528
John McCallfcef3cf2010-12-14 17:51:41 +00002529 Result.makeComplexFloat();
2530 Result.FloatImag = APFloat(Real.getSemantics());
2531 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002532 }
2533
John McCallfcef3cf2010-12-14 17:51:41 +00002534 case CK_FloatingComplexCast: {
2535 if (!Visit(E->getSubExpr()))
2536 return false;
2537
2538 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2539 QualType From
2540 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2541
2542 Result.FloatReal
2543 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2544 Result.FloatImag
2545 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2546 return true;
2547 }
2548
2549 case CK_FloatingComplexToIntegralComplex: {
2550 if (!Visit(E->getSubExpr()))
2551 return false;
2552
2553 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2554 QualType From
2555 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2556 Result.makeComplexInt();
2557 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2558 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2559 return true;
2560 }
2561
2562 case CK_IntegralRealToComplex: {
2563 APSInt &Real = Result.IntReal;
2564 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2565 return false;
2566
2567 Result.makeComplexInt();
2568 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2569 return true;
2570 }
2571
2572 case CK_IntegralComplexCast: {
2573 if (!Visit(E->getSubExpr()))
2574 return false;
2575
2576 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2577 QualType From
2578 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2579
2580 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2581 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2582 return true;
2583 }
2584
2585 case CK_IntegralComplexToFloatingComplex: {
2586 if (!Visit(E->getSubExpr()))
2587 return false;
2588
2589 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2590 QualType From
2591 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2592 Result.makeComplexFloat();
2593 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2594 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2595 return true;
2596 }
2597 }
2598
2599 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002600 return false;
2601}
2602
John McCall93d91dc2010-05-07 17:22:02 +00002603bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002604 if (E->getOpcode() == BO_Comma) {
Richard Smith4a678122011-10-24 18:44:57 +00002605 VisitIgnoredValue(E->getLHS());
2606 return Visit(E->getRHS());
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002607 }
John McCall93d91dc2010-05-07 17:22:02 +00002608 if (!Visit(E->getLHS()))
2609 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002610
John McCall93d91dc2010-05-07 17:22:02 +00002611 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002612 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002613 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002614
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002615 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2616 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002617 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002618 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002619 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002620 if (Result.isComplexFloat()) {
2621 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2622 APFloat::rmNearestTiesToEven);
2623 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2624 APFloat::rmNearestTiesToEven);
2625 } else {
2626 Result.getComplexIntReal() += RHS.getComplexIntReal();
2627 Result.getComplexIntImag() += RHS.getComplexIntImag();
2628 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002629 break;
John McCalle3027922010-08-25 11:45:40 +00002630 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002631 if (Result.isComplexFloat()) {
2632 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2633 APFloat::rmNearestTiesToEven);
2634 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2635 APFloat::rmNearestTiesToEven);
2636 } else {
2637 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2638 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2639 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002640 break;
John McCalle3027922010-08-25 11:45:40 +00002641 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002642 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002643 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002644 APFloat &LHS_r = LHS.getComplexFloatReal();
2645 APFloat &LHS_i = LHS.getComplexFloatImag();
2646 APFloat &RHS_r = RHS.getComplexFloatReal();
2647 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002648
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002649 APFloat Tmp = LHS_r;
2650 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2651 Result.getComplexFloatReal() = Tmp;
2652 Tmp = LHS_i;
2653 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2654 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2655
2656 Tmp = LHS_r;
2657 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2658 Result.getComplexFloatImag() = Tmp;
2659 Tmp = LHS_i;
2660 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2661 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2662 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002663 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002664 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002665 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2666 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002667 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002668 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2669 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2670 }
2671 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002672 case BO_Div:
2673 if (Result.isComplexFloat()) {
2674 ComplexValue LHS = Result;
2675 APFloat &LHS_r = LHS.getComplexFloatReal();
2676 APFloat &LHS_i = LHS.getComplexFloatImag();
2677 APFloat &RHS_r = RHS.getComplexFloatReal();
2678 APFloat &RHS_i = RHS.getComplexFloatImag();
2679 APFloat &Res_r = Result.getComplexFloatReal();
2680 APFloat &Res_i = Result.getComplexFloatImag();
2681
2682 APFloat Den = RHS_r;
2683 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2684 APFloat Tmp = RHS_i;
2685 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2686 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2687
2688 Res_r = LHS_r;
2689 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2690 Tmp = LHS_i;
2691 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2692 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2693 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2694
2695 Res_i = LHS_i;
2696 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2697 Tmp = LHS_r;
2698 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2699 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2700 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2701 } else {
2702 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2703 // FIXME: what about diagnostics?
2704 return false;
2705 }
2706 ComplexValue LHS = Result;
2707 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2708 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2709 Result.getComplexIntReal() =
2710 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2711 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2712 Result.getComplexIntImag() =
2713 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2714 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2715 }
2716 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002717 }
2718
John McCall93d91dc2010-05-07 17:22:02 +00002719 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002720}
2721
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002722bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2723 // Get the operand value into 'Result'.
2724 if (!Visit(E->getSubExpr()))
2725 return false;
2726
2727 switch (E->getOpcode()) {
2728 default:
2729 // FIXME: what about diagnostics?
2730 return false;
2731 case UO_Extension:
2732 return true;
2733 case UO_Plus:
2734 // The result is always just the subexpr.
2735 return true;
2736 case UO_Minus:
2737 if (Result.isComplexFloat()) {
2738 Result.getComplexFloatReal().changeSign();
2739 Result.getComplexFloatImag().changeSign();
2740 }
2741 else {
2742 Result.getComplexIntReal() = -Result.getComplexIntReal();
2743 Result.getComplexIntImag() = -Result.getComplexIntImag();
2744 }
2745 return true;
2746 case UO_Not:
2747 if (Result.isComplexFloat())
2748 Result.getComplexFloatImag().changeSign();
2749 else
2750 Result.getComplexIntImag() = -Result.getComplexIntImag();
2751 return true;
2752 }
2753}
2754
Anders Carlsson537969c2008-11-16 20:27:53 +00002755//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002756// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002757//===----------------------------------------------------------------------===//
2758
Richard Smith725810a2011-10-16 21:26:27 +00002759static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002760 // In C, function designators are not lvalues, but we evaluate them as if they
2761 // are.
2762 if (E->isGLValue() || E->getType()->isFunctionType()) {
2763 LValue LV;
2764 if (!EvaluateLValue(E, LV, Info))
2765 return false;
2766 LV.moveInto(Result);
2767 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002768 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002769 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002770 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002771 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002772 return false;
John McCall45d55e42010-05-07 21:00:08 +00002773 } else if (E->getType()->hasPointerRepresentation()) {
2774 LValue LV;
2775 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002776 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002777 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002778 } else if (E->getType()->isRealFloatingType()) {
2779 llvm::APFloat F(0.0);
2780 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002781 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002782 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00002783 } else if (E->getType()->isAnyComplexType()) {
2784 ComplexValue C;
2785 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002786 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002787 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002788 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002789 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002790
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002791 return true;
2792}
2793
Richard Smith11562c52011-10-28 17:51:58 +00002794
John McCallc07a0c72011-02-17 10:25:35 +00002795/// Evaluate - Return true if this is a constant which we can fold using
2796/// any crazy technique (that has nothing to do with language standards) that
2797/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00002798/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
2799/// will be applied to the result.
John McCallc07a0c72011-02-17 10:25:35 +00002800bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2801 EvalInfo Info(Ctx, Result);
Richard Smith11562c52011-10-28 17:51:58 +00002802
2803 if (!::Evaluate(Result.Val, Info, this))
2804 return false;
2805
2806 if (isGLValue()) {
2807 LValue LV;
2808 LV.setFrom(Result.Val);
2809 return HandleLValueToRValueConversion(Info, getType(), LV, Result.Val);
2810 }
2811
2812 // FIXME: We don't allow expressions to fold to pointers or references to
2813 // locals. Code which calls Evaluate() isn't ready for that yet.
2814 return !Result.Val.isLValue() || IsGlobalLValue(Result.Val.getLValueBase());
John McCallc07a0c72011-02-17 10:25:35 +00002815}
2816
Jay Foad39c79802011-01-12 09:06:06 +00002817bool Expr::EvaluateAsBooleanCondition(bool &Result,
2818 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00002819 EvalResult Scratch;
2820 return Evaluate(Scratch, Ctx) && HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00002821}
2822
Richard Smithcaf33902011-10-10 18:28:20 +00002823bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00002824 EvalResult ExprResult;
2825 if (!Evaluate(ExprResult, Ctx) || ExprResult.HasSideEffects ||
2826 !ExprResult.Val.isInt()) {
2827 return false;
2828 }
2829 Result = ExprResult.Val.getInt();
2830 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00002831}
2832
Jay Foad39c79802011-01-12 09:06:06 +00002833bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002834 EvalInfo Info(Ctx, Result);
2835
John McCall45d55e42010-05-07 21:00:08 +00002836 LValue LV;
Richard Smith11562c52011-10-28 17:51:58 +00002837 if (EvaluateLValue(this, LV, Info) && !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002838 IsGlobalLValue(LV.Base)) {
2839 LV.moveInto(Result.Val);
2840 return true;
2841 }
2842 return false;
2843}
2844
Jay Foad39c79802011-01-12 09:06:06 +00002845bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2846 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002847 EvalInfo Info(Ctx, Result);
2848
2849 LValue LV;
2850 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002851 LV.moveInto(Result.Val);
2852 return true;
2853 }
2854 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002855}
2856
Chris Lattner67d7b922008-11-16 21:24:15 +00002857/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002858/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002859bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002860 EvalResult Result;
2861 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002862}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002863
Jay Foad39c79802011-01-12 09:06:06 +00002864bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002865 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002866}
2867
Richard Smithcaf33902011-10-10 18:28:20 +00002868APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002869 EvalResult EvalResult;
2870 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002871 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002872 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002873 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002874
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002875 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002876}
John McCall864e3962010-05-07 05:32:02 +00002877
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002878 bool Expr::EvalResult::isGlobalLValue() const {
2879 assert(Val.isLValue());
2880 return IsGlobalLValue(Val.getLValueBase());
2881 }
2882
2883
John McCall864e3962010-05-07 05:32:02 +00002884/// isIntegerConstantExpr - this recursive routine will test if an expression is
2885/// an integer constant expression.
2886
2887/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2888/// comma, etc
2889///
2890/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2891/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2892/// cast+dereference.
2893
2894// CheckICE - This function does the fundamental ICE checking: the returned
2895// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2896// Note that to reduce code duplication, this helper does no evaluation
2897// itself; the caller checks whether the expression is evaluatable, and
2898// in the rare cases where CheckICE actually cares about the evaluated
2899// value, it calls into Evalute.
2900//
2901// Meanings of Val:
2902// 0: This expression is an ICE if it can be evaluated by Evaluate.
2903// 1: This expression is not an ICE, but if it isn't evaluated, it's
2904// a legal subexpression for an ICE. This return value is used to handle
2905// the comma operator in C99 mode.
2906// 2: This expression is not an ICE, and is not a legal subexpression for one.
2907
Dan Gohman28ade552010-07-26 21:25:24 +00002908namespace {
2909
John McCall864e3962010-05-07 05:32:02 +00002910struct ICEDiag {
2911 unsigned Val;
2912 SourceLocation Loc;
2913
2914 public:
2915 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2916 ICEDiag() : Val(0) {}
2917};
2918
Dan Gohman28ade552010-07-26 21:25:24 +00002919}
2920
2921static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002922
2923static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2924 Expr::EvalResult EVResult;
2925 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2926 !EVResult.Val.isInt()) {
2927 return ICEDiag(2, E->getLocStart());
2928 }
2929 return NoDiag();
2930}
2931
2932static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2933 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002934 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002935 return ICEDiag(2, E->getLocStart());
2936 }
2937
2938 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002939#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002940#define STMT(Node, Base) case Expr::Node##Class:
2941#define EXPR(Node, Base)
2942#include "clang/AST/StmtNodes.inc"
2943 case Expr::PredefinedExprClass:
2944 case Expr::FloatingLiteralClass:
2945 case Expr::ImaginaryLiteralClass:
2946 case Expr::StringLiteralClass:
2947 case Expr::ArraySubscriptExprClass:
2948 case Expr::MemberExprClass:
2949 case Expr::CompoundAssignOperatorClass:
2950 case Expr::CompoundLiteralExprClass:
2951 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00002952 case Expr::DesignatedInitExprClass:
2953 case Expr::ImplicitValueInitExprClass:
2954 case Expr::ParenListExprClass:
2955 case Expr::VAArgExprClass:
2956 case Expr::AddrLabelExprClass:
2957 case Expr::StmtExprClass:
2958 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002959 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002960 case Expr::CXXDynamicCastExprClass:
2961 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002962 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002963 case Expr::CXXNullPtrLiteralExprClass:
2964 case Expr::CXXThisExprClass:
2965 case Expr::CXXThrowExprClass:
2966 case Expr::CXXNewExprClass:
2967 case Expr::CXXDeleteExprClass:
2968 case Expr::CXXPseudoDestructorExprClass:
2969 case Expr::UnresolvedLookupExprClass:
2970 case Expr::DependentScopeDeclRefExprClass:
2971 case Expr::CXXConstructExprClass:
2972 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002973 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002974 case Expr::CXXTemporaryObjectExprClass:
2975 case Expr::CXXUnresolvedConstructExprClass:
2976 case Expr::CXXDependentScopeMemberExprClass:
2977 case Expr::UnresolvedMemberExprClass:
2978 case Expr::ObjCStringLiteralClass:
2979 case Expr::ObjCEncodeExprClass:
2980 case Expr::ObjCMessageExprClass:
2981 case Expr::ObjCSelectorExprClass:
2982 case Expr::ObjCProtocolExprClass:
2983 case Expr::ObjCIvarRefExprClass:
2984 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002985 case Expr::ObjCIsaExprClass:
2986 case Expr::ShuffleVectorExprClass:
2987 case Expr::BlockExprClass:
2988 case Expr::BlockDeclRefExprClass:
2989 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002990 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002991 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002992 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002993 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002994 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002995 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002996 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00002997 return ICEDiag(2, E->getLocStart());
2998
Sebastian Redl12757ab2011-09-24 17:48:14 +00002999 case Expr::InitListExprClass:
3000 if (Ctx.getLangOptions().CPlusPlus0x) {
3001 const InitListExpr *ILE = cast<InitListExpr>(E);
3002 if (ILE->getNumInits() == 0)
3003 return NoDiag();
3004 if (ILE->getNumInits() == 1)
3005 return CheckICE(ILE->getInit(0), Ctx);
3006 // Fall through for more than 1 expression.
3007 }
3008 return ICEDiag(2, E->getLocStart());
3009
Douglas Gregor820ba7b2011-01-04 17:33:58 +00003010 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00003011 case Expr::GNUNullExprClass:
3012 // GCC considers the GNU __null value to be an integral constant expression.
3013 return NoDiag();
3014
John McCall7c454bb2011-07-15 05:09:51 +00003015 case Expr::SubstNonTypeTemplateParmExprClass:
3016 return
3017 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
3018
John McCall864e3962010-05-07 05:32:02 +00003019 case Expr::ParenExprClass:
3020 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00003021 case Expr::GenericSelectionExprClass:
3022 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003023 case Expr::IntegerLiteralClass:
3024 case Expr::CharacterLiteralClass:
3025 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00003026 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00003027 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00003028 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00003029 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00003030 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00003031 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00003032 return NoDiag();
3033 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00003034 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00003035 // C99 6.6/3 allows function calls within unevaluated subexpressions of
3036 // constant expressions, but they can never be ICEs because an ICE cannot
3037 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00003038 const CallExpr *CE = cast<CallExpr>(E);
3039 if (CE->isBuiltinCall(Ctx))
3040 return CheckEvalInICE(E, Ctx);
3041 return ICEDiag(2, E->getLocStart());
3042 }
3043 case Expr::DeclRefExprClass:
3044 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
3045 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00003046 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00003047 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3048
3049 // Parameter variables are never constants. Without this check,
3050 // getAnyInitializer() can find a default argument, which leads
3051 // to chaos.
3052 if (isa<ParmVarDecl>(D))
3053 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3054
3055 // C++ 7.1.5.1p2
3056 // A variable of non-volatile const-qualified integral or enumeration
3057 // type initialized by an ICE can be used in ICEs.
3058 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00003059 // Look for a declaration of this variable that has an initializer.
3060 const VarDecl *ID = 0;
3061 const Expr *Init = Dcl->getAnyInitializer(ID);
3062 if (Init) {
3063 if (ID->isInitKnownICE()) {
3064 // We have already checked whether this subexpression is an
3065 // integral constant expression.
3066 if (ID->isInitICE())
3067 return NoDiag();
3068 else
3069 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3070 }
3071
3072 // It's an ICE whether or not the definition we found is
3073 // out-of-line. See DR 721 and the discussion in Clang PR
3074 // 6206 for details.
3075
3076 if (Dcl->isCheckingICE()) {
3077 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
3078 }
3079
3080 Dcl->setCheckingICE();
3081 ICEDiag Result = CheckICE(Init, Ctx);
3082 // Cache the result of the ICE test.
3083 Dcl->setInitKnownICE(Result.Val == 0);
3084 return Result;
3085 }
3086 }
3087 }
3088 return ICEDiag(2, E->getLocStart());
3089 case Expr::UnaryOperatorClass: {
3090 const UnaryOperator *Exp = cast<UnaryOperator>(E);
3091 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003092 case UO_PostInc:
3093 case UO_PostDec:
3094 case UO_PreInc:
3095 case UO_PreDec:
3096 case UO_AddrOf:
3097 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00003098 // C99 6.6/3 allows increment and decrement within unevaluated
3099 // subexpressions of constant expressions, but they can never be ICEs
3100 // because an ICE cannot contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003101 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00003102 case UO_Extension:
3103 case UO_LNot:
3104 case UO_Plus:
3105 case UO_Minus:
3106 case UO_Not:
3107 case UO_Real:
3108 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00003109 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003110 }
3111
3112 // OffsetOf falls through here.
3113 }
3114 case Expr::OffsetOfExprClass: {
3115 // Note that per C99, offsetof must be an ICE. And AFAIK, using
3116 // Evaluate matches the proposed gcc behavior for cases like
Richard Smith62f65952011-10-24 22:35:48 +00003117 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCall864e3962010-05-07 05:32:02 +00003118 // compliance: we should warn earlier for offsetof expressions with
3119 // array subscripts that aren't ICEs, and if the array subscripts
3120 // are ICEs, the value of the offsetof must be an integer constant.
3121 return CheckEvalInICE(E, Ctx);
3122 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003123 case Expr::UnaryExprOrTypeTraitExprClass: {
3124 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3125 if ((Exp->getKind() == UETT_SizeOf) &&
3126 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003127 return ICEDiag(2, E->getLocStart());
3128 return NoDiag();
3129 }
3130 case Expr::BinaryOperatorClass: {
3131 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3132 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003133 case BO_PtrMemD:
3134 case BO_PtrMemI:
3135 case BO_Assign:
3136 case BO_MulAssign:
3137 case BO_DivAssign:
3138 case BO_RemAssign:
3139 case BO_AddAssign:
3140 case BO_SubAssign:
3141 case BO_ShlAssign:
3142 case BO_ShrAssign:
3143 case BO_AndAssign:
3144 case BO_XorAssign:
3145 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00003146 // C99 6.6/3 allows assignments within unevaluated subexpressions of
3147 // constant expressions, but they can never be ICEs because an ICE cannot
3148 // contain an lvalue operand.
John McCall864e3962010-05-07 05:32:02 +00003149 return ICEDiag(2, E->getLocStart());
3150
John McCalle3027922010-08-25 11:45:40 +00003151 case BO_Mul:
3152 case BO_Div:
3153 case BO_Rem:
3154 case BO_Add:
3155 case BO_Sub:
3156 case BO_Shl:
3157 case BO_Shr:
3158 case BO_LT:
3159 case BO_GT:
3160 case BO_LE:
3161 case BO_GE:
3162 case BO_EQ:
3163 case BO_NE:
3164 case BO_And:
3165 case BO_Xor:
3166 case BO_Or:
3167 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003168 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3169 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003170 if (Exp->getOpcode() == BO_Div ||
3171 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003172 // Evaluate gives an error for undefined Div/Rem, so make sure
3173 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003174 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003175 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003176 if (REval == 0)
3177 return ICEDiag(1, E->getLocStart());
3178 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003179 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003180 if (LEval.isMinSignedValue())
3181 return ICEDiag(1, E->getLocStart());
3182 }
3183 }
3184 }
John McCalle3027922010-08-25 11:45:40 +00003185 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003186 if (Ctx.getLangOptions().C99) {
3187 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3188 // if it isn't evaluated.
3189 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3190 return ICEDiag(1, E->getLocStart());
3191 } else {
3192 // In both C89 and C++, commas in ICEs are illegal.
3193 return ICEDiag(2, E->getLocStart());
3194 }
3195 }
3196 if (LHSResult.Val >= RHSResult.Val)
3197 return LHSResult;
3198 return RHSResult;
3199 }
John McCalle3027922010-08-25 11:45:40 +00003200 case BO_LAnd:
3201 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003202 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003203
3204 // C++0x [expr.const]p2:
3205 // [...] subexpressions of logical AND (5.14), logical OR
3206 // (5.15), and condi- tional (5.16) operations that are not
3207 // evaluated are not considered.
3208 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3209 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003210 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003211 return LHSResult;
3212
3213 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003214 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003215 return LHSResult;
3216 }
3217
John McCall864e3962010-05-07 05:32:02 +00003218 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3219 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3220 // Rare case where the RHS has a comma "side-effect"; we need
3221 // to actually check the condition to see whether the side
3222 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003223 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003224 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003225 return RHSResult;
3226 return NoDiag();
3227 }
3228
3229 if (LHSResult.Val >= RHSResult.Val)
3230 return LHSResult;
3231 return RHSResult;
3232 }
3233 }
3234 }
3235 case Expr::ImplicitCastExprClass:
3236 case Expr::CStyleCastExprClass:
3237 case Expr::CXXFunctionalCastExprClass:
3238 case Expr::CXXStaticCastExprClass:
3239 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00003240 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003241 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003242 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2d7bb042011-10-25 00:21:54 +00003243 if (isa<ExplicitCastExpr>(E) &&
Richard Smithc3e31e72011-10-24 18:26:35 +00003244 isa<FloatingLiteral>(SubExpr->IgnoreParenImpCasts()))
3245 return NoDiag();
Eli Friedman76d4e432011-09-29 21:49:34 +00003246 switch (cast<CastExpr>(E)->getCastKind()) {
3247 case CK_LValueToRValue:
3248 case CK_NoOp:
3249 case CK_IntegralToBoolean:
3250 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003251 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003252 default:
Eli Friedman76d4e432011-09-29 21:49:34 +00003253 return ICEDiag(2, E->getLocStart());
3254 }
John McCall864e3962010-05-07 05:32:02 +00003255 }
John McCallc07a0c72011-02-17 10:25:35 +00003256 case Expr::BinaryConditionalOperatorClass: {
3257 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3258 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3259 if (CommonResult.Val == 2) return CommonResult;
3260 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3261 if (FalseResult.Val == 2) return FalseResult;
3262 if (CommonResult.Val == 1) return CommonResult;
3263 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003264 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003265 return FalseResult;
3266 }
John McCall864e3962010-05-07 05:32:02 +00003267 case Expr::ConditionalOperatorClass: {
3268 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3269 // If the condition (ignoring parens) is a __builtin_constant_p call,
3270 // then only the true side is actually considered in an integer constant
3271 // expression, and it is fully evaluated. This is an important GNU
3272 // extension. See GCC PR38377 for discussion.
3273 if (const CallExpr *CallCE
3274 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3275 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3276 Expr::EvalResult EVResult;
3277 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3278 !EVResult.Val.isInt()) {
3279 return ICEDiag(2, E->getLocStart());
3280 }
3281 return NoDiag();
3282 }
3283 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003284 if (CondResult.Val == 2)
3285 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003286
3287 // C++0x [expr.const]p2:
3288 // subexpressions of [...] conditional (5.16) operations that
3289 // are not evaluated are not considered
3290 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003291 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003292 : false;
3293 ICEDiag TrueResult = NoDiag();
3294 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3295 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3296 ICEDiag FalseResult = NoDiag();
3297 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3298 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3299
John McCall864e3962010-05-07 05:32:02 +00003300 if (TrueResult.Val == 2)
3301 return TrueResult;
3302 if (FalseResult.Val == 2)
3303 return FalseResult;
3304 if (CondResult.Val == 1)
3305 return CondResult;
3306 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3307 return NoDiag();
3308 // Rare case where the diagnostics depend on which side is evaluated
3309 // Note that if we get here, CondResult is 0, and at least one of
3310 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003311 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003312 return FalseResult;
3313 }
3314 return TrueResult;
3315 }
3316 case Expr::CXXDefaultArgExprClass:
3317 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3318 case Expr::ChooseExprClass: {
3319 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3320 }
3321 }
3322
3323 // Silence a GCC warning
3324 return ICEDiag(2, E->getLocStart());
3325}
3326
3327bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3328 SourceLocation *Loc, bool isEvaluated) const {
3329 ICEDiag d = CheckICE(this, Ctx);
3330 if (d.Val != 0) {
3331 if (Loc) *Loc = d.Loc;
3332 return false;
3333 }
Richard Smith11562c52011-10-28 17:51:58 +00003334 if (!EvaluateAsInt(Result, Ctx))
John McCall864e3962010-05-07 05:32:02 +00003335 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00003336 return true;
3337}