blob: 5d34aff7a63945d0c6046a855e885509b91432c6 [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Benjamin Kramer024e6192011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
Richard Smith725810a2011-10-16 21:26:27 +000049 /// EvalStatus - Contains information about the evaluation.
50 Expr::EvalStatus &EvalStatus;
Benjamin Kramer024e6192011-03-04 13:12:48 +000051
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
Richard Smith725810a2011-10-16 21:26:27 +000060 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
61 : Ctx(C), EvalStatus(S) {}
Richard Smith4ce706a2011-10-11 21:43:33 +000062
63 const LangOptions &getLangOpts() { return Ctx.getLangOptions(); }
Benjamin Kramer024e6192011-03-04 13:12:48 +000064 };
65
John McCall93d91dc2010-05-07 17:22:02 +000066 struct ComplexValue {
67 private:
68 bool IsInt;
69
70 public:
71 APSInt IntReal, IntImag;
72 APFloat FloatReal, FloatImag;
73
74 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
75
76 void makeComplexFloat() { IsInt = false; }
77 bool isComplexFloat() const { return !IsInt; }
78 APFloat &getComplexFloatReal() { return FloatReal; }
79 APFloat &getComplexFloatImag() { return FloatImag; }
80
81 void makeComplexInt() { IsInt = true; }
82 bool isComplexInt() const { return IsInt; }
83 APSInt &getComplexIntReal() { return IntReal; }
84 APSInt &getComplexIntImag() { return IntImag; }
85
John McCallc07a0c72011-02-17 10:25:35 +000086 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +000087 if (isComplexFloat())
88 v = APValue(FloatReal, FloatImag);
89 else
90 v = APValue(IntReal, IntImag);
91 }
John McCallc07a0c72011-02-17 10:25:35 +000092 void setFrom(const APValue &v) {
93 assert(v.isComplexFloat() || v.isComplexInt());
94 if (v.isComplexFloat()) {
95 makeComplexFloat();
96 FloatReal = v.getComplexFloatReal();
97 FloatImag = v.getComplexFloatImag();
98 } else {
99 makeComplexInt();
100 IntReal = v.getComplexIntReal();
101 IntImag = v.getComplexIntImag();
102 }
103 }
John McCall93d91dc2010-05-07 17:22:02 +0000104 };
John McCall45d55e42010-05-07 21:00:08 +0000105
106 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000107 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000108 CharUnits Offset;
109
Peter Collingbournee9200682011-05-13 03:29:01 +0000110 const Expr *getLValueBase() { return Base; }
John McCall45d55e42010-05-07 21:00:08 +0000111 CharUnits getLValueOffset() { return Offset; }
112
John McCallc07a0c72011-02-17 10:25:35 +0000113 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000114 v = APValue(Base, Offset);
115 }
John McCallc07a0c72011-02-17 10:25:35 +0000116 void setFrom(const APValue &v) {
117 assert(v.isLValue());
118 Base = v.getLValueBase();
119 Offset = v.getLValueOffset();
120 }
John McCall45d55e42010-05-07 21:00:08 +0000121 };
John McCall93d91dc2010-05-07 17:22:02 +0000122}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000123
Richard Smith725810a2011-10-16 21:26:27 +0000124static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000125static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
126static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000127static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000128static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
129 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000130static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000131static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000132
133//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000134// Misc utilities
135//===----------------------------------------------------------------------===//
136
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000137static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000138 if (!E) return true;
139
140 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
141 if (isa<FunctionDecl>(DRE->getDecl()))
142 return true;
143 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
144 return VD->hasGlobalStorage();
145 return false;
146 }
147
148 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
149 return CLE->isFileScope();
150
151 return true;
152}
153
John McCall45d55e42010-05-07 21:00:08 +0000154static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
155 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000156
John McCalleb3e4f32010-05-07 21:34:32 +0000157 // A null base expression indicates a null pointer. These are always
158 // evaluatable, and they are false unless the offset is zero.
159 if (!Base) {
160 Result = !Value.Offset.isZero();
161 return true;
162 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000163
John McCall95007602010-05-10 23:27:23 +0000164 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000165 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000166
John McCalleb3e4f32010-05-07 21:34:32 +0000167 // We have a non-null base expression. These are generally known to
168 // be true, but if it'a decl-ref to a weak symbol it can be null at
169 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000170 Result = true;
171
172 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000173 if (!DeclRef)
174 return true;
175
John McCalleb3e4f32010-05-07 21:34:32 +0000176 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000177 const ValueDecl* Decl = DeclRef->getDecl();
178 if (Decl->hasAttr<WeakAttr>() ||
179 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000180 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000181 return false;
182
Eli Friedman334046a2009-06-14 02:17:33 +0000183 return true;
184}
185
John McCall1be1c632010-01-05 23:42:56 +0000186static bool HandleConversionToBool(const Expr* E, bool& Result,
187 EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000188 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000189 APSInt IntResult;
190 if (!EvaluateInteger(E, IntResult, Info))
191 return false;
192 Result = IntResult != 0;
193 return true;
194 } else if (E->getType()->isRealFloatingType()) {
195 APFloat FloatResult(0.0);
196 if (!EvaluateFloat(E, FloatResult, Info))
197 return false;
198 Result = !FloatResult.isZero();
199 return true;
Eli Friedman64004332009-03-23 04:38:34 +0000200 } else if (E->getType()->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +0000201 LValue PointerResult;
Eli Friedman9a156e52008-11-12 09:44:48 +0000202 if (!EvaluatePointer(E, PointerResult, Info))
203 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000204 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000205 } else if (E->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +0000206 ComplexValue ComplexResult;
Eli Friedman64004332009-03-23 04:38:34 +0000207 if (!EvaluateComplex(E, ComplexResult, Info))
208 return false;
209 if (ComplexResult.isComplexFloat()) {
210 Result = !ComplexResult.getComplexFloatReal().isZero() ||
211 !ComplexResult.getComplexFloatImag().isZero();
212 } else {
213 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
214 ComplexResult.getComplexIntImag().getBoolValue();
215 }
216 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000217 }
218
219 return false;
220}
221
Mike Stump11289f42009-09-09 15:08:12 +0000222static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000223 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000224 unsigned DestWidth = Ctx.getIntWidth(DestType);
225 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000226 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000227
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000228 // FIXME: Warning for overflow.
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000229 APSInt Result(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000230 bool ignored;
Jeffrey Yasskind0f079d2011-07-15 17:03:07 +0000231 (void)Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored);
232 return Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000233}
234
Mike Stump11289f42009-09-09 15:08:12 +0000235static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000236 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000237 bool ignored;
238 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000239 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000240 APFloat::rmNearestTiesToEven, &ignored);
241 return Result;
242}
243
Mike Stump11289f42009-09-09 15:08:12 +0000244static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000245 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000246 unsigned DestWidth = Ctx.getIntWidth(DestType);
247 APSInt Result = Value;
248 // Figure out if this is a truncate, extend or noop cast.
249 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000250 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000251 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000252 return Result;
253}
254
Mike Stump11289f42009-09-09 15:08:12 +0000255static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000256 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000257
258 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
259 Result.convertFromAPInt(Value, Value.isSigned(),
260 APFloat::rmNearestTiesToEven);
261 return Result;
262}
263
Richard Smith27908702011-10-24 17:54:18 +0000264/// Try to evaluate the initializer for a variable declaration.
265static APValue *EvaluateVarDeclInit(EvalInfo &Info, const VarDecl *VD) {
266 if (isa<ParmVarDecl>(VD))
267 return 0;
268
269 const Expr *Init = VD->getAnyInitializer();
270 if (!Init)
271 return 0;
272
273 if (APValue *V = VD->getEvaluatedValue())
274 return V;
275
276 if (VD->isEvaluatingValue())
277 return 0;
278
279 VD->setEvaluatingValue();
280
281 // FIXME: If the initializer isn't a constant expression, propagate up any
282 // diagnostic explaining why not.
283 Expr::EvalResult EResult;
284 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects)
285 VD->setEvaluatedValue(EResult.Val);
286 else
287 VD->setEvaluatedValue(APValue());
288
289 return VD->getEvaluatedValue();
290}
291
292bool IsConstNonVolatile(QualType T) {
293 Qualifiers Quals = T.getQualifiers();
294 return Quals.hasConst() && !Quals.hasVolatile();
295}
296
Mike Stump876387b2009-10-27 22:09:17 +0000297namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000298class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000299 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith725810a2011-10-16 21:26:27 +0000300 const ASTContext &Ctx;
Mike Stump876387b2009-10-27 22:09:17 +0000301public:
302
Richard Smith725810a2011-10-16 21:26:27 +0000303 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stump876387b2009-10-27 22:09:17 +0000304
305 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000306 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000307 return true;
308 }
309
Peter Collingbournee9200682011-05-13 03:29:01 +0000310 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
311 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000312 return Visit(E->getResultExpr());
313 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000314 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000315 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000316 return true;
317 return false;
318 }
John McCall31168b02011-06-15 23:02:42 +0000319 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000320 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000321 return true;
322 return false;
323 }
324 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000325 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCall31168b02011-06-15 23:02:42 +0000326 return true;
327 return false;
328 }
329
Mike Stump876387b2009-10-27 22:09:17 +0000330 // We don't want to evaluate BlockExprs multiple times, as they generate
331 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000332 bool VisitBlockExpr(const BlockExpr *E) { return true; }
333 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
334 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000335 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000336 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
337 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
338 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
339 bool VisitStringLiteral(const StringLiteral *E) { return false; }
340 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
341 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000342 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000343 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000344 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000345 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith725810a2011-10-16 21:26:27 +0000346 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000347 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
348 bool VisitBinAssign(const BinaryOperator *E) { return true; }
349 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
350 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000351 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000352 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
353 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
354 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
355 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
356 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +0000357 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000358 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000359 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000360 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000361 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000362
363 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000364 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000365 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
366 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000367 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000368 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000369 return false;
370 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000371
Peter Collingbournee9200682011-05-13 03:29:01 +0000372 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000373};
374
John McCallc07a0c72011-02-17 10:25:35 +0000375class OpaqueValueEvaluation {
376 EvalInfo &info;
377 OpaqueValueExpr *opaqueValue;
378
379public:
380 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
381 Expr *value)
382 : info(info), opaqueValue(opaqueValue) {
383
384 // If evaluation fails, fail immediately.
Richard Smith725810a2011-10-16 21:26:27 +0000385 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCallc07a0c72011-02-17 10:25:35 +0000386 this->opaqueValue = 0;
387 return;
388 }
John McCallc07a0c72011-02-17 10:25:35 +0000389 }
390
391 bool hasError() const { return opaqueValue == 0; }
392
393 ~OpaqueValueEvaluation() {
Richard Smith725810a2011-10-16 21:26:27 +0000394 // FIXME: This will not work for recursive constexpr functions using opaque
395 // values. Restore the former value.
John McCallc07a0c72011-02-17 10:25:35 +0000396 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
397 }
398};
399
Mike Stump876387b2009-10-27 22:09:17 +0000400} // end anonymous namespace
401
Eli Friedman9a156e52008-11-12 09:44:48 +0000402//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000403// Generic Evaluation
404//===----------------------------------------------------------------------===//
405namespace {
406
407template <class Derived, typename RetTy=void>
408class ExprEvaluatorBase
409 : public ConstStmtVisitor<Derived, RetTy> {
410private:
411 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
412 return static_cast<Derived*>(this)->Success(V, E);
413 }
414 RetTy DerivedError(const Expr *E) {
415 return static_cast<Derived*>(this)->Error(E);
416 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000417 RetTy DerivedValueInitialization(const Expr *E) {
418 return static_cast<Derived*>(this)->ValueInitialization(E);
419 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000420
421protected:
422 EvalInfo &Info;
423 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
424 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
425
Richard Smith4ce706a2011-10-11 21:43:33 +0000426 RetTy ValueInitialization(const Expr *E) { return DerivedError(E); }
427
Peter Collingbournee9200682011-05-13 03:29:01 +0000428public:
429 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
430
431 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +0000432 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +0000433 }
434 RetTy VisitExpr(const Expr *E) {
435 return DerivedError(E);
436 }
437
438 RetTy VisitParenExpr(const ParenExpr *E)
439 { return StmtVisitorTy::Visit(E->getSubExpr()); }
440 RetTy VisitUnaryExtension(const UnaryOperator *E)
441 { return StmtVisitorTy::Visit(E->getSubExpr()); }
442 RetTy VisitUnaryPlus(const UnaryOperator *E)
443 { return StmtVisitorTy::Visit(E->getSubExpr()); }
444 RetTy VisitChooseExpr(const ChooseExpr *E)
445 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
446 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
447 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000448 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
449 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000450
451 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
452 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
453 if (opaque.hasError())
454 return DerivedError(E);
455
456 bool cond;
457 if (!HandleConversionToBool(E->getCond(), cond, Info))
458 return DerivedError(E);
459
460 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
461 }
462
463 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
464 bool BoolResult;
465 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
466 return DerivedError(E);
467
468 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
469 return StmtVisitorTy::Visit(EvalExpr);
470 }
471
472 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
473 const APValue *value = Info.getOpaqueValue(E);
474 if (!value)
475 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
476 : DerivedError(E));
477 return DerivedSuccess(*value, E);
478 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000479
480 RetTy VisitInitListExpr(const InitListExpr *E) {
481 if (Info.getLangOpts().CPlusPlus0x) {
482 if (E->getNumInits() == 0)
483 return DerivedValueInitialization(E);
484 if (E->getNumInits() == 1)
485 return StmtVisitorTy::Visit(E->getInit(0));
486 }
487 return DerivedError(E);
488 }
489 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
490 return DerivedValueInitialization(E);
491 }
492 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
493 return DerivedValueInitialization(E);
494 }
495
Peter Collingbournee9200682011-05-13 03:29:01 +0000496};
497
498}
499
500//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000501// LValue Evaluation
502//===----------------------------------------------------------------------===//
503namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000504class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000505 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000506 LValue &Result;
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000507 const Decl *PrevDecl;
John McCall45d55e42010-05-07 21:00:08 +0000508
Peter Collingbournee9200682011-05-13 03:29:01 +0000509 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000510 Result.Base = E;
511 Result.Offset = CharUnits::Zero();
512 return true;
513 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000514public:
Mike Stump11289f42009-09-09 15:08:12 +0000515
John McCall45d55e42010-05-07 21:00:08 +0000516 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000517 ExprEvaluatorBaseTy(info), Result(Result), PrevDecl(0) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000518
Peter Collingbournee9200682011-05-13 03:29:01 +0000519 bool Success(const APValue &V, const Expr *E) {
520 Result.setFrom(V);
521 return true;
522 }
523 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000524 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000525 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000526
Peter Collingbournee9200682011-05-13 03:29:01 +0000527 bool VisitDeclRefExpr(const DeclRefExpr *E);
528 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
529 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
530 bool VisitMemberExpr(const MemberExpr *E);
531 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
532 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
533 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
534 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000535
Peter Collingbournee9200682011-05-13 03:29:01 +0000536 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000537 switch (E->getCastKind()) {
538 default:
John McCall45d55e42010-05-07 21:00:08 +0000539 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000540
John McCalle3027922010-08-25 11:45:40 +0000541 case CK_NoOp:
Eli Friedmance3e02a2011-10-11 00:13:24 +0000542 case CK_LValueBitCast:
Anders Carlssonde55f642009-10-03 16:30:22 +0000543 return Visit(E->getSubExpr());
Eli Friedmance3e02a2011-10-11 00:13:24 +0000544
545 // FIXME: Support CK_DerivedToBase and friends.
Anders Carlssonde55f642009-10-03 16:30:22 +0000546 }
547 }
Sebastian Redl12757ab2011-09-24 17:48:14 +0000548
Eli Friedman449fe542009-03-23 04:56:01 +0000549 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000550
Eli Friedman9a156e52008-11-12 09:44:48 +0000551};
552} // end anonymous namespace
553
John McCall45d55e42010-05-07 21:00:08 +0000554static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000555 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000556}
557
Peter Collingbournee9200682011-05-13 03:29:01 +0000558bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000559 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000560 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000561 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000562 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000563 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000564 // Reference parameters can refer to anything even if they have an
565 // "initializer" in the form of a default argument.
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000566 if (!isa<ParmVarDecl>(VD)) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000567 // FIXME: Check whether VD might be overridden!
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000568
569 // Check for recursive initializers of references.
570 if (PrevDecl == VD)
571 return Error(E);
572 PrevDecl = VD;
Peter Collingbournee9200682011-05-13 03:29:01 +0000573 if (const Expr *Init = VD->getAnyInitializer())
574 return Visit(Init);
Chandler Carruth41c6dcc2011-08-22 17:24:56 +0000575 }
Eli Friedman751aa72b72009-05-27 06:04:58 +0000576 }
577
Peter Collingbournee9200682011-05-13 03:29:01 +0000578 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000579}
580
Peter Collingbournee9200682011-05-13 03:29:01 +0000581bool
582LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000583 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000584}
585
Peter Collingbournee9200682011-05-13 03:29:01 +0000586bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000587 QualType Ty;
588 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000589 if (!EvaluatePointer(E->getBase(), Result, Info))
590 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000591 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000592 } else {
John McCall45d55e42010-05-07 21:00:08 +0000593 if (!Visit(E->getBase()))
594 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000595 Ty = E->getBase()->getType();
596 }
597
Peter Collingbournee9200682011-05-13 03:29:01 +0000598 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000599 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000600
Peter Collingbournee9200682011-05-13 03:29:01 +0000601 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000602 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000603 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000604
605 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000606 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000607
Eli Friedmana3c122d2011-07-07 01:54:01 +0000608 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000609 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000610 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000611}
612
Peter Collingbournee9200682011-05-13 03:29:01 +0000613bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000614 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000615 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000616
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000617 APSInt Index;
618 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000619 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000620
Ken Dyck40775002010-01-11 17:06:35 +0000621 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000622 Result.Offset += Index.getSExtValue() * ElementSize;
623 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000624}
Eli Friedman9a156e52008-11-12 09:44:48 +0000625
Peter Collingbournee9200682011-05-13 03:29:01 +0000626bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000627 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000628}
629
Eli Friedman9a156e52008-11-12 09:44:48 +0000630//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000631// Pointer Evaluation
632//===----------------------------------------------------------------------===//
633
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000634namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000635class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000636 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000637 LValue &Result;
638
Peter Collingbournee9200682011-05-13 03:29:01 +0000639 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000640 Result.Base = E;
641 Result.Offset = CharUnits::Zero();
642 return true;
643 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000644public:
Mike Stump11289f42009-09-09 15:08:12 +0000645
John McCall45d55e42010-05-07 21:00:08 +0000646 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000647 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000648
Peter Collingbournee9200682011-05-13 03:29:01 +0000649 bool Success(const APValue &V, const Expr *E) {
650 Result.setFrom(V);
651 return true;
652 }
653 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000654 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000655 }
Richard Smith4ce706a2011-10-11 21:43:33 +0000656 bool ValueInitialization(const Expr *E) {
657 return Success((Expr*)0);
658 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000659
John McCall45d55e42010-05-07 21:00:08 +0000660 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000661 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000662 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000663 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000664 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000665 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000666 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000667 bool VisitCallExpr(const CallExpr *E);
668 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000669 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000670 return Success(E);
671 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000672 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000673 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Richard Smith4ce706a2011-10-11 21:43:33 +0000674 { return ValueInitialization(E); }
John McCallc07a0c72011-02-17 10:25:35 +0000675
Eli Friedman449fe542009-03-23 04:56:01 +0000676 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000677};
Chris Lattner05706e882008-07-11 18:11:29 +0000678} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000679
John McCall45d55e42010-05-07 21:00:08 +0000680static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000681 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000682 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000683}
684
John McCall45d55e42010-05-07 21:00:08 +0000685bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000686 if (E->getOpcode() != BO_Add &&
687 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000688 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000689
Chris Lattner05706e882008-07-11 18:11:29 +0000690 const Expr *PExp = E->getLHS();
691 const Expr *IExp = E->getRHS();
692 if (IExp->getType()->isPointerType())
693 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000694
John McCall45d55e42010-05-07 21:00:08 +0000695 if (!EvaluatePointer(PExp, Result, Info))
696 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000697
John McCall45d55e42010-05-07 21:00:08 +0000698 llvm::APSInt Offset;
699 if (!EvaluateInteger(IExp, Offset, Info))
700 return false;
701 int64_t AdditionalOffset
702 = Offset.isSigned() ? Offset.getSExtValue()
703 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000704
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000705 // Compute the new offset in the appropriate width.
706
707 QualType PointeeType =
708 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000709 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000710
Anders Carlssonef56fba2009-02-19 04:55:58 +0000711 // Explicitly handle GNU void* and function pointer arithmetic extensions.
712 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000713 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000714 else
John McCall45d55e42010-05-07 21:00:08 +0000715 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000716
John McCalle3027922010-08-25 11:45:40 +0000717 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000718 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000719 else
John McCall45d55e42010-05-07 21:00:08 +0000720 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000721
John McCall45d55e42010-05-07 21:00:08 +0000722 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000723}
Eli Friedman9a156e52008-11-12 09:44:48 +0000724
John McCall45d55e42010-05-07 21:00:08 +0000725bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
726 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000727}
Mike Stump11289f42009-09-09 15:08:12 +0000728
Chris Lattner05706e882008-07-11 18:11:29 +0000729
Peter Collingbournee9200682011-05-13 03:29:01 +0000730bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
731 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000732
Eli Friedman847a2bc2009-12-27 05:43:15 +0000733 switch (E->getCastKind()) {
734 default:
735 break;
736
John McCalle3027922010-08-25 11:45:40 +0000737 case CK_NoOp:
738 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +0000739 case CK_CPointerToObjCPointerCast:
740 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +0000741 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000742 return Visit(SubExpr);
743
Anders Carlsson18275092010-10-31 20:41:46 +0000744 case CK_DerivedToBase:
745 case CK_UncheckedDerivedToBase: {
746 LValue BaseLV;
747 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
748 return false;
749
750 // Now figure out the necessary offset to add to the baseLV to get from
751 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000752 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000753
754 QualType Ty = E->getSubExpr()->getType();
755 const CXXRecordDecl *DerivedDecl =
756 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
757
758 for (CastExpr::path_const_iterator PathI = E->path_begin(),
759 PathE = E->path_end(); PathI != PathE; ++PathI) {
760 const CXXBaseSpecifier *Base = *PathI;
761
762 // FIXME: If the base is virtual, we'd need to determine the type of the
763 // most derived class and we don't support that right now.
764 if (Base->isVirtual())
765 return false;
766
767 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
768 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
769
Ken Dyck02155cb2011-01-26 02:17:08 +0000770 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000771 DerivedDecl = BaseDecl;
772 }
773
774 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000775 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000776 return true;
777 }
778
John McCalle84af4e2010-11-13 01:35:44 +0000779 case CK_NullToPointer: {
780 Result.Base = 0;
781 Result.Offset = CharUnits::Zero();
782 return true;
783 }
784
John McCalle3027922010-08-25 11:45:40 +0000785 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000786 APValue Value;
787 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000788 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000789
John McCall45d55e42010-05-07 21:00:08 +0000790 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000791 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000792 Result.Base = 0;
793 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
794 return true;
795 } else {
796 // Cast is of an lvalue, no need to change value.
797 Result.Base = Value.getLValueBase();
798 Result.Offset = Value.getLValueOffset();
799 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000800 }
801 }
John McCalle3027922010-08-25 11:45:40 +0000802 case CK_ArrayToPointerDecay:
803 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000804 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000805 }
806
John McCall45d55e42010-05-07 21:00:08 +0000807 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000808}
Chris Lattner05706e882008-07-11 18:11:29 +0000809
Peter Collingbournee9200682011-05-13 03:29:01 +0000810bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000811 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000812 Builtin::BI__builtin___CFStringMakeConstantString ||
813 E->isBuiltinCall(Info.Ctx) ==
814 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000815 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000816
Peter Collingbournee9200682011-05-13 03:29:01 +0000817 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000818}
Chris Lattner05706e882008-07-11 18:11:29 +0000819
820//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000821// Vector Evaluation
822//===----------------------------------------------------------------------===//
823
824namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000825 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +0000826 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
827 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000828 public:
Mike Stump11289f42009-09-09 15:08:12 +0000829
Richard Smith2d406342011-10-22 21:10:00 +0000830 VectorExprEvaluator(EvalInfo &info, APValue &Result)
831 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +0000832
Richard Smith2d406342011-10-22 21:10:00 +0000833 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
834 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
835 // FIXME: remove this APValue copy.
836 Result = APValue(V.data(), V.size());
837 return true;
838 }
839 bool Success(const APValue &V, const Expr *E) {
840 Result = V;
841 return true;
842 }
843 bool Error(const Expr *E) { return false; }
844 bool ValueInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +0000845
Richard Smith2d406342011-10-22 21:10:00 +0000846 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +0000847 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +0000848 bool VisitCastExpr(const CastExpr* E);
849 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
850 bool VisitInitListExpr(const InitListExpr *E);
851 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000852 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000853 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000854 // shufflevector, ExtVectorElementExpr
855 // (Note that these require implementing conversions
856 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000857 };
858} // end anonymous namespace
859
860static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
861 if (!E->getType()->isVectorType())
862 return false;
Richard Smith2d406342011-10-22 21:10:00 +0000863 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000864}
865
Richard Smith2d406342011-10-22 21:10:00 +0000866bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
867 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000868 QualType EltTy = VTy->getElementType();
869 unsigned NElts = VTy->getNumElements();
870 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000871
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000872 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000873 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000874
Eli Friedmanc757de22011-03-25 00:43:55 +0000875 switch (E->getCastKind()) {
876 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +0000877 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000878 if (SETy->isIntegerType()) {
879 APSInt IntResult;
880 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000881 return Error(E);
882 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +0000883 } else if (SETy->isRealFloatingType()) {
884 APFloat F(0.0);
885 if (!EvaluateFloat(SE, F, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000886 return Error(E);
887 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +0000888 } else {
Richard Smith2d406342011-10-22 21:10:00 +0000889 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +0000890 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000891
892 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +0000893 SmallVector<APValue, 4> Elts(NElts, Val);
894 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +0000895 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000896 case CK_BitCast: {
Richard Smith2d406342011-10-22 21:10:00 +0000897 // FIXME: this is wrong for any cast other than a no-op cast.
Eli Friedmanc757de22011-03-25 00:43:55 +0000898 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000899 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000900
Eli Friedmanc757de22011-03-25 00:43:55 +0000901 if (!SETy->isIntegerType())
Richard Smith2d406342011-10-22 21:10:00 +0000902 return Error(E);
Mike Stump11289f42009-09-09 15:08:12 +0000903
Eli Friedmanc757de22011-03-25 00:43:55 +0000904 APSInt Init;
905 if (!EvaluateInteger(SE, Init, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000906 return Error(E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000907
Eli Friedmanc757de22011-03-25 00:43:55 +0000908 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
909 "Vectors must be composed of ints or floats");
910
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000911 SmallVector<APValue, 4> Elts;
Eli Friedmanc757de22011-03-25 00:43:55 +0000912 for (unsigned i = 0; i != NElts; ++i) {
913 APSInt Tmp = Init.extOrTrunc(EltWidth);
914
915 if (EltTy->isIntegerType())
916 Elts.push_back(APValue(Tmp));
917 else
918 Elts.push_back(APValue(APFloat(Tmp)));
919
920 Init >>= EltWidth;
921 }
Richard Smith2d406342011-10-22 21:10:00 +0000922 return Success(Elts, E);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000923 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000924 case CK_LValueToRValue:
925 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000926 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000927 default:
Richard Smith2d406342011-10-22 21:10:00 +0000928 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +0000929 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000930}
931
Richard Smith2d406342011-10-22 21:10:00 +0000932bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000933VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +0000934 return Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000935}
936
Richard Smith2d406342011-10-22 21:10:00 +0000937bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000938VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +0000939 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000940 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000941 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000942
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000943 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000944 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000945
John McCall875679e2010-06-11 17:54:15 +0000946 // If a vector is initialized with a single element, that value
947 // becomes every element of the vector, not just the first.
948 // This is the behavior described in the IBM AltiVec documentation.
949 if (NumInits == 1) {
Richard Smith2d406342011-10-22 21:10:00 +0000950
951 // Handle the case where the vector is initialized by another
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000952 // vector (OpenCL 6.1.6).
953 if (E->getInit(0)->getType()->isVectorType())
Richard Smith2d406342011-10-22 21:10:00 +0000954 return Visit(E->getInit(0));
955
John McCall875679e2010-06-11 17:54:15 +0000956 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000957 if (EltTy->isIntegerType()) {
958 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000959 if (!EvaluateInteger(E->getInit(0), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000960 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000961 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000962 } else {
963 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000964 if (!EvaluateFloat(E->getInit(0), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000965 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000966 InitValue = APValue(f);
967 }
968 for (unsigned i = 0; i < NumElements; i++) {
969 Elements.push_back(InitValue);
970 }
971 } else {
972 for (unsigned i = 0; i < NumElements; i++) {
973 if (EltTy->isIntegerType()) {
974 llvm::APSInt sInt(32);
975 if (i < NumInits) {
976 if (!EvaluateInteger(E->getInit(i), sInt, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000977 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000978 } else {
979 sInt = Info.Ctx.MakeIntValue(0, EltTy);
980 }
981 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000982 } else {
John McCall875679e2010-06-11 17:54:15 +0000983 llvm::APFloat f(0.0);
984 if (i < NumInits) {
985 if (!EvaluateFloat(E->getInit(i), f, Info))
Richard Smith2d406342011-10-22 21:10:00 +0000986 return Error(E);
John McCall875679e2010-06-11 17:54:15 +0000987 } else {
988 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
989 }
990 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000991 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000992 }
993 }
Richard Smith2d406342011-10-22 21:10:00 +0000994 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000995}
996
Richard Smith2d406342011-10-22 21:10:00 +0000997bool
998VectorExprEvaluator::ValueInitialization(const Expr *E) {
999 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00001000 QualType EltTy = VT->getElementType();
1001 APValue ZeroElement;
1002 if (EltTy->isIntegerType())
1003 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
1004 else
1005 ZeroElement =
1006 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
1007
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001008 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00001009 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001010}
1011
Richard Smith2d406342011-10-22 21:10:00 +00001012bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith725810a2011-10-16 21:26:27 +00001013 APValue Scratch;
1014 if (!Evaluate(Scratch, Info, E->getSubExpr()))
1015 Info.EvalStatus.HasSideEffects = true;
Richard Smith2d406342011-10-22 21:10:00 +00001016 return ValueInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00001017}
1018
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00001019//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001020// Integer Evaluation
1021//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00001022
1023namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001024class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001025 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001026 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001027public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001028 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001029 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00001030
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001031 bool Success(const llvm::APSInt &SI, const Expr *E) {
1032 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001033 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001034 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001035 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001036 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001037 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001038 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001039 return true;
1040 }
1041
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001042 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001043 assert(E->getType()->isIntegralOrEnumerationType() &&
1044 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001045 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001046 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001047 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001048 Result.getInt().setIsUnsigned(
1049 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001050 return true;
1051 }
1052
1053 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001054 assert(E->getType()->isIntegralOrEnumerationType() &&
1055 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001056 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001057 return true;
1058 }
1059
Ken Dyckdbc01912011-03-11 02:13:43 +00001060 bool Success(CharUnits Size, const Expr *E) {
1061 return Success(Size.getQuantity(), E);
1062 }
1063
1064
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001065 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001066 // Take the first error.
Richard Smith725810a2011-10-16 21:26:27 +00001067 if (Info.EvalStatus.Diag == 0) {
1068 Info.EvalStatus.DiagLoc = L;
1069 Info.EvalStatus.Diag = D;
1070 Info.EvalStatus.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001071 }
Chris Lattner99415702008-07-12 00:14:42 +00001072 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +00001073 }
Mike Stump11289f42009-09-09 15:08:12 +00001074
Peter Collingbournee9200682011-05-13 03:29:01 +00001075 bool Success(const APValue &V, const Expr *E) {
1076 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001077 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001078 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001079 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001080 }
Mike Stump11289f42009-09-09 15:08:12 +00001081
Richard Smith4ce706a2011-10-11 21:43:33 +00001082 bool ValueInitialization(const Expr *E) { return Success(0, E); }
1083
Peter Collingbournee9200682011-05-13 03:29:01 +00001084 //===--------------------------------------------------------------------===//
1085 // Visitor Methods
1086 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001087
Chris Lattner7174bf32008-07-12 00:38:25 +00001088 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001089 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001090 }
1091 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001092 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001093 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001094
1095 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1096 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001097 if (CheckReferencedDecl(E, E->getDecl()))
1098 return true;
1099
1100 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001101 }
1102 bool VisitMemberExpr(const MemberExpr *E) {
1103 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1104 // Conservatively assume a MemberExpr will have side-effects
Richard Smith725810a2011-10-16 21:26:27 +00001105 Info.EvalStatus.HasSideEffects = true;
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001106 return true;
1107 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001108
1109 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001110 }
1111
Peter Collingbournee9200682011-05-13 03:29:01 +00001112 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001113 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001114 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001115 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001116
Peter Collingbournee9200682011-05-13 03:29:01 +00001117 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001118 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001119
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001120 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001121 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001122 }
Mike Stump11289f42009-09-09 15:08:12 +00001123
Richard Smith4ce706a2011-10-11 21:43:33 +00001124 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00001125 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00001126 return ValueInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001127 }
1128
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001129 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001130 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001131 }
1132
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001133 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1134 return Success(E->getValue(), E);
1135 }
1136
John Wiegley6242b6a2011-04-28 00:16:57 +00001137 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1138 return Success(E->getValue(), E);
1139 }
1140
John Wiegleyf9f65842011-04-25 06:54:41 +00001141 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1142 return Success(E->getValue(), E);
1143 }
1144
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001145 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001146 bool VisitUnaryImag(const UnaryOperator *E);
1147
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001148 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001149 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00001150
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001151private:
Ken Dyck160146e2010-01-27 17:10:57 +00001152 CharUnits GetAlignOfExpr(const Expr *E);
1153 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001154 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001155 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001156 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001157};
Chris Lattner05706e882008-07-11 18:11:29 +00001158} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001159
Daniel Dunbarce399542009-02-20 18:22:23 +00001160static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001161 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001162 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001163}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001164
Daniel Dunbarce399542009-02-20 18:22:23 +00001165static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001166 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001167
Daniel Dunbarce399542009-02-20 18:22:23 +00001168 APValue Val;
1169 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1170 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001171 Result = Val.getInt();
1172 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001173}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001174
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001175bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001176 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001177 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001178 // Check for signedness/width mismatches between E type and ECD value.
1179 bool SameSign = (ECD->getInitVal().isSigned()
1180 == E->getType()->isSignedIntegerOrEnumerationType());
1181 bool SameWidth = (ECD->getInitVal().getBitWidth()
1182 == Info.Ctx.getIntWidth(E->getType()));
1183 if (SameSign && SameWidth)
1184 return Success(ECD->getInitVal(), E);
1185 else {
1186 // Get rid of mismatch (otherwise Success assertions will fail)
1187 // by computing a new value matching the type of E.
1188 llvm::APSInt Val = ECD->getInitVal();
1189 if (!SameSign)
1190 Val.setIsSigned(!ECD->getInitVal().isSigned());
1191 if (!SameWidth)
1192 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1193 return Success(Val, E);
1194 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001195 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001196
1197 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001198 // In C, they can also be folded, although they are not ICEs.
Richard Smith27908702011-10-24 17:54:18 +00001199 if (IsConstNonVolatile(E->getType())) {
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001200 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Richard Smith27908702011-10-24 17:54:18 +00001201 APValue *V = EvaluateVarDeclInit(Info, VD);
1202 if (V && V->isInt())
1203 return Success(V->getInt(), E);
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001204 }
1205 }
1206
Chris Lattner7174bf32008-07-12 00:38:25 +00001207 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001208 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001209}
1210
Chris Lattner86ee2862008-10-06 06:40:35 +00001211/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1212/// as GCC.
1213static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1214 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001215 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001216 enum gcc_type_class {
1217 no_type_class = -1,
1218 void_type_class, integer_type_class, char_type_class,
1219 enumeral_type_class, boolean_type_class,
1220 pointer_type_class, reference_type_class, offset_type_class,
1221 real_type_class, complex_type_class,
1222 function_type_class, method_type_class,
1223 record_type_class, union_type_class,
1224 array_type_class, string_type_class,
1225 lang_type_class
1226 };
Mike Stump11289f42009-09-09 15:08:12 +00001227
1228 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001229 // ideal, however it is what gcc does.
1230 if (E->getNumArgs() == 0)
1231 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001232
Chris Lattner86ee2862008-10-06 06:40:35 +00001233 QualType ArgTy = E->getArg(0)->getType();
1234 if (ArgTy->isVoidType())
1235 return void_type_class;
1236 else if (ArgTy->isEnumeralType())
1237 return enumeral_type_class;
1238 else if (ArgTy->isBooleanType())
1239 return boolean_type_class;
1240 else if (ArgTy->isCharType())
1241 return string_type_class; // gcc doesn't appear to use char_type_class
1242 else if (ArgTy->isIntegerType())
1243 return integer_type_class;
1244 else if (ArgTy->isPointerType())
1245 return pointer_type_class;
1246 else if (ArgTy->isReferenceType())
1247 return reference_type_class;
1248 else if (ArgTy->isRealType())
1249 return real_type_class;
1250 else if (ArgTy->isComplexType())
1251 return complex_type_class;
1252 else if (ArgTy->isFunctionType())
1253 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001254 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001255 return record_type_class;
1256 else if (ArgTy->isUnionType())
1257 return union_type_class;
1258 else if (ArgTy->isArrayType())
1259 return array_type_class;
1260 else if (ArgTy->isUnionType())
1261 return union_type_class;
1262 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00001263 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00001264 return -1;
1265}
1266
John McCall95007602010-05-10 23:27:23 +00001267/// Retrieves the "underlying object type" of the given expression,
1268/// as used by __builtin_object_size.
1269QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1271 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1272 return VD->getType();
1273 } else if (isa<CompoundLiteralExpr>(E)) {
1274 return E->getType();
1275 }
1276
1277 return QualType();
1278}
1279
Peter Collingbournee9200682011-05-13 03:29:01 +00001280bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001281 // TODO: Perhaps we should let LLVM lower this?
1282 LValue Base;
1283 if (!EvaluatePointer(E->getArg(0), Base, Info))
1284 return false;
1285
1286 // If we can prove the base is null, lower to zero now.
1287 const Expr *LVBase = Base.getLValueBase();
1288 if (!LVBase) return Success(0, E);
1289
1290 QualType T = GetObjectType(LVBase);
1291 if (T.isNull() ||
1292 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001293 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001294 T->isVariablyModifiedType() ||
1295 T->isDependentType())
1296 return false;
1297
1298 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1299 CharUnits Offset = Base.getLValueOffset();
1300
1301 if (!Offset.isNegative() && Offset <= Size)
1302 Size -= Offset;
1303 else
1304 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001305 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001306}
1307
Peter Collingbournee9200682011-05-13 03:29:01 +00001308bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001309 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001310 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001311 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001312
1313 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001314 if (TryEvaluateBuiltinObjectSize(E))
1315 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001316
Eric Christopher99469702010-01-19 22:58:35 +00001317 // If evaluating the argument has side-effects we can't determine
1318 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001319 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00001320 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001321 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001322 return Success(0, E);
1323 }
Mike Stump876387b2009-10-27 22:09:17 +00001324
Mike Stump722cedf2009-10-26 18:35:08 +00001325 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1326 }
1327
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001328 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001329 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001330
Anders Carlsson4c76e932008-11-24 04:21:33 +00001331 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001332 // __builtin_constant_p always has one operand: it returns true if that
1333 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001334 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001335
1336 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00001337 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00001338 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001339 return Success(Operand, E);
1340 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001341
1342 case Builtin::BI__builtin_expect:
1343 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001344
1345 case Builtin::BIstrlen:
1346 case Builtin::BI__builtin_strlen:
1347 // As an extension, we support strlen() and __builtin_strlen() as constant
1348 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001349 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001350 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1351 // The string literal may have embedded null characters. Find the first
1352 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001353 StringRef Str = S->getString();
1354 StringRef::size_type Pos = Str.find(0);
1355 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001356 Str = Str.substr(0, Pos);
1357
1358 return Success(Str.size(), E);
1359 }
1360
1361 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00001362
1363 case Builtin::BI__atomic_is_lock_free: {
1364 APSInt SizeVal;
1365 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
1366 return false;
1367
1368 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
1369 // of two less than the maximum inline atomic width, we know it is
1370 // lock-free. If the size isn't a power of two, or greater than the
1371 // maximum alignment where we promote atomics, we know it is not lock-free
1372 // (at least not in the sense of atomic_is_lock_free). Otherwise,
1373 // the answer can only be determined at runtime; for example, 16-byte
1374 // atomics have lock-free implementations on some, but not all,
1375 // x86-64 processors.
1376
1377 // Check power-of-two.
1378 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
1379 if (!Size.isPowerOfTwo())
1380#if 0
1381 // FIXME: Suppress this folding until the ABI for the promotion width
1382 // settles.
1383 return Success(0, E);
1384#else
1385 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1386#endif
1387
1388#if 0
1389 // Check against promotion width.
1390 // FIXME: Suppress this folding until the ABI for the promotion width
1391 // settles.
1392 unsigned PromoteWidthBits =
1393 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
1394 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
1395 return Success(0, E);
1396#endif
1397
1398 // Check against inlining width.
1399 unsigned InlineWidthBits =
1400 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
1401 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
1402 return Success(1, E);
1403
1404 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1405 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001406 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001407}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001408
Chris Lattnere13042c2008-07-11 19:10:17 +00001409bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001410 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001411 if (!Visit(E->getRHS()))
1412 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001413
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001414 // If we can't evaluate the LHS, it might have side effects;
1415 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00001416 APValue Scratch;
1417 if (!Evaluate(Scratch, Info, E->getLHS()))
1418 Info.EvalStatus.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001419
Anders Carlsson564730a2008-12-01 02:07:06 +00001420 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001421 }
1422
1423 if (E->isLogicalOp()) {
1424 // These need to be handled specially because the operands aren't
1425 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001426 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001427
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001428 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001429 // We were able to evaluate the LHS, see if we can get away with not
1430 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001431 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001432 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001433
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001434 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001435 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001436 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001437 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001438 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001439 }
1440 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001441 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001442 // We can't evaluate the LHS; however, sometimes the result
1443 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001444 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1445 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001446 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001447 // must have had side effects.
Richard Smith725810a2011-10-16 21:26:27 +00001448 Info.EvalStatus.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001449
1450 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001451 }
1452 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001453 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001454
Eli Friedman5a332ea2008-11-13 06:09:17 +00001455 return false;
1456 }
1457
Anders Carlssonacc79812008-11-16 07:17:21 +00001458 QualType LHSTy = E->getLHS()->getType();
1459 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001460
1461 if (LHSTy->isAnyComplexType()) {
1462 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001463 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001464
1465 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1466 return false;
1467
1468 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1469 return false;
1470
1471 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001472 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001473 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001474 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001475 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1476
John McCalle3027922010-08-25 11:45:40 +00001477 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001478 return Success((CR_r == APFloat::cmpEqual &&
1479 CR_i == APFloat::cmpEqual), E);
1480 else {
John McCalle3027922010-08-25 11:45:40 +00001481 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001482 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001483 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001484 CR_r == APFloat::cmpLessThan ||
1485 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001486 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001487 CR_i == APFloat::cmpLessThan ||
1488 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001489 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001490 } else {
John McCalle3027922010-08-25 11:45:40 +00001491 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001492 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1493 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1494 else {
John McCalle3027922010-08-25 11:45:40 +00001495 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001496 "Invalid compex comparison.");
1497 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1498 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1499 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001500 }
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502
Anders Carlssonacc79812008-11-16 07:17:21 +00001503 if (LHSTy->isRealFloatingType() &&
1504 RHSTy->isRealFloatingType()) {
1505 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001506
Anders Carlssonacc79812008-11-16 07:17:21 +00001507 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1508 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001509
Anders Carlssonacc79812008-11-16 07:17:21 +00001510 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1511 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001512
Anders Carlssonacc79812008-11-16 07:17:21 +00001513 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001514
Anders Carlssonacc79812008-11-16 07:17:21 +00001515 switch (E->getOpcode()) {
1516 default:
David Blaikie83d382b2011-09-23 05:06:16 +00001517 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001518 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001519 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001520 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001521 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001522 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001523 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001524 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001525 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001526 E);
John McCalle3027922010-08-25 11:45:40 +00001527 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001528 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001529 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001530 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001531 || CR == APFloat::cmpLessThan
1532 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001533 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Eli Friedmana38da572009-04-28 19:17:36 +00001536 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001537 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001538 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001539 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1540 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001541
John McCall45d55e42010-05-07 21:00:08 +00001542 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001543 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1544 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001545
Eli Friedman334046a2009-06-14 02:17:33 +00001546 // Reject any bases from the normal codepath; we special-case comparisons
1547 // to null.
1548 if (LHSValue.getLValueBase()) {
1549 if (!E->isEqualityOp())
1550 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001551 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001552 return false;
1553 bool bres;
1554 if (!EvalPointerValueAsBool(LHSValue, bres))
1555 return false;
John McCalle3027922010-08-25 11:45:40 +00001556 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001557 } else if (RHSValue.getLValueBase()) {
1558 if (!E->isEqualityOp())
1559 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001560 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001561 return false;
1562 bool bres;
1563 if (!EvalPointerValueAsBool(RHSValue, bres))
1564 return false;
John McCalle3027922010-08-25 11:45:40 +00001565 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001566 }
Eli Friedman64004332009-03-23 04:38:34 +00001567
John McCalle3027922010-08-25 11:45:40 +00001568 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001569 QualType Type = E->getLHS()->getType();
1570 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001571
Ken Dyck02990832010-01-15 12:37:54 +00001572 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001573 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001574 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001575
Ken Dyck02990832010-01-15 12:37:54 +00001576 CharUnits Diff = LHSValue.getLValueOffset() -
1577 RHSValue.getLValueOffset();
1578 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001579 }
1580 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001581 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001582 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001583 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001584 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1585 }
1586 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001587 }
1588 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001589 if (!LHSTy->isIntegralOrEnumerationType() ||
1590 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001591 // We can't continue from here for non-integral types, and they
1592 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001593 return false;
1594 }
1595
Anders Carlsson9c181652008-07-08 14:35:21 +00001596 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001597 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001598 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001599
Eli Friedman94c25c62009-03-24 01:14:50 +00001600 APValue RHSVal;
1601 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001602 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001603
1604 // Handle cases like (unsigned long)&a + 4.
1605 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001606 CharUnits Offset = Result.getLValueOffset();
1607 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1608 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001609 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001610 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001611 else
Ken Dyck02990832010-01-15 12:37:54 +00001612 Offset -= AdditionalOffset;
1613 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001614 return true;
1615 }
1616
1617 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001618 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001619 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001620 CharUnits Offset = RHSVal.getLValueOffset();
1621 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1622 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001623 return true;
1624 }
1625
1626 // All the following cases expect both operands to be an integer
1627 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001628 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001629
Eli Friedman94c25c62009-03-24 01:14:50 +00001630 APSInt& RHS = RHSVal.getInt();
1631
Anders Carlsson9c181652008-07-08 14:35:21 +00001632 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001633 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001634 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001635 case BO_Mul: return Success(Result.getInt() * RHS, E);
1636 case BO_Add: return Success(Result.getInt() + RHS, E);
1637 case BO_Sub: return Success(Result.getInt() - RHS, E);
1638 case BO_And: return Success(Result.getInt() & RHS, E);
1639 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1640 case BO_Or: return Success(Result.getInt() | RHS, E);
1641 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001642 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001643 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001644 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001645 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001646 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001647 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001648 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001649 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001650 // During constant-folding, a negative shift is an opposite shift.
1651 if (RHS.isSigned() && RHS.isNegative()) {
1652 RHS = -RHS;
1653 goto shift_right;
1654 }
1655
1656 shift_left:
1657 unsigned SA
1658 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001659 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001660 }
John McCalle3027922010-08-25 11:45:40 +00001661 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001662 // During constant-folding, a negative shift is an opposite shift.
1663 if (RHS.isSigned() && RHS.isNegative()) {
1664 RHS = -RHS;
1665 goto shift_left;
1666 }
1667
1668 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001669 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001670 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1671 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001672 }
Mike Stump11289f42009-09-09 15:08:12 +00001673
John McCalle3027922010-08-25 11:45:40 +00001674 case BO_LT: return Success(Result.getInt() < RHS, E);
1675 case BO_GT: return Success(Result.getInt() > RHS, E);
1676 case BO_LE: return Success(Result.getInt() <= RHS, E);
1677 case BO_GE: return Success(Result.getInt() >= RHS, E);
1678 case BO_EQ: return Success(Result.getInt() == RHS, E);
1679 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001680 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001681}
1682
Ken Dyck160146e2010-01-27 17:10:57 +00001683CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001684 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1685 // the result is the size of the referenced type."
1686 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1687 // result shall be the alignment of the referenced type."
1688 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1689 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00001690
1691 // __alignof is defined to return the preferred alignment.
1692 return Info.Ctx.toCharUnitsFromBits(
1693 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001694}
1695
Ken Dyck160146e2010-01-27 17:10:57 +00001696CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001697 E = E->IgnoreParens();
1698
1699 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001700 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001701 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001702 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1703 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001704
Chris Lattner68061312009-01-24 21:53:27 +00001705 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001706 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1707 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001708
Chris Lattner24aeeab2009-01-24 21:09:06 +00001709 return GetAlignOfType(E->getType());
1710}
1711
1712
Peter Collingbournee190dee2011-03-11 19:24:49 +00001713/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1714/// a result as the expression's type.
1715bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1716 const UnaryExprOrTypeTraitExpr *E) {
1717 switch(E->getKind()) {
1718 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001719 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001720 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001721 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001722 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001723 }
Eli Friedman64004332009-03-23 04:38:34 +00001724
Peter Collingbournee190dee2011-03-11 19:24:49 +00001725 case UETT_VecStep: {
1726 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001727
Peter Collingbournee190dee2011-03-11 19:24:49 +00001728 if (Ty->isVectorType()) {
1729 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001730
Peter Collingbournee190dee2011-03-11 19:24:49 +00001731 // The vec_step built-in functions that take a 3-component
1732 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1733 if (n == 3)
1734 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001735
Peter Collingbournee190dee2011-03-11 19:24:49 +00001736 return Success(n, E);
1737 } else
1738 return Success(1, E);
1739 }
1740
1741 case UETT_SizeOf: {
1742 QualType SrcTy = E->getTypeOfArgument();
1743 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1744 // the result is the size of the referenced type."
1745 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1746 // result shall be the alignment of the referenced type."
1747 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1748 SrcTy = Ref->getPointeeType();
1749
1750 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1751 // extension.
1752 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1753 return Success(1, E);
1754
1755 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1756 if (!SrcTy->isConstantSizeType())
1757 return false;
1758
1759 // Get information about the size.
1760 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1761 }
1762 }
1763
1764 llvm_unreachable("unknown expr/type trait");
1765 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001766}
1767
Peter Collingbournee9200682011-05-13 03:29:01 +00001768bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001769 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001770 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001771 if (n == 0)
1772 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001773 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001774 for (unsigned i = 0; i != n; ++i) {
1775 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1776 switch (ON.getKind()) {
1777 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001778 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001779 APSInt IdxResult;
1780 if (!EvaluateInteger(Idx, IdxResult, Info))
1781 return false;
1782 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1783 if (!AT)
1784 return false;
1785 CurrentType = AT->getElementType();
1786 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1787 Result += IdxResult.getSExtValue() * ElementSize;
1788 break;
1789 }
1790
1791 case OffsetOfExpr::OffsetOfNode::Field: {
1792 FieldDecl *MemberDecl = ON.getField();
1793 const RecordType *RT = CurrentType->getAs<RecordType>();
1794 if (!RT)
1795 return false;
1796 RecordDecl *RD = RT->getDecl();
1797 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001798 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001799 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001800 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001801 CurrentType = MemberDecl->getType().getNonReferenceType();
1802 break;
1803 }
1804
1805 case OffsetOfExpr::OffsetOfNode::Identifier:
1806 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001807 return false;
1808
1809 case OffsetOfExpr::OffsetOfNode::Base: {
1810 CXXBaseSpecifier *BaseSpec = ON.getBase();
1811 if (BaseSpec->isVirtual())
1812 return false;
1813
1814 // Find the layout of the class whose base we are looking into.
1815 const RecordType *RT = CurrentType->getAs<RecordType>();
1816 if (!RT)
1817 return false;
1818 RecordDecl *RD = RT->getDecl();
1819 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1820
1821 // Find the base class itself.
1822 CurrentType = BaseSpec->getType();
1823 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1824 if (!BaseRT)
1825 return false;
1826
1827 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001828 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001829 break;
1830 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001831 }
1832 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001833 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001834}
1835
Chris Lattnere13042c2008-07-11 19:10:17 +00001836bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001837 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001838 // LNot's operand isn't necessarily an integer, so we handle it specially.
1839 bool bres;
1840 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1841 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001842 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001843 }
1844
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001845 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001846 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001847 return false;
1848
Chris Lattnercdf34e72008-07-11 22:52:41 +00001849 // Get the operand value into 'Result'.
1850 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001851 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001852
Chris Lattnerf09ad162008-07-11 22:15:16 +00001853 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001854 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001855 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1856 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001857 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001858 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001859 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1860 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001861 return true;
John McCalle3027922010-08-25 11:45:40 +00001862 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001863 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001864 return true;
John McCalle3027922010-08-25 11:45:40 +00001865 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001866 if (!Result.isInt()) return false;
1867 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001868 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001869 if (!Result.isInt()) return false;
1870 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001871 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001872}
Mike Stump11289f42009-09-09 15:08:12 +00001873
Chris Lattner477c4be2008-07-12 01:15:53 +00001874/// HandleCast - This is used to evaluate implicit or explicit casts where the
1875/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001876bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1877 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001878 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001879 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001880
Eli Friedmanc757de22011-03-25 00:43:55 +00001881 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001882 case CK_BaseToDerived:
1883 case CK_DerivedToBase:
1884 case CK_UncheckedDerivedToBase:
1885 case CK_Dynamic:
1886 case CK_ToUnion:
1887 case CK_ArrayToPointerDecay:
1888 case CK_FunctionToPointerDecay:
1889 case CK_NullToPointer:
1890 case CK_NullToMemberPointer:
1891 case CK_BaseToDerivedMemberPointer:
1892 case CK_DerivedToBaseMemberPointer:
1893 case CK_ConstructorConversion:
1894 case CK_IntegralToPointer:
1895 case CK_ToVoid:
1896 case CK_VectorSplat:
1897 case CK_IntegralToFloating:
1898 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00001899 case CK_CPointerToObjCPointerCast:
1900 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001901 case CK_AnyPointerToBlockPointerCast:
1902 case CK_ObjCObjectLValueCast:
1903 case CK_FloatingRealToComplex:
1904 case CK_FloatingComplexToReal:
1905 case CK_FloatingComplexCast:
1906 case CK_FloatingComplexToIntegralComplex:
1907 case CK_IntegralRealToComplex:
1908 case CK_IntegralComplexCast:
1909 case CK_IntegralComplexToFloatingComplex:
1910 llvm_unreachable("invalid cast kind for integral value");
1911
Eli Friedman9faf2f92011-03-25 19:07:11 +00001912 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001913 case CK_Dependent:
1914 case CK_GetObjCProperty:
1915 case CK_LValueBitCast:
1916 case CK_UserDefinedConversion:
John McCall2d637d22011-09-10 06:18:15 +00001917 case CK_ARCProduceObject:
1918 case CK_ARCConsumeObject:
1919 case CK_ARCReclaimReturnedObject:
1920 case CK_ARCExtendBlockObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001921 return false;
1922
1923 case CK_LValueToRValue:
1924 case CK_NoOp:
1925 return Visit(E->getSubExpr());
1926
1927 case CK_MemberPointerToBoolean:
1928 case CK_PointerToBoolean:
1929 case CK_IntegralToBoolean:
1930 case CK_FloatingToBoolean:
1931 case CK_FloatingComplexToBoolean:
1932 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001933 bool BoolResult;
1934 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1935 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001936 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001937 }
1938
Eli Friedmanc757de22011-03-25 00:43:55 +00001939 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001940 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001941 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001942
Eli Friedman742421e2009-02-20 01:15:07 +00001943 if (!Result.isInt()) {
1944 // Only allow casts of lvalues if they are lossless.
1945 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1946 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001947
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001948 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001949 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001950 }
Mike Stump11289f42009-09-09 15:08:12 +00001951
Eli Friedmanc757de22011-03-25 00:43:55 +00001952 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001953 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001954 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001955 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001956
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001957 if (LV.getLValueBase()) {
1958 // Only allow based lvalue casts if they are lossless.
1959 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1960 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001961
John McCall45d55e42010-05-07 21:00:08 +00001962 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001963 return true;
1964 }
1965
Ken Dyck02990832010-01-15 12:37:54 +00001966 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1967 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001968 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001969 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001970
Eli Friedmanc757de22011-03-25 00:43:55 +00001971 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001972 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001973 if (!EvaluateComplex(SubExpr, C, Info))
1974 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001975 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001976 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001977
Eli Friedmanc757de22011-03-25 00:43:55 +00001978 case CK_FloatingToIntegral: {
1979 APFloat F(0.0);
1980 if (!EvaluateFloat(SubExpr, F, Info))
1981 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001982
Eli Friedmanc757de22011-03-25 00:43:55 +00001983 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1984 }
1985 }
Mike Stump11289f42009-09-09 15:08:12 +00001986
Eli Friedmanc757de22011-03-25 00:43:55 +00001987 llvm_unreachable("unknown cast resulting in integral value");
1988 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001989}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001990
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001991bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1992 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001993 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001994 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1995 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1996 return Success(LV.getComplexIntReal(), E);
1997 }
1998
1999 return Visit(E->getSubExpr());
2000}
2001
Eli Friedman4e7a2412009-02-27 04:45:43 +00002002bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002003 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00002004 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00002005 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
2006 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
2007 return Success(LV.getComplexIntImag(), E);
2008 }
2009
Richard Smith725810a2011-10-16 21:26:27 +00002010 APValue Scratch;
2011 if (!Evaluate(Scratch, Info, E->getSubExpr()))
2012 Info.EvalStatus.HasSideEffects = true;
Eli Friedman4e7a2412009-02-27 04:45:43 +00002013 return Success(0, E);
2014}
2015
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002016bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
2017 return Success(E->getPackLength(), E);
2018}
2019
Sebastian Redl5f0180d2010-09-10 20:55:47 +00002020bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2021 return Success(E->getValue(), E);
2022}
2023
Chris Lattner05706e882008-07-11 18:11:29 +00002024//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00002025// Float Evaluation
2026//===----------------------------------------------------------------------===//
2027
2028namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002029class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002030 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00002031 APFloat &Result;
2032public:
2033 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002034 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00002035
Peter Collingbournee9200682011-05-13 03:29:01 +00002036 bool Success(const APValue &V, const Expr *e) {
2037 Result = V.getFloat();
2038 return true;
2039 }
2040 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00002041 return false;
2042 }
2043
Richard Smith4ce706a2011-10-11 21:43:33 +00002044 bool ValueInitialization(const Expr *E) {
2045 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2046 return true;
2047 }
2048
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002049 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002050
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002051 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00002052 bool VisitBinaryOperator(const BinaryOperator *E);
2053 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002054 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00002055
John McCallb1fb0d32010-05-07 22:08:54 +00002056 bool VisitUnaryReal(const UnaryOperator *E);
2057 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00002058
John McCalla2fabff2010-10-09 01:34:31 +00002059 bool VisitDeclRefExpr(const DeclRefExpr *E);
2060
John McCallb1fb0d32010-05-07 22:08:54 +00002061 // FIXME: Missing: array subscript of vector, member of vector,
2062 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00002063};
2064} // end anonymous namespace
2065
2066static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002067 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002068 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00002069}
2070
Jay Foad39c79802011-01-12 09:06:06 +00002071static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00002072 QualType ResultTy,
2073 const Expr *Arg,
2074 bool SNaN,
2075 llvm::APFloat &Result) {
2076 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
2077 if (!S) return false;
2078
2079 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
2080
2081 llvm::APInt fill;
2082
2083 // Treat empty strings as if they were zero.
2084 if (S->getString().empty())
2085 fill = llvm::APInt(32, 0);
2086 else if (S->getString().getAsInteger(0, fill))
2087 return false;
2088
2089 if (SNaN)
2090 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
2091 else
2092 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
2093 return true;
2094}
2095
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002096bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00002097 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002098 default:
2099 return ExprEvaluatorBaseTy::VisitCallExpr(E);
2100
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002101 case Builtin::BI__builtin_huge_val:
2102 case Builtin::BI__builtin_huge_valf:
2103 case Builtin::BI__builtin_huge_vall:
2104 case Builtin::BI__builtin_inf:
2105 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002106 case Builtin::BI__builtin_infl: {
2107 const llvm::fltSemantics &Sem =
2108 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002109 Result = llvm::APFloat::getInf(Sem);
2110 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002111 }
Mike Stump11289f42009-09-09 15:08:12 +00002112
John McCall16291492010-02-28 13:00:19 +00002113 case Builtin::BI__builtin_nans:
2114 case Builtin::BI__builtin_nansf:
2115 case Builtin::BI__builtin_nansl:
2116 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2117 true, Result);
2118
Chris Lattner0b7282e2008-10-06 06:31:58 +00002119 case Builtin::BI__builtin_nan:
2120 case Builtin::BI__builtin_nanf:
2121 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002122 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002123 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002124 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2125 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002126
2127 case Builtin::BI__builtin_fabs:
2128 case Builtin::BI__builtin_fabsf:
2129 case Builtin::BI__builtin_fabsl:
2130 if (!EvaluateFloat(E->getArg(0), Result, Info))
2131 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002132
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002133 if (Result.isNegative())
2134 Result.changeSign();
2135 return true;
2136
Mike Stump11289f42009-09-09 15:08:12 +00002137 case Builtin::BI__builtin_copysign:
2138 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002139 case Builtin::BI__builtin_copysignl: {
2140 APFloat RHS(0.);
2141 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2142 !EvaluateFloat(E->getArg(1), RHS, Info))
2143 return false;
2144 Result.copySign(RHS);
2145 return true;
2146 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002147 }
2148}
2149
John McCalla2fabff2010-10-09 01:34:31 +00002150bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002151 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2152 return true;
2153
Richard Smith27908702011-10-24 17:54:18 +00002154 const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl());
2155 if (VD && IsConstNonVolatile(VD->getType())) {
2156 APValue *V = EvaluateVarDeclInit(Info, VD);
2157 if (V && V->isFloat()) {
John McCalla2fabff2010-10-09 01:34:31 +00002158 Result = V->getFloat();
2159 return true;
2160 }
John McCalla2fabff2010-10-09 01:34:31 +00002161 }
John McCalla2fabff2010-10-09 01:34:31 +00002162 return false;
2163}
2164
John McCallb1fb0d32010-05-07 22:08:54 +00002165bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002166 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2167 ComplexValue CV;
2168 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2169 return false;
2170 Result = CV.FloatReal;
2171 return true;
2172 }
2173
2174 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002175}
2176
2177bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002178 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2179 ComplexValue CV;
2180 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2181 return false;
2182 Result = CV.FloatImag;
2183 return true;
2184 }
2185
Richard Smith725810a2011-10-16 21:26:27 +00002186 APValue Scratch;
2187 if (!Evaluate(Scratch, Info, E->getSubExpr()))
2188 Info.EvalStatus.HasSideEffects = true;
Eli Friedman95719532010-08-14 20:52:13 +00002189 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2190 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002191 return true;
2192}
2193
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002194bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002195 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002196 return false;
2197
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002198 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2199 return false;
2200
2201 switch (E->getOpcode()) {
2202 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002203 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002204 return true;
John McCalle3027922010-08-25 11:45:40 +00002205 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002206 Result.changeSign();
2207 return true;
2208 }
2209}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002210
Eli Friedman24c01542008-08-22 00:06:13 +00002211bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002212 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002213 if (!EvaluateFloat(E->getRHS(), Result, Info))
2214 return false;
2215
2216 // If we can't evaluate the LHS, it might have side effects;
2217 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00002218 APValue Scratch;
2219 if (!Evaluate(Scratch, Info, E->getLHS()))
2220 Info.EvalStatus.HasSideEffects = true;
Eli Friedman141fbf32009-11-16 04:25:37 +00002221
2222 return true;
2223 }
2224
Anders Carlssona5df61a2010-10-31 01:21:47 +00002225 // We can't evaluate pointer-to-member operations.
2226 if (E->isPtrMemOp())
2227 return false;
2228
Eli Friedman24c01542008-08-22 00:06:13 +00002229 // FIXME: Diagnostics? I really don't understand how the warnings
2230 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002231 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002232 if (!EvaluateFloat(E->getLHS(), Result, Info))
2233 return false;
2234 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2235 return false;
2236
2237 switch (E->getOpcode()) {
2238 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002239 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002240 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2241 return true;
John McCalle3027922010-08-25 11:45:40 +00002242 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002243 Result.add(RHS, APFloat::rmNearestTiesToEven);
2244 return true;
John McCalle3027922010-08-25 11:45:40 +00002245 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002246 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2247 return true;
John McCalle3027922010-08-25 11:45:40 +00002248 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002249 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2250 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002251 }
2252}
2253
2254bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2255 Result = E->getValue();
2256 return true;
2257}
2258
Peter Collingbournee9200682011-05-13 03:29:01 +00002259bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2260 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002261
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002262 switch (E->getCastKind()) {
2263 default:
2264 return false;
2265
2266 case CK_LValueToRValue:
2267 case CK_NoOp:
2268 return Visit(SubExpr);
2269
2270 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002271 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002272 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002273 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002274 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002275 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002276 return true;
2277 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002278
2279 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002280 if (!Visit(SubExpr))
2281 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002282 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2283 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002284 return true;
2285 }
John McCalld7646252010-11-14 08:17:51 +00002286
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002287 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002288 ComplexValue V;
2289 if (!EvaluateComplex(SubExpr, V, Info))
2290 return false;
2291 Result = V.getComplexFloatReal();
2292 return true;
2293 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002294 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002295
2296 return false;
2297}
2298
Eli Friedman24c01542008-08-22 00:06:13 +00002299//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002300// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002301//===----------------------------------------------------------------------===//
2302
2303namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002304class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002305 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002306 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002307
Anders Carlsson537969c2008-11-16 20:27:53 +00002308public:
John McCall93d91dc2010-05-07 17:22:02 +00002309 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002310 : ExprEvaluatorBaseTy(info), Result(Result) {}
2311
2312 bool Success(const APValue &V, const Expr *e) {
2313 Result.setFrom(V);
2314 return true;
2315 }
2316 bool Error(const Expr *E) {
2317 return false;
2318 }
Mike Stump11289f42009-09-09 15:08:12 +00002319
Anders Carlsson537969c2008-11-16 20:27:53 +00002320 //===--------------------------------------------------------------------===//
2321 // Visitor Methods
2322 //===--------------------------------------------------------------------===//
2323
Peter Collingbournee9200682011-05-13 03:29:01 +00002324 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002325
Peter Collingbournee9200682011-05-13 03:29:01 +00002326 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002327
John McCall93d91dc2010-05-07 17:22:02 +00002328 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002329 bool VisitUnaryOperator(const UnaryOperator *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00002330 // FIXME Missing: ImplicitValueInitExpr, InitListExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002331};
2332} // end anonymous namespace
2333
John McCall93d91dc2010-05-07 17:22:02 +00002334static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2335 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002336 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002337 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002338}
2339
Peter Collingbournee9200682011-05-13 03:29:01 +00002340bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2341 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002342
2343 if (SubExpr->getType()->isRealFloatingType()) {
2344 Result.makeComplexFloat();
2345 APFloat &Imag = Result.FloatImag;
2346 if (!EvaluateFloat(SubExpr, Imag, Info))
2347 return false;
2348
2349 Result.FloatReal = APFloat(Imag.getSemantics());
2350 return true;
2351 } else {
2352 assert(SubExpr->getType()->isIntegerType() &&
2353 "Unexpected imaginary literal.");
2354
2355 Result.makeComplexInt();
2356 APSInt &Imag = Result.IntImag;
2357 if (!EvaluateInteger(SubExpr, Imag, Info))
2358 return false;
2359
2360 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2361 return true;
2362 }
2363}
2364
Peter Collingbournee9200682011-05-13 03:29:01 +00002365bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002366
John McCallfcef3cf2010-12-14 17:51:41 +00002367 switch (E->getCastKind()) {
2368 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002369 case CK_BaseToDerived:
2370 case CK_DerivedToBase:
2371 case CK_UncheckedDerivedToBase:
2372 case CK_Dynamic:
2373 case CK_ToUnion:
2374 case CK_ArrayToPointerDecay:
2375 case CK_FunctionToPointerDecay:
2376 case CK_NullToPointer:
2377 case CK_NullToMemberPointer:
2378 case CK_BaseToDerivedMemberPointer:
2379 case CK_DerivedToBaseMemberPointer:
2380 case CK_MemberPointerToBoolean:
2381 case CK_ConstructorConversion:
2382 case CK_IntegralToPointer:
2383 case CK_PointerToIntegral:
2384 case CK_PointerToBoolean:
2385 case CK_ToVoid:
2386 case CK_VectorSplat:
2387 case CK_IntegralCast:
2388 case CK_IntegralToBoolean:
2389 case CK_IntegralToFloating:
2390 case CK_FloatingToIntegral:
2391 case CK_FloatingToBoolean:
2392 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00002393 case CK_CPointerToObjCPointerCast:
2394 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002395 case CK_AnyPointerToBlockPointerCast:
2396 case CK_ObjCObjectLValueCast:
2397 case CK_FloatingComplexToReal:
2398 case CK_FloatingComplexToBoolean:
2399 case CK_IntegralComplexToReal:
2400 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00002401 case CK_ARCProduceObject:
2402 case CK_ARCConsumeObject:
2403 case CK_ARCReclaimReturnedObject:
2404 case CK_ARCExtendBlockObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002405 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002406
John McCallfcef3cf2010-12-14 17:51:41 +00002407 case CK_LValueToRValue:
2408 case CK_NoOp:
2409 return Visit(E->getSubExpr());
2410
2411 case CK_Dependent:
2412 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002413 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002414 case CK_UserDefinedConversion:
2415 return false;
2416
2417 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002418 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002419 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002420 return false;
2421
John McCallfcef3cf2010-12-14 17:51:41 +00002422 Result.makeComplexFloat();
2423 Result.FloatImag = APFloat(Real.getSemantics());
2424 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002425 }
2426
John McCallfcef3cf2010-12-14 17:51:41 +00002427 case CK_FloatingComplexCast: {
2428 if (!Visit(E->getSubExpr()))
2429 return false;
2430
2431 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2432 QualType From
2433 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2434
2435 Result.FloatReal
2436 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2437 Result.FloatImag
2438 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2439 return true;
2440 }
2441
2442 case CK_FloatingComplexToIntegralComplex: {
2443 if (!Visit(E->getSubExpr()))
2444 return false;
2445
2446 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2447 QualType From
2448 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2449 Result.makeComplexInt();
2450 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2451 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2452 return true;
2453 }
2454
2455 case CK_IntegralRealToComplex: {
2456 APSInt &Real = Result.IntReal;
2457 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2458 return false;
2459
2460 Result.makeComplexInt();
2461 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2462 return true;
2463 }
2464
2465 case CK_IntegralComplexCast: {
2466 if (!Visit(E->getSubExpr()))
2467 return false;
2468
2469 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2470 QualType From
2471 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2472
2473 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2474 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2475 return true;
2476 }
2477
2478 case CK_IntegralComplexToFloatingComplex: {
2479 if (!Visit(E->getSubExpr()))
2480 return false;
2481
2482 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2483 QualType From
2484 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2485 Result.makeComplexFloat();
2486 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2487 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2488 return true;
2489 }
2490 }
2491
2492 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002493 return false;
2494}
2495
John McCall93d91dc2010-05-07 17:22:02 +00002496bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002497 if (E->getOpcode() == BO_Comma) {
2498 if (!Visit(E->getRHS()))
2499 return false;
2500
2501 // If we can't evaluate the LHS, it might have side effects;
2502 // conservatively mark it.
Richard Smith725810a2011-10-16 21:26:27 +00002503 APValue Scratch;
2504 if (!Evaluate(Scratch, Info, E->getLHS()))
2505 Info.EvalStatus.HasSideEffects = true;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002506
2507 return true;
2508 }
John McCall93d91dc2010-05-07 17:22:02 +00002509 if (!Visit(E->getLHS()))
2510 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002511
John McCall93d91dc2010-05-07 17:22:02 +00002512 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002513 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002514 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002515
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002516 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2517 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002518 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002519 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002520 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002521 if (Result.isComplexFloat()) {
2522 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2523 APFloat::rmNearestTiesToEven);
2524 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2525 APFloat::rmNearestTiesToEven);
2526 } else {
2527 Result.getComplexIntReal() += RHS.getComplexIntReal();
2528 Result.getComplexIntImag() += RHS.getComplexIntImag();
2529 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002530 break;
John McCalle3027922010-08-25 11:45:40 +00002531 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002532 if (Result.isComplexFloat()) {
2533 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2534 APFloat::rmNearestTiesToEven);
2535 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2536 APFloat::rmNearestTiesToEven);
2537 } else {
2538 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2539 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2540 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002541 break;
John McCalle3027922010-08-25 11:45:40 +00002542 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002543 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002544 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002545 APFloat &LHS_r = LHS.getComplexFloatReal();
2546 APFloat &LHS_i = LHS.getComplexFloatImag();
2547 APFloat &RHS_r = RHS.getComplexFloatReal();
2548 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002549
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002550 APFloat Tmp = LHS_r;
2551 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2552 Result.getComplexFloatReal() = Tmp;
2553 Tmp = LHS_i;
2554 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2555 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2556
2557 Tmp = LHS_r;
2558 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2559 Result.getComplexFloatImag() = Tmp;
2560 Tmp = LHS_i;
2561 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2562 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2563 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002564 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002565 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002566 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2567 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002568 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002569 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2570 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2571 }
2572 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002573 case BO_Div:
2574 if (Result.isComplexFloat()) {
2575 ComplexValue LHS = Result;
2576 APFloat &LHS_r = LHS.getComplexFloatReal();
2577 APFloat &LHS_i = LHS.getComplexFloatImag();
2578 APFloat &RHS_r = RHS.getComplexFloatReal();
2579 APFloat &RHS_i = RHS.getComplexFloatImag();
2580 APFloat &Res_r = Result.getComplexFloatReal();
2581 APFloat &Res_i = Result.getComplexFloatImag();
2582
2583 APFloat Den = RHS_r;
2584 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2585 APFloat Tmp = RHS_i;
2586 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2587 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2588
2589 Res_r = LHS_r;
2590 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2591 Tmp = LHS_i;
2592 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2593 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2594 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2595
2596 Res_i = LHS_i;
2597 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2598 Tmp = LHS_r;
2599 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2600 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2601 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2602 } else {
2603 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2604 // FIXME: what about diagnostics?
2605 return false;
2606 }
2607 ComplexValue LHS = Result;
2608 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2609 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2610 Result.getComplexIntReal() =
2611 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2612 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2613 Result.getComplexIntImag() =
2614 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2615 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2616 }
2617 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002618 }
2619
John McCall93d91dc2010-05-07 17:22:02 +00002620 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002621}
2622
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002623bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2624 // Get the operand value into 'Result'.
2625 if (!Visit(E->getSubExpr()))
2626 return false;
2627
2628 switch (E->getOpcode()) {
2629 default:
2630 // FIXME: what about diagnostics?
2631 return false;
2632 case UO_Extension:
2633 return true;
2634 case UO_Plus:
2635 // The result is always just the subexpr.
2636 return true;
2637 case UO_Minus:
2638 if (Result.isComplexFloat()) {
2639 Result.getComplexFloatReal().changeSign();
2640 Result.getComplexFloatImag().changeSign();
2641 }
2642 else {
2643 Result.getComplexIntReal() = -Result.getComplexIntReal();
2644 Result.getComplexIntImag() = -Result.getComplexIntImag();
2645 }
2646 return true;
2647 case UO_Not:
2648 if (Result.isComplexFloat())
2649 Result.getComplexFloatImag().changeSign();
2650 else
2651 Result.getComplexIntImag() = -Result.getComplexIntImag();
2652 return true;
2653 }
2654}
2655
Anders Carlsson537969c2008-11-16 20:27:53 +00002656//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002657// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002658//===----------------------------------------------------------------------===//
2659
Richard Smith725810a2011-10-16 21:26:27 +00002660static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002661 if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002662 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002663 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002664 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00002665 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002666 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002667 if (Result.isLValue() &&
2668 !IsGlobalLValue(Result.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002669 return false;
John McCall45d55e42010-05-07 21:00:08 +00002670 } else if (E->getType()->hasPointerRepresentation()) {
2671 LValue LV;
2672 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002673 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002674 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002675 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002676 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00002677 } else if (E->getType()->isRealFloatingType()) {
2678 llvm::APFloat F(0.0);
2679 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002680 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002681
Richard Smith725810a2011-10-16 21:26:27 +00002682 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00002683 } else if (E->getType()->isAnyComplexType()) {
2684 ComplexValue C;
2685 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002686 return false;
Richard Smith725810a2011-10-16 21:26:27 +00002687 C.moveInto(Result);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002688 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002689 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002690
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002691 return true;
2692}
2693
John McCallc07a0c72011-02-17 10:25:35 +00002694/// Evaluate - Return true if this is a constant which we can fold using
2695/// any crazy technique (that has nothing to do with language standards) that
2696/// we want to. If this function returns true, it returns the folded constant
2697/// in Result.
2698bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2699 EvalInfo Info(Ctx, Result);
Richard Smith725810a2011-10-16 21:26:27 +00002700 return ::Evaluate(Result.Val, Info, this);
John McCallc07a0c72011-02-17 10:25:35 +00002701}
2702
Jay Foad39c79802011-01-12 09:06:06 +00002703bool Expr::EvaluateAsBooleanCondition(bool &Result,
2704 const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002705 EvalStatus Scratch;
John McCall1be1c632010-01-05 23:42:56 +00002706 EvalInfo Info(Ctx, Scratch);
2707
2708 return HandleConversionToBool(this, Result, Info);
2709}
2710
Richard Smithcaf33902011-10-10 18:28:20 +00002711bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002712 EvalStatus Scratch;
Richard Smithcaf33902011-10-10 18:28:20 +00002713 EvalInfo Info(Ctx, Scratch);
2714
2715 return EvaluateInteger(this, Result, Info) && !Scratch.HasSideEffects;
2716}
2717
Jay Foad39c79802011-01-12 09:06:06 +00002718bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002719 EvalInfo Info(Ctx, Result);
2720
John McCall45d55e42010-05-07 21:00:08 +00002721 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002722 if (EvaluateLValue(this, LV, Info) &&
2723 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002724 IsGlobalLValue(LV.Base)) {
2725 LV.moveInto(Result.Val);
2726 return true;
2727 }
2728 return false;
2729}
2730
Jay Foad39c79802011-01-12 09:06:06 +00002731bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2732 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002733 EvalInfo Info(Ctx, Result);
2734
2735 LValue LV;
2736 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002737 LV.moveInto(Result.Val);
2738 return true;
2739 }
2740 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002741}
2742
Chris Lattner67d7b922008-11-16 21:24:15 +00002743/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002744/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002745bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002746 EvalResult Result;
2747 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002748}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002749
Jay Foad39c79802011-01-12 09:06:06 +00002750bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith725810a2011-10-16 21:26:27 +00002751 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002752}
2753
Richard Smithcaf33902011-10-10 18:28:20 +00002754APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002755 EvalResult EvalResult;
2756 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002757 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002758 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002759 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002760
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002761 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002762}
John McCall864e3962010-05-07 05:32:02 +00002763
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002764 bool Expr::EvalResult::isGlobalLValue() const {
2765 assert(Val.isLValue());
2766 return IsGlobalLValue(Val.getLValueBase());
2767 }
2768
2769
John McCall864e3962010-05-07 05:32:02 +00002770/// isIntegerConstantExpr - this recursive routine will test if an expression is
2771/// an integer constant expression.
2772
2773/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2774/// comma, etc
2775///
2776/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2777/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2778/// cast+dereference.
2779
2780// CheckICE - This function does the fundamental ICE checking: the returned
2781// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2782// Note that to reduce code duplication, this helper does no evaluation
2783// itself; the caller checks whether the expression is evaluatable, and
2784// in the rare cases where CheckICE actually cares about the evaluated
2785// value, it calls into Evalute.
2786//
2787// Meanings of Val:
2788// 0: This expression is an ICE if it can be evaluated by Evaluate.
2789// 1: This expression is not an ICE, but if it isn't evaluated, it's
2790// a legal subexpression for an ICE. This return value is used to handle
2791// the comma operator in C99 mode.
2792// 2: This expression is not an ICE, and is not a legal subexpression for one.
2793
Dan Gohman28ade552010-07-26 21:25:24 +00002794namespace {
2795
John McCall864e3962010-05-07 05:32:02 +00002796struct ICEDiag {
2797 unsigned Val;
2798 SourceLocation Loc;
2799
2800 public:
2801 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2802 ICEDiag() : Val(0) {}
2803};
2804
Dan Gohman28ade552010-07-26 21:25:24 +00002805}
2806
2807static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002808
2809static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2810 Expr::EvalResult EVResult;
2811 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2812 !EVResult.Val.isInt()) {
2813 return ICEDiag(2, E->getLocStart());
2814 }
2815 return NoDiag();
2816}
2817
2818static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2819 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002820 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002821 return ICEDiag(2, E->getLocStart());
2822 }
2823
2824 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002825#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002826#define STMT(Node, Base) case Expr::Node##Class:
2827#define EXPR(Node, Base)
2828#include "clang/AST/StmtNodes.inc"
2829 case Expr::PredefinedExprClass:
2830 case Expr::FloatingLiteralClass:
2831 case Expr::ImaginaryLiteralClass:
2832 case Expr::StringLiteralClass:
2833 case Expr::ArraySubscriptExprClass:
2834 case Expr::MemberExprClass:
2835 case Expr::CompoundAssignOperatorClass:
2836 case Expr::CompoundLiteralExprClass:
2837 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00002838 case Expr::DesignatedInitExprClass:
2839 case Expr::ImplicitValueInitExprClass:
2840 case Expr::ParenListExprClass:
2841 case Expr::VAArgExprClass:
2842 case Expr::AddrLabelExprClass:
2843 case Expr::StmtExprClass:
2844 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002845 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002846 case Expr::CXXDynamicCastExprClass:
2847 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002848 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002849 case Expr::CXXNullPtrLiteralExprClass:
2850 case Expr::CXXThisExprClass:
2851 case Expr::CXXThrowExprClass:
2852 case Expr::CXXNewExprClass:
2853 case Expr::CXXDeleteExprClass:
2854 case Expr::CXXPseudoDestructorExprClass:
2855 case Expr::UnresolvedLookupExprClass:
2856 case Expr::DependentScopeDeclRefExprClass:
2857 case Expr::CXXConstructExprClass:
2858 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002859 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002860 case Expr::CXXTemporaryObjectExprClass:
2861 case Expr::CXXUnresolvedConstructExprClass:
2862 case Expr::CXXDependentScopeMemberExprClass:
2863 case Expr::UnresolvedMemberExprClass:
2864 case Expr::ObjCStringLiteralClass:
2865 case Expr::ObjCEncodeExprClass:
2866 case Expr::ObjCMessageExprClass:
2867 case Expr::ObjCSelectorExprClass:
2868 case Expr::ObjCProtocolExprClass:
2869 case Expr::ObjCIvarRefExprClass:
2870 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002871 case Expr::ObjCIsaExprClass:
2872 case Expr::ShuffleVectorExprClass:
2873 case Expr::BlockExprClass:
2874 case Expr::BlockDeclRefExprClass:
2875 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002876 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002877 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002878 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002879 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002880 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002881 case Expr::MaterializeTemporaryExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00002882 case Expr::AtomicExprClass:
John McCall864e3962010-05-07 05:32:02 +00002883 return ICEDiag(2, E->getLocStart());
2884
Sebastian Redl12757ab2011-09-24 17:48:14 +00002885 case Expr::InitListExprClass:
2886 if (Ctx.getLangOptions().CPlusPlus0x) {
2887 const InitListExpr *ILE = cast<InitListExpr>(E);
2888 if (ILE->getNumInits() == 0)
2889 return NoDiag();
2890 if (ILE->getNumInits() == 1)
2891 return CheckICE(ILE->getInit(0), Ctx);
2892 // Fall through for more than 1 expression.
2893 }
2894 return ICEDiag(2, E->getLocStart());
2895
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002896 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002897 case Expr::GNUNullExprClass:
2898 // GCC considers the GNU __null value to be an integral constant expression.
2899 return NoDiag();
2900
John McCall7c454bb2011-07-15 05:09:51 +00002901 case Expr::SubstNonTypeTemplateParmExprClass:
2902 return
2903 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2904
John McCall864e3962010-05-07 05:32:02 +00002905 case Expr::ParenExprClass:
2906 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002907 case Expr::GenericSelectionExprClass:
2908 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002909 case Expr::IntegerLiteralClass:
2910 case Expr::CharacterLiteralClass:
2911 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002912 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002913 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002914 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002915 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002916 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002917 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002918 return NoDiag();
2919 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002920 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002921 const CallExpr *CE = cast<CallExpr>(E);
2922 if (CE->isBuiltinCall(Ctx))
2923 return CheckEvalInICE(E, Ctx);
2924 return ICEDiag(2, E->getLocStart());
2925 }
2926 case Expr::DeclRefExprClass:
2927 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2928 return NoDiag();
Richard Smith27908702011-10-24 17:54:18 +00002929 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCall864e3962010-05-07 05:32:02 +00002930 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2931
2932 // Parameter variables are never constants. Without this check,
2933 // getAnyInitializer() can find a default argument, which leads
2934 // to chaos.
2935 if (isa<ParmVarDecl>(D))
2936 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2937
2938 // C++ 7.1.5.1p2
2939 // A variable of non-volatile const-qualified integral or enumeration
2940 // type initialized by an ICE can be used in ICEs.
2941 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
John McCall864e3962010-05-07 05:32:02 +00002942 // Look for a declaration of this variable that has an initializer.
2943 const VarDecl *ID = 0;
2944 const Expr *Init = Dcl->getAnyInitializer(ID);
2945 if (Init) {
2946 if (ID->isInitKnownICE()) {
2947 // We have already checked whether this subexpression is an
2948 // integral constant expression.
2949 if (ID->isInitICE())
2950 return NoDiag();
2951 else
2952 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2953 }
2954
2955 // It's an ICE whether or not the definition we found is
2956 // out-of-line. See DR 721 and the discussion in Clang PR
2957 // 6206 for details.
2958
2959 if (Dcl->isCheckingICE()) {
2960 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2961 }
2962
2963 Dcl->setCheckingICE();
2964 ICEDiag Result = CheckICE(Init, Ctx);
2965 // Cache the result of the ICE test.
2966 Dcl->setInitKnownICE(Result.Val == 0);
2967 return Result;
2968 }
2969 }
2970 }
2971 return ICEDiag(2, E->getLocStart());
2972 case Expr::UnaryOperatorClass: {
2973 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2974 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002975 case UO_PostInc:
2976 case UO_PostDec:
2977 case UO_PreInc:
2978 case UO_PreDec:
2979 case UO_AddrOf:
2980 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002981 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002982 case UO_Extension:
2983 case UO_LNot:
2984 case UO_Plus:
2985 case UO_Minus:
2986 case UO_Not:
2987 case UO_Real:
2988 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00002989 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002990 }
2991
2992 // OffsetOf falls through here.
2993 }
2994 case Expr::OffsetOfExprClass: {
2995 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2996 // Evaluate matches the proposed gcc behavior for cases like
2997 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2998 // compliance: we should warn earlier for offsetof expressions with
2999 // array subscripts that aren't ICEs, and if the array subscripts
3000 // are ICEs, the value of the offsetof must be an integer constant.
3001 return CheckEvalInICE(E, Ctx);
3002 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00003003 case Expr::UnaryExprOrTypeTraitExprClass: {
3004 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
3005 if ((Exp->getKind() == UETT_SizeOf) &&
3006 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00003007 return ICEDiag(2, E->getLocStart());
3008 return NoDiag();
3009 }
3010 case Expr::BinaryOperatorClass: {
3011 const BinaryOperator *Exp = cast<BinaryOperator>(E);
3012 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00003013 case BO_PtrMemD:
3014 case BO_PtrMemI:
3015 case BO_Assign:
3016 case BO_MulAssign:
3017 case BO_DivAssign:
3018 case BO_RemAssign:
3019 case BO_AddAssign:
3020 case BO_SubAssign:
3021 case BO_ShlAssign:
3022 case BO_ShrAssign:
3023 case BO_AndAssign:
3024 case BO_XorAssign:
3025 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00003026 return ICEDiag(2, E->getLocStart());
3027
John McCalle3027922010-08-25 11:45:40 +00003028 case BO_Mul:
3029 case BO_Div:
3030 case BO_Rem:
3031 case BO_Add:
3032 case BO_Sub:
3033 case BO_Shl:
3034 case BO_Shr:
3035 case BO_LT:
3036 case BO_GT:
3037 case BO_LE:
3038 case BO_GE:
3039 case BO_EQ:
3040 case BO_NE:
3041 case BO_And:
3042 case BO_Xor:
3043 case BO_Or:
3044 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00003045 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
3046 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00003047 if (Exp->getOpcode() == BO_Div ||
3048 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00003049 // Evaluate gives an error for undefined Div/Rem, so make sure
3050 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00003051 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smithcaf33902011-10-10 18:28:20 +00003052 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003053 if (REval == 0)
3054 return ICEDiag(1, E->getLocStart());
3055 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00003056 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00003057 if (LEval.isMinSignedValue())
3058 return ICEDiag(1, E->getLocStart());
3059 }
3060 }
3061 }
John McCalle3027922010-08-25 11:45:40 +00003062 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00003063 if (Ctx.getLangOptions().C99) {
3064 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
3065 // if it isn't evaluated.
3066 if (LHSResult.Val == 0 && RHSResult.Val == 0)
3067 return ICEDiag(1, E->getLocStart());
3068 } else {
3069 // In both C89 and C++, commas in ICEs are illegal.
3070 return ICEDiag(2, E->getLocStart());
3071 }
3072 }
3073 if (LHSResult.Val >= RHSResult.Val)
3074 return LHSResult;
3075 return RHSResult;
3076 }
John McCalle3027922010-08-25 11:45:40 +00003077 case BO_LAnd:
3078 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00003079 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003080
3081 // C++0x [expr.const]p2:
3082 // [...] subexpressions of logical AND (5.14), logical OR
3083 // (5.15), and condi- tional (5.16) operations that are not
3084 // evaluated are not considered.
3085 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3086 if (Exp->getOpcode() == BO_LAnd &&
Richard Smithcaf33902011-10-10 18:28:20 +00003087 Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003088 return LHSResult;
3089
3090 if (Exp->getOpcode() == BO_LOr &&
Richard Smithcaf33902011-10-10 18:28:20 +00003091 Exp->getLHS()->EvaluateKnownConstInt(Ctx) != 0)
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003092 return LHSResult;
3093 }
3094
John McCall864e3962010-05-07 05:32:02 +00003095 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3096 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3097 // Rare case where the RHS has a comma "side-effect"; we need
3098 // to actually check the condition to see whether the side
3099 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003100 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00003101 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00003102 return RHSResult;
3103 return NoDiag();
3104 }
3105
3106 if (LHSResult.Val >= RHSResult.Val)
3107 return LHSResult;
3108 return RHSResult;
3109 }
3110 }
3111 }
3112 case Expr::ImplicitCastExprClass:
3113 case Expr::CStyleCastExprClass:
3114 case Expr::CXXFunctionalCastExprClass:
3115 case Expr::CXXStaticCastExprClass:
3116 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003117 case Expr::CXXConstCastExprClass:
3118 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003119 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Eli Friedman76d4e432011-09-29 21:49:34 +00003120 switch (cast<CastExpr>(E)->getCastKind()) {
3121 case CK_LValueToRValue:
3122 case CK_NoOp:
3123 case CK_IntegralToBoolean:
3124 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00003125 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00003126 default:
3127 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3128 return NoDiag();
3129 return ICEDiag(2, E->getLocStart());
3130 }
John McCall864e3962010-05-07 05:32:02 +00003131 }
John McCallc07a0c72011-02-17 10:25:35 +00003132 case Expr::BinaryConditionalOperatorClass: {
3133 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3134 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3135 if (CommonResult.Val == 2) return CommonResult;
3136 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3137 if (FalseResult.Val == 2) return FalseResult;
3138 if (CommonResult.Val == 1) return CommonResult;
3139 if (FalseResult.Val == 1 &&
Richard Smithcaf33902011-10-10 18:28:20 +00003140 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00003141 return FalseResult;
3142 }
John McCall864e3962010-05-07 05:32:02 +00003143 case Expr::ConditionalOperatorClass: {
3144 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3145 // If the condition (ignoring parens) is a __builtin_constant_p call,
3146 // then only the true side is actually considered in an integer constant
3147 // expression, and it is fully evaluated. This is an important GNU
3148 // extension. See GCC PR38377 for discussion.
3149 if (const CallExpr *CallCE
3150 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3151 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3152 Expr::EvalResult EVResult;
3153 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3154 !EVResult.Val.isInt()) {
3155 return ICEDiag(2, E->getLocStart());
3156 }
3157 return NoDiag();
3158 }
3159 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003160 if (CondResult.Val == 2)
3161 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003162
3163 // C++0x [expr.const]p2:
3164 // subexpressions of [...] conditional (5.16) operations that
3165 // are not evaluated are not considered
3166 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
Richard Smithcaf33902011-10-10 18:28:20 +00003167 ? Exp->getCond()->EvaluateKnownConstInt(Ctx) != 0
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003168 : false;
3169 ICEDiag TrueResult = NoDiag();
3170 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3171 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3172 ICEDiag FalseResult = NoDiag();
3173 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3174 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3175
John McCall864e3962010-05-07 05:32:02 +00003176 if (TrueResult.Val == 2)
3177 return TrueResult;
3178 if (FalseResult.Val == 2)
3179 return FalseResult;
3180 if (CondResult.Val == 1)
3181 return CondResult;
3182 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3183 return NoDiag();
3184 // Rare case where the diagnostics depend on which side is evaluated
3185 // Note that if we get here, CondResult is 0, and at least one of
3186 // TrueResult and FalseResult is non-zero.
Richard Smithcaf33902011-10-10 18:28:20 +00003187 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCall864e3962010-05-07 05:32:02 +00003188 return FalseResult;
3189 }
3190 return TrueResult;
3191 }
3192 case Expr::CXXDefaultArgExprClass:
3193 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3194 case Expr::ChooseExprClass: {
3195 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3196 }
3197 }
3198
3199 // Silence a GCC warning
3200 return ICEDiag(2, E->getLocStart());
3201}
3202
3203bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3204 SourceLocation *Loc, bool isEvaluated) const {
3205 ICEDiag d = CheckICE(this, Ctx);
3206 if (d.Val != 0) {
3207 if (Loc) *Loc = d.Loc;
3208 return false;
3209 }
3210 EvalResult EvalResult;
3211 if (!Evaluate(EvalResult, Ctx))
3212 llvm_unreachable("ICE cannot be evaluated!");
3213 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3214 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3215 Result = EvalResult.Val.getInt();
3216 return true;
3217}