blob: 987b02bb8ffbcce405fa20c3c1c05fa215eaa7ed [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/APValue.h"
15#include "clang/AST/ASTContext.h"
Ken Dyck40775002010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner60f36222009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump2346cd22009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlsson7a241ba2008-07-03 04:20:39 +000027using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000030
Chris Lattnercdf34e72008-07-11 22:52:41 +000031/// EvalInfo - This is a private struct used by the evaluator to capture
32/// information about a subexpression as it is folded. It retains information
33/// about the AST context, but also maintains information about the folded
34/// expression.
35///
36/// If an expression could be evaluated, it is still possible it is not a C
37/// "integer constant expression" or constant expression. If not, this struct
38/// captures information about how and why not.
39///
40/// One bit of information passed *into* the request for constant folding
41/// indicates whether the subexpression is "evaluated" or not according to C
42/// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
43/// evaluate the expression regardless of what the RHS is, but C only allows
44/// certain things in certain situations.
John McCall93d91dc2010-05-07 17:22:02 +000045namespace {
Benjamin Kramer024e6192011-03-04 13:12:48 +000046 struct EvalInfo {
47 const ASTContext &Ctx;
48
49 /// EvalResult - Contains information about the evaluation.
50 Expr::EvalResult &EvalResult;
51
52 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
53 MapTy OpaqueValues;
54 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
55 MapTy::const_iterator i = OpaqueValues.find(e);
56 if (i == OpaqueValues.end()) return 0;
57 return &i->second;
58 }
59
60 EvalInfo(const ASTContext &ctx, Expr::EvalResult &evalresult)
61 : Ctx(ctx), EvalResult(evalresult) {}
62 };
63
John McCall93d91dc2010-05-07 17:22:02 +000064 struct ComplexValue {
65 private:
66 bool IsInt;
67
68 public:
69 APSInt IntReal, IntImag;
70 APFloat FloatReal, FloatImag;
71
72 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
73
74 void makeComplexFloat() { IsInt = false; }
75 bool isComplexFloat() const { return !IsInt; }
76 APFloat &getComplexFloatReal() { return FloatReal; }
77 APFloat &getComplexFloatImag() { return FloatImag; }
78
79 void makeComplexInt() { IsInt = true; }
80 bool isComplexInt() const { return IsInt; }
81 APSInt &getComplexIntReal() { return IntReal; }
82 APSInt &getComplexIntImag() { return IntImag; }
83
John McCallc07a0c72011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCallc07a0c72011-02-17 10:25:35 +000090 void setFrom(const APValue &v) {
91 assert(v.isComplexFloat() || v.isComplexInt());
92 if (v.isComplexFloat()) {
93 makeComplexFloat();
94 FloatReal = v.getComplexFloatReal();
95 FloatImag = v.getComplexFloatImag();
96 } else {
97 makeComplexInt();
98 IntReal = v.getComplexIntReal();
99 IntImag = v.getComplexIntImag();
100 }
101 }
John McCall93d91dc2010-05-07 17:22:02 +0000102 };
John McCall45d55e42010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbournee9200682011-05-13 03:29:01 +0000105 const Expr *Base;
John McCall45d55e42010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbournee9200682011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCall45d55e42010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCallc07a0c72011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCall45d55e42010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCallc07a0c72011-02-17 10:25:35 +0000114 void setFrom(const APValue &v) {
115 assert(v.isLValue());
116 Base = v.getLValueBase();
117 Offset = v.getLValueOffset();
118 }
John McCall45d55e42010-05-07 21:00:08 +0000119 };
John McCall93d91dc2010-05-07 17:22:02 +0000120}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000121
John McCallc07a0c72011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCall45d55e42010-05-07 21:00:08 +0000123static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
124static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattner6c4d2552009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall95007602010-05-10 23:27:23 +0000136 if (!E) return true;
137
138 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
139 if (isa<FunctionDecl>(DRE->getDecl()))
140 return true;
141 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
142 return VD->hasGlobalStorage();
143 return false;
144 }
145
146 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(E))
147 return CLE->isFileScope();
148
149 return true;
150}
151
John McCall45d55e42010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000154
John McCalleb3e4f32010-05-07 21:34:32 +0000155 // A null base expression indicates a null pointer. These are always
156 // evaluatable, and they are false unless the offset is zero.
157 if (!Base) {
158 Result = !Value.Offset.isZero();
159 return true;
160 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000161
John McCall95007602010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnaraf8199452010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall95007602010-05-10 23:27:23 +0000164
John McCalleb3e4f32010-05-07 21:34:32 +0000165 // We have a non-null base expression. These are generally known to
166 // be true, but if it'a decl-ref to a weak symbol it can be null at
167 // runtime.
John McCalleb3e4f32010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCalleb3e4f32010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman334046a2009-06-14 02:17:33 +0000181 return true;
182}
183
John McCall1be1c632010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000187 APSInt IntResult;
188 if (!EvaluateInteger(E, IntResult, Info))
189 return false;
190 Result = IntResult != 0;
191 return true;
192 } else if (E->getType()->isRealFloatingType()) {
193 APFloat FloatResult(0.0);
194 if (!EvaluateFloat(E, FloatResult, Info))
195 return false;
196 Result = !FloatResult.isZero();
197 return true;
Eli Friedman64004332009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman9a156e52008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman334046a2009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedman64004332009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedman64004332009-03-23 04:38:34 +0000205 if (!EvaluateComplex(E, ComplexResult, Info))
206 return false;
207 if (ComplexResult.isComplexFloat()) {
208 Result = !ComplexResult.getComplexFloatReal().isZero() ||
209 !ComplexResult.getComplexFloatImag().isZero();
210 } else {
211 Result = ComplexResult.getComplexIntReal().getBoolValue() ||
212 ComplexResult.getComplexIntImag().getBoolValue();
213 }
214 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump11289f42009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +0000225
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000226 // FIXME: Warning for overflow.
227 uint64_t Space[4];
228 bool ignored;
229 (void)Value.convertToInteger(Space, DestWidth, DestSigned,
230 llvm::APFloat::rmTowardZero, &ignored);
231 return APSInt(llvm::APInt(DestWidth, 4, Space), !DestSigned);
232}
233
Mike Stump11289f42009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump11289f42009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump11289f42009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000245 unsigned DestWidth = Ctx.getIntWidth(DestType);
246 APSInt Result = Value;
247 // Figure out if this is a truncate, extend or noop cast.
248 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000251 return Result;
252}
253
Mike Stump11289f42009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad39c79802011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbarb6f953e2009-01-29 06:16:07 +0000256
257 APFloat Result(Ctx.getFloatTypeSemantics(DestType), 1);
258 Result.convertFromAPInt(Value, Value.isSigned(),
259 APFloat::rmNearestTiesToEven);
260 return Result;
261}
262
Mike Stump876387b2009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000264class HasSideEffect
Peter Collingbournee9200682011-05-13 03:29:01 +0000265 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stump876387b2009-10-27 22:09:17 +0000266 EvalInfo &Info;
267public:
268
269 HasSideEffect(EvalInfo &info) : Info(info) {}
270
271 // Unhandled nodes conservatively default to having side effects.
Peter Collingbournee9200682011-05-13 03:29:01 +0000272 bool VisitStmt(const Stmt *S) {
Mike Stump876387b2009-10-27 22:09:17 +0000273 return true;
274 }
275
Peter Collingbournee9200682011-05-13 03:29:01 +0000276 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
277 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbourne91147592011-04-15 00:35:48 +0000278 return Visit(E->getResultExpr());
279 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000280 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
John McCall31168b02011-06-15 23:02:42 +0000285 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
286 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
287 return true;
288 return false;
289 }
290 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
291 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
292 return true;
293 return false;
294 }
295
Mike Stump876387b2009-10-27 22:09:17 +0000296 // We don't want to evaluate BlockExprs multiple times, as they generate
297 // a ton of code.
Peter Collingbournee9200682011-05-13 03:29:01 +0000298 bool VisitBlockExpr(const BlockExpr *E) { return true; }
299 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
300 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000301 { return Visit(E->getInitializer()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000302 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
303 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
304 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
305 bool VisitStringLiteral(const StringLiteral *E) { return false; }
306 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
307 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournee190dee2011-03-11 19:24:49 +0000308 { return false; }
Peter Collingbournee9200682011-05-13 03:29:01 +0000309 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000310 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000311 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stump876387b2009-10-27 22:09:17 +0000312 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000313 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
314 bool VisitBinAssign(const BinaryOperator *E) { return true; }
315 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
316 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stumpfa502902009-10-29 20:48:09 +0000317 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000318 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
319 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
320 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
321 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
322 bool VisitUnaryDeref(const UnaryOperator *E) {
Mike Stump53f9ded2009-11-03 23:25:48 +0000323 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stump876387b2009-10-27 22:09:17 +0000324 return true;
Mike Stumpfa502902009-10-29 20:48:09 +0000325 return Visit(E->getSubExpr());
Mike Stump876387b2009-10-27 22:09:17 +0000326 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000327 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattnera0679422010-04-13 17:34:23 +0000328
329 // Has side effects if any element does.
Peter Collingbournee9200682011-05-13 03:29:01 +0000330 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattnera0679422010-04-13 17:34:23 +0000331 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
332 if (Visit(E->getInit(i))) return true;
Peter Collingbournee9200682011-05-13 03:29:01 +0000333 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidisb2ed28e2011-04-21 00:27:41 +0000334 return Visit(filler);
Chris Lattnera0679422010-04-13 17:34:23 +0000335 return false;
336 }
Douglas Gregor820ba7b2011-01-04 17:33:58 +0000337
Peter Collingbournee9200682011-05-13 03:29:01 +0000338 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stump876387b2009-10-27 22:09:17 +0000339};
340
John McCallc07a0c72011-02-17 10:25:35 +0000341class OpaqueValueEvaluation {
342 EvalInfo &info;
343 OpaqueValueExpr *opaqueValue;
344
345public:
346 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
347 Expr *value)
348 : info(info), opaqueValue(opaqueValue) {
349
350 // If evaluation fails, fail immediately.
351 if (!Evaluate(info, value)) {
352 this->opaqueValue = 0;
353 return;
354 }
355 info.OpaqueValues[opaqueValue] = info.EvalResult.Val;
356 }
357
358 bool hasError() const { return opaqueValue == 0; }
359
360 ~OpaqueValueEvaluation() {
361 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
362 }
363};
364
Mike Stump876387b2009-10-27 22:09:17 +0000365} // end anonymous namespace
366
Eli Friedman9a156e52008-11-12 09:44:48 +0000367//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +0000368// Generic Evaluation
369//===----------------------------------------------------------------------===//
370namespace {
371
372template <class Derived, typename RetTy=void>
373class ExprEvaluatorBase
374 : public ConstStmtVisitor<Derived, RetTy> {
375private:
376 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
377 return static_cast<Derived*>(this)->Success(V, E);
378 }
379 RetTy DerivedError(const Expr *E) {
380 return static_cast<Derived*>(this)->Error(E);
381 }
382
383protected:
384 EvalInfo &Info;
385 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
386 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
387
388public:
389 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
390
391 RetTy VisitStmt(const Stmt *) {
392 assert(0 && "Expression evaluator should not be called on stmts");
393 return DerivedError(0);
394 }
395 RetTy VisitExpr(const Expr *E) {
396 return DerivedError(E);
397 }
398
399 RetTy VisitParenExpr(const ParenExpr *E)
400 { return StmtVisitorTy::Visit(E->getSubExpr()); }
401 RetTy VisitUnaryExtension(const UnaryOperator *E)
402 { return StmtVisitorTy::Visit(E->getSubExpr()); }
403 RetTy VisitUnaryPlus(const UnaryOperator *E)
404 { return StmtVisitorTy::Visit(E->getSubExpr()); }
405 RetTy VisitChooseExpr(const ChooseExpr *E)
406 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
407 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
408 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +0000409 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
410 { return StmtVisitorTy::Visit(E->getReplacement()); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000411
412 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
413 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
414 if (opaque.hasError())
415 return DerivedError(E);
416
417 bool cond;
418 if (!HandleConversionToBool(E->getCond(), cond, Info))
419 return DerivedError(E);
420
421 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
422 }
423
424 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
425 bool BoolResult;
426 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
427 return DerivedError(E);
428
429 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
430 return StmtVisitorTy::Visit(EvalExpr);
431 }
432
433 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
434 const APValue *value = Info.getOpaqueValue(E);
435 if (!value)
436 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
437 : DerivedError(E));
438 return DerivedSuccess(*value, E);
439 }
440};
441
442}
443
444//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000445// LValue Evaluation
446//===----------------------------------------------------------------------===//
447namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000448class LValueExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000449 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000450 LValue &Result;
451
Peter Collingbournee9200682011-05-13 03:29:01 +0000452 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000453 Result.Base = E;
454 Result.Offset = CharUnits::Zero();
455 return true;
456 }
Eli Friedman9a156e52008-11-12 09:44:48 +0000457public:
Mike Stump11289f42009-09-09 15:08:12 +0000458
John McCall45d55e42010-05-07 21:00:08 +0000459 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Peter Collingbournee9200682011-05-13 03:29:01 +0000460 ExprEvaluatorBaseTy(info), Result(Result) {}
Eli Friedman9a156e52008-11-12 09:44:48 +0000461
Peter Collingbournee9200682011-05-13 03:29:01 +0000462 bool Success(const APValue &V, const Expr *E) {
463 Result.setFrom(V);
464 return true;
465 }
466 bool Error(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000467 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000468 }
Douglas Gregor882211c2010-04-28 22:16:22 +0000469
Peter Collingbournee9200682011-05-13 03:29:01 +0000470 bool VisitDeclRefExpr(const DeclRefExpr *E);
471 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
472 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
473 bool VisitMemberExpr(const MemberExpr *E);
474 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
475 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
476 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
477 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +0000478
Peter Collingbournee9200682011-05-13 03:29:01 +0000479 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +0000480 switch (E->getCastKind()) {
481 default:
John McCall45d55e42010-05-07 21:00:08 +0000482 return false;
Anders Carlssonde55f642009-10-03 16:30:22 +0000483
John McCalle3027922010-08-25 11:45:40 +0000484 case CK_NoOp:
Anders Carlssonde55f642009-10-03 16:30:22 +0000485 return Visit(E->getSubExpr());
486 }
487 }
Eli Friedman449fe542009-03-23 04:56:01 +0000488 // FIXME: Missing: __real__, __imag__
Peter Collingbournee9200682011-05-13 03:29:01 +0000489
Eli Friedman9a156e52008-11-12 09:44:48 +0000490};
491} // end anonymous namespace
492
John McCall45d55e42010-05-07 21:00:08 +0000493static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000494 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000495}
496
Peter Collingbournee9200682011-05-13 03:29:01 +0000497bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000498 if (isa<FunctionDecl>(E->getDecl())) {
John McCall45d55e42010-05-07 21:00:08 +0000499 return Success(E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000500 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman751aa72b72009-05-27 06:04:58 +0000501 if (!VD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000502 return Success(E);
Chandler Carruthe299ba62010-05-16 09:32:51 +0000503 // Reference parameters can refer to anything even if they have an
504 // "initializer" in the form of a default argument.
Peter Collingbournee9200682011-05-13 03:29:01 +0000505 if (!isa<ParmVarDecl>(VD))
506 // FIXME: Check whether VD might be overridden!
507 if (const Expr *Init = VD->getAnyInitializer())
508 return Visit(Init);
Eli Friedman751aa72b72009-05-27 06:04:58 +0000509 }
510
Peter Collingbournee9200682011-05-13 03:29:01 +0000511 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlssona42ee442008-11-24 04:41:22 +0000512}
513
Peter Collingbournee9200682011-05-13 03:29:01 +0000514bool
515LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000516 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000517}
518
Peter Collingbournee9200682011-05-13 03:29:01 +0000519bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +0000520 QualType Ty;
521 if (E->isArrow()) {
John McCall45d55e42010-05-07 21:00:08 +0000522 if (!EvaluatePointer(E->getBase(), Result, Info))
523 return false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000524 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman9a156e52008-11-12 09:44:48 +0000525 } else {
John McCall45d55e42010-05-07 21:00:08 +0000526 if (!Visit(E->getBase()))
527 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +0000528 Ty = E->getBase()->getType();
529 }
530
Peter Collingbournee9200682011-05-13 03:29:01 +0000531 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman9a156e52008-11-12 09:44:48 +0000532 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000533
Peter Collingbournee9200682011-05-13 03:29:01 +0000534 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000535 if (!FD) // FIXME: deal with other kinds of member expressions
John McCall45d55e42010-05-07 21:00:08 +0000536 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000537
538 if (FD->getType()->isReferenceType())
John McCall45d55e42010-05-07 21:00:08 +0000539 return false;
Eli Friedmanf7f9f682009-05-30 21:09:44 +0000540
Eli Friedmana3c122d2011-07-07 01:54:01 +0000541 unsigned i = FD->getFieldIndex();
Ken Dyck86a7fcc2011-01-18 01:56:16 +0000542 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCall45d55e42010-05-07 21:00:08 +0000543 return true;
Eli Friedman9a156e52008-11-12 09:44:48 +0000544}
545
Peter Collingbournee9200682011-05-13 03:29:01 +0000546bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000547 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +0000548 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000549
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000550 APSInt Index;
551 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +0000552 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000553
Ken Dyck40775002010-01-11 17:06:35 +0000554 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCall45d55e42010-05-07 21:00:08 +0000555 Result.Offset += Index.getSExtValue() * ElementSize;
556 return true;
Anders Carlsson9f9e4242008-11-16 19:01:22 +0000557}
Eli Friedman9a156e52008-11-12 09:44:48 +0000558
Peter Collingbournee9200682011-05-13 03:29:01 +0000559bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +0000560 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +0000561}
562
Eli Friedman9a156e52008-11-12 09:44:48 +0000563//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000564// Pointer Evaluation
565//===----------------------------------------------------------------------===//
566
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000567namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000568class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000569 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +0000570 LValue &Result;
571
Peter Collingbournee9200682011-05-13 03:29:01 +0000572 bool Success(const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +0000573 Result.Base = E;
574 Result.Offset = CharUnits::Zero();
575 return true;
576 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000577public:
Mike Stump11289f42009-09-09 15:08:12 +0000578
John McCall45d55e42010-05-07 21:00:08 +0000579 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000580 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000581
Peter Collingbournee9200682011-05-13 03:29:01 +0000582 bool Success(const APValue &V, const Expr *E) {
583 Result.setFrom(V);
584 return true;
585 }
586 bool Error(const Stmt *S) {
John McCall45d55e42010-05-07 21:00:08 +0000587 return false;
Anders Carlssonb5ad0212008-07-08 14:30:00 +0000588 }
589
John McCall45d55e42010-05-07 21:00:08 +0000590 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000591 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +0000592 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +0000593 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +0000594 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000595 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000596 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000597 bool VisitCallExpr(const CallExpr *E);
598 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +0000599 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +0000600 return Success(E);
601 return false;
Mike Stumpa6703322009-02-19 22:01:56 +0000602 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000603 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000604 { return Success((Expr*)0); }
Peter Collingbournee9200682011-05-13 03:29:01 +0000605 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCall45d55e42010-05-07 21:00:08 +0000606 { return Success((Expr*)0); }
John McCallc07a0c72011-02-17 10:25:35 +0000607
Eli Friedman449fe542009-03-23 04:56:01 +0000608 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000609};
Chris Lattner05706e882008-07-11 18:11:29 +0000610} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +0000611
John McCall45d55e42010-05-07 21:00:08 +0000612static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +0000613 assert(E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +0000614 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +0000615}
616
John McCall45d55e42010-05-07 21:00:08 +0000617bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +0000618 if (E->getOpcode() != BO_Add &&
619 E->getOpcode() != BO_Sub)
John McCall45d55e42010-05-07 21:00:08 +0000620 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000621
Chris Lattner05706e882008-07-11 18:11:29 +0000622 const Expr *PExp = E->getLHS();
623 const Expr *IExp = E->getRHS();
624 if (IExp->getType()->isPointerType())
625 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +0000626
John McCall45d55e42010-05-07 21:00:08 +0000627 if (!EvaluatePointer(PExp, Result, Info))
628 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000629
John McCall45d55e42010-05-07 21:00:08 +0000630 llvm::APSInt Offset;
631 if (!EvaluateInteger(IExp, Offset, Info))
632 return false;
633 int64_t AdditionalOffset
634 = Offset.isSigned() ? Offset.getSExtValue()
635 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattner05706e882008-07-11 18:11:29 +0000636
Daniel Dunbar4c43e312010-03-20 05:53:45 +0000637 // Compute the new offset in the appropriate width.
638
639 QualType PointeeType =
640 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCall45d55e42010-05-07 21:00:08 +0000641 CharUnits SizeOfPointee;
Mike Stump11289f42009-09-09 15:08:12 +0000642
Anders Carlssonef56fba2009-02-19 04:55:58 +0000643 // Explicitly handle GNU void* and function pointer arithmetic extensions.
644 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCall45d55e42010-05-07 21:00:08 +0000645 SizeOfPointee = CharUnits::One();
Anders Carlssonef56fba2009-02-19 04:55:58 +0000646 else
John McCall45d55e42010-05-07 21:00:08 +0000647 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman9a156e52008-11-12 09:44:48 +0000648
John McCalle3027922010-08-25 11:45:40 +0000649 if (E->getOpcode() == BO_Add)
John McCall45d55e42010-05-07 21:00:08 +0000650 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattner05706e882008-07-11 18:11:29 +0000651 else
John McCall45d55e42010-05-07 21:00:08 +0000652 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman9a156e52008-11-12 09:44:48 +0000653
John McCall45d55e42010-05-07 21:00:08 +0000654 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000655}
Eli Friedman9a156e52008-11-12 09:44:48 +0000656
John McCall45d55e42010-05-07 21:00:08 +0000657bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
658 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000659}
Mike Stump11289f42009-09-09 15:08:12 +0000660
Chris Lattner05706e882008-07-11 18:11:29 +0000661
Peter Collingbournee9200682011-05-13 03:29:01 +0000662bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
663 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +0000664
Eli Friedman847a2bc2009-12-27 05:43:15 +0000665 switch (E->getCastKind()) {
666 default:
667 break;
668
John McCalle3027922010-08-25 11:45:40 +0000669 case CK_NoOp:
670 case CK_BitCast:
John McCalle3027922010-08-25 11:45:40 +0000671 case CK_AnyPointerToObjCPointerCast:
672 case CK_AnyPointerToBlockPointerCast:
Eli Friedman847a2bc2009-12-27 05:43:15 +0000673 return Visit(SubExpr);
674
Anders Carlsson18275092010-10-31 20:41:46 +0000675 case CK_DerivedToBase:
676 case CK_UncheckedDerivedToBase: {
677 LValue BaseLV;
678 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
679 return false;
680
681 // Now figure out the necessary offset to add to the baseLV to get from
682 // the derived class to the base class.
Ken Dyck02155cb2011-01-26 02:17:08 +0000683 CharUnits Offset = CharUnits::Zero();
Anders Carlsson18275092010-10-31 20:41:46 +0000684
685 QualType Ty = E->getSubExpr()->getType();
686 const CXXRecordDecl *DerivedDecl =
687 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
688
689 for (CastExpr::path_const_iterator PathI = E->path_begin(),
690 PathE = E->path_end(); PathI != PathE; ++PathI) {
691 const CXXBaseSpecifier *Base = *PathI;
692
693 // FIXME: If the base is virtual, we'd need to determine the type of the
694 // most derived class and we don't support that right now.
695 if (Base->isVirtual())
696 return false;
697
698 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
699 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
700
Ken Dyck02155cb2011-01-26 02:17:08 +0000701 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson18275092010-10-31 20:41:46 +0000702 DerivedDecl = BaseDecl;
703 }
704
705 Result.Base = BaseLV.getLValueBase();
Ken Dyck02155cb2011-01-26 02:17:08 +0000706 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson18275092010-10-31 20:41:46 +0000707 return true;
708 }
709
John McCalle84af4e2010-11-13 01:35:44 +0000710 case CK_NullToPointer: {
711 Result.Base = 0;
712 Result.Offset = CharUnits::Zero();
713 return true;
714 }
715
John McCalle3027922010-08-25 11:45:40 +0000716 case CK_IntegralToPointer: {
John McCall45d55e42010-05-07 21:00:08 +0000717 APValue Value;
718 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +0000719 break;
Daniel Dunbarce399542009-02-20 18:22:23 +0000720
John McCall45d55e42010-05-07 21:00:08 +0000721 if (Value.isInt()) {
Jay Foad6d4db0c2010-12-07 08:25:34 +0000722 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCall45d55e42010-05-07 21:00:08 +0000723 Result.Base = 0;
724 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
725 return true;
726 } else {
727 // Cast is of an lvalue, no need to change value.
728 Result.Base = Value.getLValueBase();
729 Result.Offset = Value.getLValueOffset();
730 return true;
Chris Lattner05706e882008-07-11 18:11:29 +0000731 }
732 }
John McCalle3027922010-08-25 11:45:40 +0000733 case CK_ArrayToPointerDecay:
734 case CK_FunctionToPointerDecay:
John McCall45d55e42010-05-07 21:00:08 +0000735 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +0000736 }
737
John McCall45d55e42010-05-07 21:00:08 +0000738 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000739}
Chris Lattner05706e882008-07-11 18:11:29 +0000740
Peter Collingbournee9200682011-05-13 03:29:01 +0000741bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump11289f42009-09-09 15:08:12 +0000742 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall481e3a82010-01-23 02:40:42 +0000743 Builtin::BI__builtin___CFStringMakeConstantString ||
744 E->isBuiltinCall(Info.Ctx) ==
745 Builtin::BI__builtin___NSStringMakeConstantString)
John McCall45d55e42010-05-07 21:00:08 +0000746 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +0000747
Peter Collingbournee9200682011-05-13 03:29:01 +0000748 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +0000749}
Chris Lattner05706e882008-07-11 18:11:29 +0000750
751//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000752// Vector Evaluation
753//===----------------------------------------------------------------------===//
754
755namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000756 class VectorExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000757 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman3ae59112009-02-23 04:23:56 +0000758 APValue GetZeroVector(QualType VecType);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000759 public:
Mike Stump11289f42009-09-09 15:08:12 +0000760
Peter Collingbournee9200682011-05-13 03:29:01 +0000761 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump11289f42009-09-09 15:08:12 +0000762
Peter Collingbournee9200682011-05-13 03:29:01 +0000763 APValue Success(const APValue &V, const Expr *E) { return V; }
764 APValue Error(const Expr *E) { return APValue(); }
Mike Stump11289f42009-09-09 15:08:12 +0000765
Eli Friedman3ae59112009-02-23 04:23:56 +0000766 APValue VisitUnaryReal(const UnaryOperator *E)
767 { return Visit(E->getSubExpr()); }
768 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
769 { return GetZeroVector(E->getType()); }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000770 APValue VisitCastExpr(const CastExpr* E);
771 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
772 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman3ae59112009-02-23 04:23:56 +0000773 APValue VisitUnaryImag(const UnaryOperator *E);
774 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +0000775 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +0000776 // shufflevector, ExtVectorElementExpr
777 // (Note that these require implementing conversions
778 // between vector types.)
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000779 };
780} // end anonymous namespace
781
782static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
783 if (!E->getType()->isVectorType())
784 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +0000785 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000786 return !Result.isUninit();
787}
788
789APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall9dd450b2009-09-21 23:43:11 +0000790 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000791 QualType EltTy = VTy->getElementType();
792 unsigned NElts = VTy->getNumElements();
793 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump11289f42009-09-09 15:08:12 +0000794
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000795 const Expr* SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +0000796 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000797
Eli Friedmanc757de22011-03-25 00:43:55 +0000798 switch (E->getCastKind()) {
799 case CK_VectorSplat: {
800 APValue Result = APValue();
801 if (SETy->isIntegerType()) {
802 APSInt IntResult;
803 if (!EvaluateInteger(SE, IntResult, Info))
804 return APValue();
805 Result = APValue(IntResult);
806 } else if (SETy->isRealFloatingType()) {
807 APFloat F(0.0);
808 if (!EvaluateFloat(SE, F, Info))
809 return APValue();
810 Result = APValue(F);
811 } else {
Anders Carlsson6fc22042011-03-25 11:22:47 +0000812 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000813 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000814
815 // Splat and create vector APValue.
816 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
817 return APValue(&Elts[0], Elts.size());
Nate Begeman2ffd3842009-06-26 18:22:18 +0000818 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000819 case CK_BitCast: {
820 if (SETy->isVectorType())
Peter Collingbournee9200682011-05-13 03:29:01 +0000821 return Visit(SE);
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000822
Eli Friedmanc757de22011-03-25 00:43:55 +0000823 if (!SETy->isIntegerType())
Anders Carlsson6fc22042011-03-25 11:22:47 +0000824 return APValue();
Mike Stump11289f42009-09-09 15:08:12 +0000825
Eli Friedmanc757de22011-03-25 00:43:55 +0000826 APSInt Init;
827 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000828 return APValue();
829
Eli Friedmanc757de22011-03-25 00:43:55 +0000830 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
831 "Vectors must be composed of ints or floats");
832
833 llvm::SmallVector<APValue, 4> Elts;
834 for (unsigned i = 0; i != NElts; ++i) {
835 APSInt Tmp = Init.extOrTrunc(EltWidth);
836
837 if (EltTy->isIntegerType())
838 Elts.push_back(APValue(Tmp));
839 else
840 Elts.push_back(APValue(APFloat(Tmp)));
841
842 Init >>= EltWidth;
843 }
844 return APValue(&Elts[0], Elts.size());
Nate Begemanef1a7fa2009-07-01 07:50:47 +0000845 }
Eli Friedmanc757de22011-03-25 00:43:55 +0000846 case CK_LValueToRValue:
847 case CK_NoOp:
Peter Collingbournee9200682011-05-13 03:29:01 +0000848 return Visit(SE);
Eli Friedmanc757de22011-03-25 00:43:55 +0000849 default:
Anders Carlsson6fc22042011-03-25 11:22:47 +0000850 return APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +0000851 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000852}
853
Mike Stump11289f42009-09-09 15:08:12 +0000854APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000855VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +0000856 return this->Visit(E->getInitializer());
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000857}
858
Mike Stump11289f42009-09-09 15:08:12 +0000859APValue
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000860VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall9dd450b2009-09-21 23:43:11 +0000861 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000862 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +0000863 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +0000864
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000865 QualType EltTy = VT->getElementType();
866 llvm::SmallVector<APValue, 4> Elements;
867
John McCall875679e2010-06-11 17:54:15 +0000868 // If a vector is initialized with a single element, that value
869 // becomes every element of the vector, not just the first.
870 // This is the behavior described in the IBM AltiVec documentation.
871 if (NumInits == 1) {
Tanya Lattner5ac257d2011-04-15 22:42:59 +0000872
873 // Handle the case where the vector is initialized by a another
874 // vector (OpenCL 6.1.6).
875 if (E->getInit(0)->getType()->isVectorType())
876 return this->Visit(const_cast<Expr*>(E->getInit(0)));
877
John McCall875679e2010-06-11 17:54:15 +0000878 APValue InitValue;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000879 if (EltTy->isIntegerType()) {
880 llvm::APSInt sInt(32);
John McCall875679e2010-06-11 17:54:15 +0000881 if (!EvaluateInteger(E->getInit(0), sInt, Info))
882 return APValue();
883 InitValue = APValue(sInt);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000884 } else {
885 llvm::APFloat f(0.0);
John McCall875679e2010-06-11 17:54:15 +0000886 if (!EvaluateFloat(E->getInit(0), f, Info))
887 return APValue();
888 InitValue = APValue(f);
889 }
890 for (unsigned i = 0; i < NumElements; i++) {
891 Elements.push_back(InitValue);
892 }
893 } else {
894 for (unsigned i = 0; i < NumElements; i++) {
895 if (EltTy->isIntegerType()) {
896 llvm::APSInt sInt(32);
897 if (i < NumInits) {
898 if (!EvaluateInteger(E->getInit(i), sInt, Info))
899 return APValue();
900 } else {
901 sInt = Info.Ctx.MakeIntValue(0, EltTy);
902 }
903 Elements.push_back(APValue(sInt));
Eli Friedman3ae59112009-02-23 04:23:56 +0000904 } else {
John McCall875679e2010-06-11 17:54:15 +0000905 llvm::APFloat f(0.0);
906 if (i < NumInits) {
907 if (!EvaluateFloat(E->getInit(i), f, Info))
908 return APValue();
909 } else {
910 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
911 }
912 Elements.push_back(APValue(f));
Eli Friedman3ae59112009-02-23 04:23:56 +0000913 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000914 }
915 }
916 return APValue(&Elements[0], Elements.size());
917}
918
Mike Stump11289f42009-09-09 15:08:12 +0000919APValue
Eli Friedman3ae59112009-02-23 04:23:56 +0000920VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall9dd450b2009-09-21 23:43:11 +0000921 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +0000922 QualType EltTy = VT->getElementType();
923 APValue ZeroElement;
924 if (EltTy->isIntegerType())
925 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
926 else
927 ZeroElement =
928 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
929
930 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
931 return APValue(&Elements[0], Elements.size());
932}
933
Eli Friedman3ae59112009-02-23 04:23:56 +0000934APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
935 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
936 Info.EvalResult.HasSideEffects = true;
937 return GetZeroVector(E->getType());
938}
939
Nate Begeman2f2bdeb2009-01-18 03:20:47 +0000940//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000941// Integer Evaluation
942//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +0000943
944namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +0000945class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +0000946 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000947 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +0000948public:
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000949 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +0000950 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +0000951
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000952 bool Success(const llvm::APSInt &SI, const Expr *E) {
953 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +0000954 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000955 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000956 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +0000957 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000958 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000959 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000960 return true;
961 }
962
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000963 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000964 assert(E->getType()->isIntegralOrEnumerationType() &&
965 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000966 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +0000967 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000968 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000969 Result.getInt().setIsUnsigned(
970 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000971 return true;
972 }
973
974 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregorb90df602010-06-16 00:17:44 +0000975 assert(E->getType()->isIntegralOrEnumerationType() &&
976 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +0000977 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +0000978 return true;
979 }
980
Ken Dyckdbc01912011-03-11 02:13:43 +0000981 bool Success(CharUnits Size, const Expr *E) {
982 return Success(Size.getQuantity(), E);
983 }
984
985
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000986 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000987 // Take the first error.
Anders Carlssonbd1df8e2008-11-30 16:38:33 +0000988 if (Info.EvalResult.Diag == 0) {
989 Info.EvalResult.DiagLoc = L;
990 Info.EvalResult.Diag = D;
Anders Carlsson27b8c5c2008-11-30 18:14:57 +0000991 Info.EvalResult.DiagExpr = E;
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000992 }
Chris Lattner99415702008-07-12 00:14:42 +0000993 return false;
Chris Lattnerae8cc152008-07-11 19:24:49 +0000994 }
Mike Stump11289f42009-09-09 15:08:12 +0000995
Peter Collingbournee9200682011-05-13 03:29:01 +0000996 bool Success(const APValue &V, const Expr *E) {
997 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +0000998 }
Peter Collingbournee9200682011-05-13 03:29:01 +0000999 bool Error(const Expr *E) {
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001000 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001001 }
Mike Stump11289f42009-09-09 15:08:12 +00001002
Peter Collingbournee9200682011-05-13 03:29:01 +00001003 //===--------------------------------------------------------------------===//
1004 // Visitor Methods
1005 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00001006
Chris Lattner7174bf32008-07-12 00:38:25 +00001007 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001008 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001009 }
1010 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001011 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00001012 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001013
1014 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1015 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001016 if (CheckReferencedDecl(E, E->getDecl()))
1017 return true;
1018
1019 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001020 }
1021 bool VisitMemberExpr(const MemberExpr *E) {
1022 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1023 // Conservatively assume a MemberExpr will have side-effects
1024 Info.EvalResult.HasSideEffects = true;
1025 return true;
1026 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001027
1028 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001029 }
1030
Peter Collingbournee9200682011-05-13 03:29:01 +00001031 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001032 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00001033 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00001034 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00001035
Peter Collingbournee9200682011-05-13 03:29:01 +00001036 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00001037 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00001038
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001039 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001040 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001041 }
Mike Stump11289f42009-09-09 15:08:12 +00001042
Anders Carlsson39def3a2008-12-21 22:39:40 +00001043 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001044 return Success(0, E);
Anders Carlsson39def3a2008-12-21 22:39:40 +00001045 }
Mike Stump11289f42009-09-09 15:08:12 +00001046
Douglas Gregor747eb782010-07-08 06:14:04 +00001047 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001048 return Success(0, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001049 }
1050
Eli Friedman4e7a2412009-02-27 04:45:43 +00001051 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1052 return Success(0, E);
1053 }
1054
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001055 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00001056 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00001057 }
1058
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00001059 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1060 return Success(E->getValue(), E);
1061 }
1062
John Wiegley6242b6a2011-04-28 00:16:57 +00001063 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1064 return Success(E->getValue(), E);
1065 }
1066
John Wiegleyf9f65842011-04-25 06:54:41 +00001067 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1068 return Success(E->getValue(), E);
1069 }
1070
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001071 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001072 bool VisitUnaryImag(const UnaryOperator *E);
1073
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001074 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001075 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1076
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001077private:
Ken Dyck160146e2010-01-27 17:10:57 +00001078 CharUnits GetAlignOfExpr(const Expr *E);
1079 CharUnits GetAlignOfType(QualType T);
John McCall95007602010-05-10 23:27:23 +00001080 static QualType GetObjectType(const Expr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001081 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00001082 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00001083};
Chris Lattner05706e882008-07-11 18:11:29 +00001084} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001085
Daniel Dunbarce399542009-02-20 18:22:23 +00001086static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001087 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001088 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00001089}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001090
Daniel Dunbarce399542009-02-20 18:22:23 +00001091static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregorb90df602010-06-16 00:17:44 +00001092 assert(E->getType()->isIntegralOrEnumerationType());
John McCallf0c4f352010-05-07 05:46:35 +00001093
Daniel Dunbarce399542009-02-20 18:22:23 +00001094 APValue Val;
1095 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1096 return false;
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001097 Result = Val.getInt();
1098 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001099}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001100
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001101bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001102 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001103 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00001104 // Check for signedness/width mismatches between E type and ECD value.
1105 bool SameSign = (ECD->getInitVal().isSigned()
1106 == E->getType()->isSignedIntegerOrEnumerationType());
1107 bool SameWidth = (ECD->getInitVal().getBitWidth()
1108 == Info.Ctx.getIntWidth(E->getType()));
1109 if (SameSign && SameWidth)
1110 return Success(ECD->getInitVal(), E);
1111 else {
1112 // Get rid of mismatch (otherwise Success assertions will fail)
1113 // by computing a new value matching the type of E.
1114 llvm::APSInt Val = ECD->getInitVal();
1115 if (!SameSign)
1116 Val.setIsSigned(!ECD->getInitVal().isSigned());
1117 if (!SameWidth)
1118 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1119 return Success(Val, E);
1120 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00001121 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001122
1123 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedman29f80c32009-03-30 23:39:01 +00001124 // In C, they can also be folded, although they are not ICEs.
Douglas Gregor0840cc02009-11-01 20:32:48 +00001125 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1126 == Qualifiers::Const) {
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001127
1128 if (isa<ParmVarDecl>(D))
Peter Collingbournee9200682011-05-13 03:29:01 +00001129 return false;
Anders Carlssonb0695ef2010-02-03 21:58:41 +00001130
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00001131 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl5ca79842010-02-01 20:16:42 +00001132 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedman1d6fb162009-12-03 20:31:57 +00001133 if (APValue *V = VD->getEvaluatedValue()) {
1134 if (V->isInt())
1135 return Success(V->getInt(), E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001136 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001137 }
1138
1139 if (VD->isEvaluatingValue())
Peter Collingbournee9200682011-05-13 03:29:01 +00001140 return false;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001141
1142 VD->setEvaluatingValue();
1143
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001144 Expr::EvalResult EResult;
1145 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1146 EResult.Val.isInt()) {
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001147 // Cache the evaluated value in the variable declaration.
Eli Friedman0b1fbd12010-09-06 00:10:32 +00001148 Result = EResult.Val;
Eli Friedman1d6fb162009-12-03 20:31:57 +00001149 VD->setEvaluatedValue(Result);
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001150 return true;
1151 }
1152
Eli Friedman1d6fb162009-12-03 20:31:57 +00001153 VD->setEvaluatedValue(APValue());
Douglas Gregor31cf12c2009-05-26 18:54:04 +00001154 }
Sebastian Redlc9ab3d42009-02-08 15:51:17 +00001155 }
1156 }
1157
Chris Lattner7174bf32008-07-12 00:38:25 +00001158 // Otherwise, random variable references are not constants.
Peter Collingbournee9200682011-05-13 03:29:01 +00001159 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00001160}
1161
Chris Lattner86ee2862008-10-06 06:40:35 +00001162/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1163/// as GCC.
1164static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1165 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00001166 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00001167 enum gcc_type_class {
1168 no_type_class = -1,
1169 void_type_class, integer_type_class, char_type_class,
1170 enumeral_type_class, boolean_type_class,
1171 pointer_type_class, reference_type_class, offset_type_class,
1172 real_type_class, complex_type_class,
1173 function_type_class, method_type_class,
1174 record_type_class, union_type_class,
1175 array_type_class, string_type_class,
1176 lang_type_class
1177 };
Mike Stump11289f42009-09-09 15:08:12 +00001178
1179 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00001180 // ideal, however it is what gcc does.
1181 if (E->getNumArgs() == 0)
1182 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00001183
Chris Lattner86ee2862008-10-06 06:40:35 +00001184 QualType ArgTy = E->getArg(0)->getType();
1185 if (ArgTy->isVoidType())
1186 return void_type_class;
1187 else if (ArgTy->isEnumeralType())
1188 return enumeral_type_class;
1189 else if (ArgTy->isBooleanType())
1190 return boolean_type_class;
1191 else if (ArgTy->isCharType())
1192 return string_type_class; // gcc doesn't appear to use char_type_class
1193 else if (ArgTy->isIntegerType())
1194 return integer_type_class;
1195 else if (ArgTy->isPointerType())
1196 return pointer_type_class;
1197 else if (ArgTy->isReferenceType())
1198 return reference_type_class;
1199 else if (ArgTy->isRealType())
1200 return real_type_class;
1201 else if (ArgTy->isComplexType())
1202 return complex_type_class;
1203 else if (ArgTy->isFunctionType())
1204 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00001205 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00001206 return record_type_class;
1207 else if (ArgTy->isUnionType())
1208 return union_type_class;
1209 else if (ArgTy->isArrayType())
1210 return array_type_class;
1211 else if (ArgTy->isUnionType())
1212 return union_type_class;
1213 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1214 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1215 return -1;
1216}
1217
John McCall95007602010-05-10 23:27:23 +00001218/// Retrieves the "underlying object type" of the given expression,
1219/// as used by __builtin_object_size.
1220QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1221 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1222 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1223 return VD->getType();
1224 } else if (isa<CompoundLiteralExpr>(E)) {
1225 return E->getType();
1226 }
1227
1228 return QualType();
1229}
1230
Peter Collingbournee9200682011-05-13 03:29:01 +00001231bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00001232 // TODO: Perhaps we should let LLVM lower this?
1233 LValue Base;
1234 if (!EvaluatePointer(E->getArg(0), Base, Info))
1235 return false;
1236
1237 // If we can prove the base is null, lower to zero now.
1238 const Expr *LVBase = Base.getLValueBase();
1239 if (!LVBase) return Success(0, E);
1240
1241 QualType T = GetObjectType(LVBase);
1242 if (T.isNull() ||
1243 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00001244 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00001245 T->isVariablyModifiedType() ||
1246 T->isDependentType())
1247 return false;
1248
1249 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1250 CharUnits Offset = Base.getLValueOffset();
1251
1252 if (!Offset.isNegative() && Offset <= Size)
1253 Size -= Offset;
1254 else
1255 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00001256 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00001257}
1258
Peter Collingbournee9200682011-05-13 03:29:01 +00001259bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001260 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001261 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00001262 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00001263
1264 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00001265 if (TryEvaluateBuiltinObjectSize(E))
1266 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00001267
Eric Christopher99469702010-01-19 22:58:35 +00001268 // If evaluating the argument has side-effects we can't determine
1269 // the size of the object and lower it to unknown now.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00001270 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer0128f662010-01-03 18:18:37 +00001271 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00001272 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00001273 return Success(0, E);
1274 }
Mike Stump876387b2009-10-27 22:09:17 +00001275
Mike Stump722cedf2009-10-26 18:35:08 +00001276 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1277 }
1278
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001279 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001280 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00001281
Anders Carlsson4c76e932008-11-24 04:21:33 +00001282 case Builtin::BI__builtin_constant_p:
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001283 // __builtin_constant_p always has one operand: it returns true if that
1284 // operand can be folded, false otherwise.
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001285 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattnerd545ad12009-09-23 06:06:36 +00001286
1287 case Builtin::BI__builtin_eh_return_data_regno: {
1288 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1289 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1290 return Success(Operand, E);
1291 }
Eli Friedmand5c93992010-02-13 00:10:10 +00001292
1293 case Builtin::BI__builtin_expect:
1294 return Visit(E->getArg(0));
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001295
1296 case Builtin::BIstrlen:
1297 case Builtin::BI__builtin_strlen:
1298 // As an extension, we support strlen() and __builtin_strlen() as constant
1299 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00001300 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00001301 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1302 // The string literal may have embedded null characters. Find the first
1303 // one and truncate there.
1304 llvm::StringRef Str = S->getString();
1305 llvm::StringRef::size_type Pos = Str.find(0);
1306 if (Pos != llvm::StringRef::npos)
1307 Str = Str.substr(0, Pos);
1308
1309 return Success(Str.size(), E);
1310 }
1311
1312 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001313 }
Chris Lattner7174bf32008-07-12 00:38:25 +00001314}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00001315
Chris Lattnere13042c2008-07-11 19:10:17 +00001316bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001317 if (E->getOpcode() == BO_Comma) {
Anders Carlsson564730a2008-12-01 02:07:06 +00001318 if (!Visit(E->getRHS()))
1319 return false;
Anders Carlsson5b3638b2008-12-01 06:44:05 +00001320
Eli Friedman9cb9ff42009-02-26 10:19:36 +00001321 // If we can't evaluate the LHS, it might have side effects;
1322 // conservatively mark it.
1323 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1324 Info.EvalResult.HasSideEffects = true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001325
Anders Carlsson564730a2008-12-01 02:07:06 +00001326 return true;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001327 }
1328
1329 if (E->isLogicalOp()) {
1330 // These need to be handled specially because the operands aren't
1331 // necessarily integral
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001332 bool lhsResult, rhsResult;
Mike Stump11289f42009-09-09 15:08:12 +00001333
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001334 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson59689ed2008-11-22 21:04:56 +00001335 // We were able to evaluate the LHS, see if we can get away with not
1336 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCalle3027922010-08-25 11:45:40 +00001337 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001338 return Success(lhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001339
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001340 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCalle3027922010-08-25 11:45:40 +00001341 if (E->getOpcode() == BO_LOr)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001342 return Success(lhsResult || rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001343 else
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001344 return Success(lhsResult && rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001345 }
1346 } else {
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001347 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4c76e932008-11-24 04:21:33 +00001348 // We can't evaluate the LHS; however, sometimes the result
1349 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCalle3027922010-08-25 11:45:40 +00001350 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1351 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001352 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonf50de0c2008-11-30 16:51:17 +00001353 // must have had side effects.
1354 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001355
1356 return Success(rhsResult, E);
Anders Carlsson4c76e932008-11-24 04:21:33 +00001357 }
1358 }
Anders Carlsson59689ed2008-11-22 21:04:56 +00001359 }
Eli Friedman5a332ea2008-11-13 06:09:17 +00001360
Eli Friedman5a332ea2008-11-13 06:09:17 +00001361 return false;
1362 }
1363
Anders Carlssonacc79812008-11-16 07:17:21 +00001364 QualType LHSTy = E->getLHS()->getType();
1365 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001366
1367 if (LHSTy->isAnyComplexType()) {
1368 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00001369 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001370
1371 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1372 return false;
1373
1374 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1375 return false;
1376
1377 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00001378 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001379 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00001380 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001381 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1382
John McCalle3027922010-08-25 11:45:40 +00001383 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001384 return Success((CR_r == APFloat::cmpEqual &&
1385 CR_i == APFloat::cmpEqual), E);
1386 else {
John McCalle3027922010-08-25 11:45:40 +00001387 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001388 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00001389 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001390 CR_r == APFloat::cmpLessThan ||
1391 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00001392 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00001393 CR_i == APFloat::cmpLessThan ||
1394 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001395 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001396 } else {
John McCalle3027922010-08-25 11:45:40 +00001397 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001398 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1399 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1400 else {
John McCalle3027922010-08-25 11:45:40 +00001401 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001402 "Invalid compex comparison.");
1403 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1404 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1405 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00001406 }
1407 }
Mike Stump11289f42009-09-09 15:08:12 +00001408
Anders Carlssonacc79812008-11-16 07:17:21 +00001409 if (LHSTy->isRealFloatingType() &&
1410 RHSTy->isRealFloatingType()) {
1411 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00001412
Anders Carlssonacc79812008-11-16 07:17:21 +00001413 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1414 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001415
Anders Carlssonacc79812008-11-16 07:17:21 +00001416 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1417 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001418
Anders Carlssonacc79812008-11-16 07:17:21 +00001419 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00001420
Anders Carlssonacc79812008-11-16 07:17:21 +00001421 switch (E->getOpcode()) {
1422 default:
1423 assert(0 && "Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00001424 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001425 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00001426 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001427 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00001428 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001429 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001430 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00001431 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001432 E);
John McCalle3027922010-08-25 11:45:40 +00001433 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001434 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00001435 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00001436 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00001437 || CR == APFloat::cmpLessThan
1438 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00001439 }
Anders Carlssonacc79812008-11-16 07:17:21 +00001440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
Eli Friedmana38da572009-04-28 19:17:36 +00001442 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCalle3027922010-08-25 11:45:40 +00001443 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCall45d55e42010-05-07 21:00:08 +00001444 LValue LHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001445 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1446 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001447
John McCall45d55e42010-05-07 21:00:08 +00001448 LValue RHSValue;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001449 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1450 return false;
Eli Friedman64004332009-03-23 04:38:34 +00001451
Eli Friedman334046a2009-06-14 02:17:33 +00001452 // Reject any bases from the normal codepath; we special-case comparisons
1453 // to null.
1454 if (LHSValue.getLValueBase()) {
1455 if (!E->isEqualityOp())
1456 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001457 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001458 return false;
1459 bool bres;
1460 if (!EvalPointerValueAsBool(LHSValue, bres))
1461 return false;
John McCalle3027922010-08-25 11:45:40 +00001462 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001463 } else if (RHSValue.getLValueBase()) {
1464 if (!E->isEqualityOp())
1465 return false;
Ken Dyck02990832010-01-15 12:37:54 +00001466 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman334046a2009-06-14 02:17:33 +00001467 return false;
1468 bool bres;
1469 if (!EvalPointerValueAsBool(RHSValue, bres))
1470 return false;
John McCalle3027922010-08-25 11:45:40 +00001471 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman334046a2009-06-14 02:17:33 +00001472 }
Eli Friedman64004332009-03-23 04:38:34 +00001473
John McCalle3027922010-08-25 11:45:40 +00001474 if (E->getOpcode() == BO_Sub) {
Chris Lattner882bdf22010-04-20 17:13:14 +00001475 QualType Type = E->getLHS()->getType();
1476 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001477
Ken Dyck02990832010-01-15 12:37:54 +00001478 CharUnits ElementSize = CharUnits::One();
Eli Friedmanfa90b152009-06-04 20:23:20 +00001479 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dyck02990832010-01-15 12:37:54 +00001480 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedman64004332009-03-23 04:38:34 +00001481
Ken Dyck02990832010-01-15 12:37:54 +00001482 CharUnits Diff = LHSValue.getLValueOffset() -
1483 RHSValue.getLValueOffset();
1484 return Success(Diff / ElementSize, E);
Eli Friedmana38da572009-04-28 19:17:36 +00001485 }
1486 bool Result;
John McCalle3027922010-08-25 11:45:40 +00001487 if (E->getOpcode() == BO_EQ) {
Eli Friedmana38da572009-04-28 19:17:36 +00001488 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman8b171f62009-04-29 20:29:43 +00001489 } else {
Eli Friedmana38da572009-04-28 19:17:36 +00001490 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1491 }
1492 return Success(Result, E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00001493 }
1494 }
Douglas Gregorb90df602010-06-16 00:17:44 +00001495 if (!LHSTy->isIntegralOrEnumerationType() ||
1496 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001497 // We can't continue from here for non-integral types, and they
1498 // could potentially confuse the following operations.
Eli Friedman5a332ea2008-11-13 06:09:17 +00001499 return false;
1500 }
1501
Anders Carlsson9c181652008-07-08 14:35:21 +00001502 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001503 if (!Visit(E->getLHS()))
Chris Lattner99415702008-07-12 00:14:42 +00001504 return false; // error in subexpression.
Eli Friedmanbd840592008-07-27 05:46:18 +00001505
Eli Friedman94c25c62009-03-24 01:14:50 +00001506 APValue RHSVal;
1507 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001508 return false;
Eli Friedman94c25c62009-03-24 01:14:50 +00001509
1510 // Handle cases like (unsigned long)&a + 4.
1511 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001512 CharUnits Offset = Result.getLValueOffset();
1513 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1514 RHSVal.getInt().getZExtValue());
John McCalle3027922010-08-25 11:45:40 +00001515 if (E->getOpcode() == BO_Add)
Ken Dyck02990832010-01-15 12:37:54 +00001516 Offset += AdditionalOffset;
Eli Friedman94c25c62009-03-24 01:14:50 +00001517 else
Ken Dyck02990832010-01-15 12:37:54 +00001518 Offset -= AdditionalOffset;
1519 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001520 return true;
1521 }
1522
1523 // Handle cases like 4 + (unsigned long)&a
John McCalle3027922010-08-25 11:45:40 +00001524 if (E->getOpcode() == BO_Add &&
Eli Friedman94c25c62009-03-24 01:14:50 +00001525 RHSVal.isLValue() && Result.isInt()) {
Ken Dyck02990832010-01-15 12:37:54 +00001526 CharUnits Offset = RHSVal.getLValueOffset();
1527 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1528 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman94c25c62009-03-24 01:14:50 +00001529 return true;
1530 }
1531
1532 // All the following cases expect both operands to be an integer
1533 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnere13042c2008-07-11 19:10:17 +00001534 return false;
Eli Friedman5a332ea2008-11-13 06:09:17 +00001535
Eli Friedman94c25c62009-03-24 01:14:50 +00001536 APSInt& RHS = RHSVal.getInt();
1537
Anders Carlsson9c181652008-07-08 14:35:21 +00001538 switch (E->getOpcode()) {
Chris Lattnerfac05ae2008-11-12 07:43:42 +00001539 default:
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001540 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001541 case BO_Mul: return Success(Result.getInt() * RHS, E);
1542 case BO_Add: return Success(Result.getInt() + RHS, E);
1543 case BO_Sub: return Success(Result.getInt() - RHS, E);
1544 case BO_And: return Success(Result.getInt() & RHS, E);
1545 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1546 case BO_Or: return Success(Result.getInt() | RHS, E);
1547 case BO_Div:
Chris Lattner99415702008-07-12 00:14:42 +00001548 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001549 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001550 return Success(Result.getInt() / RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001551 case BO_Rem:
Chris Lattner99415702008-07-12 00:14:42 +00001552 if (RHS == 0)
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001553 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001554 return Success(Result.getInt() % RHS, E);
John McCalle3027922010-08-25 11:45:40 +00001555 case BO_Shl: {
John McCall18a2c2c2010-11-09 22:22:12 +00001556 // During constant-folding, a negative shift is an opposite shift.
1557 if (RHS.isSigned() && RHS.isNegative()) {
1558 RHS = -RHS;
1559 goto shift_right;
1560 }
1561
1562 shift_left:
1563 unsigned SA
1564 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001565 return Success(Result.getInt() << SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001566 }
John McCalle3027922010-08-25 11:45:40 +00001567 case BO_Shr: {
John McCall18a2c2c2010-11-09 22:22:12 +00001568 // During constant-folding, a negative shift is an opposite shift.
1569 if (RHS.isSigned() && RHS.isNegative()) {
1570 RHS = -RHS;
1571 goto shift_left;
1572 }
1573
1574 shift_right:
Mike Stump11289f42009-09-09 15:08:12 +00001575 unsigned SA =
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001576 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1577 return Success(Result.getInt() >> SA, E);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001578 }
Mike Stump11289f42009-09-09 15:08:12 +00001579
John McCalle3027922010-08-25 11:45:40 +00001580 case BO_LT: return Success(Result.getInt() < RHS, E);
1581 case BO_GT: return Success(Result.getInt() > RHS, E);
1582 case BO_LE: return Success(Result.getInt() <= RHS, E);
1583 case BO_GE: return Success(Result.getInt() >= RHS, E);
1584 case BO_EQ: return Success(Result.getInt() == RHS, E);
1585 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedman8553a982008-11-13 02:13:11 +00001586 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001587}
1588
Ken Dyck160146e2010-01-27 17:10:57 +00001589CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00001590 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1591 // the result is the size of the referenced type."
1592 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1593 // result shall be the alignment of the referenced type."
1594 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1595 T = Ref->getPointeeType();
1596
Eli Friedmanf7f9f682009-05-30 21:09:44 +00001597 // __alignof is defined to return the preferred alignment.
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001598 return Info.Ctx.toCharUnitsFromBits(
1599 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00001600}
1601
Ken Dyck160146e2010-01-27 17:10:57 +00001602CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00001603 E = E->IgnoreParens();
1604
1605 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00001606 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00001607 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001608 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1609 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00001610
Chris Lattner68061312009-01-24 21:53:27 +00001611 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00001612 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1613 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00001614
Chris Lattner24aeeab2009-01-24 21:09:06 +00001615 return GetAlignOfType(E->getType());
1616}
1617
1618
Peter Collingbournee190dee2011-03-11 19:24:49 +00001619/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1620/// a result as the expression's type.
1621bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1622 const UnaryExprOrTypeTraitExpr *E) {
1623 switch(E->getKind()) {
1624 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00001625 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00001626 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001627 else
Ken Dyckdbc01912011-03-11 02:13:43 +00001628 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00001629 }
Eli Friedman64004332009-03-23 04:38:34 +00001630
Peter Collingbournee190dee2011-03-11 19:24:49 +00001631 case UETT_VecStep: {
1632 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00001633
Peter Collingbournee190dee2011-03-11 19:24:49 +00001634 if (Ty->isVectorType()) {
1635 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00001636
Peter Collingbournee190dee2011-03-11 19:24:49 +00001637 // The vec_step built-in functions that take a 3-component
1638 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1639 if (n == 3)
1640 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00001641
Peter Collingbournee190dee2011-03-11 19:24:49 +00001642 return Success(n, E);
1643 } else
1644 return Success(1, E);
1645 }
1646
1647 case UETT_SizeOf: {
1648 QualType SrcTy = E->getTypeOfArgument();
1649 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1650 // the result is the size of the referenced type."
1651 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1652 // result shall be the alignment of the referenced type."
1653 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1654 SrcTy = Ref->getPointeeType();
1655
1656 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1657 // extension.
1658 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1659 return Success(1, E);
1660
1661 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1662 if (!SrcTy->isConstantSizeType())
1663 return false;
1664
1665 // Get information about the size.
1666 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1667 }
1668 }
1669
1670 llvm_unreachable("unknown expr/type trait");
1671 return false;
Chris Lattnerf8d7f722008-07-11 21:24:13 +00001672}
1673
Peter Collingbournee9200682011-05-13 03:29:01 +00001674bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00001675 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00001676 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00001677 if (n == 0)
1678 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00001679 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00001680 for (unsigned i = 0; i != n; ++i) {
1681 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1682 switch (ON.getKind()) {
1683 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00001684 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00001685 APSInt IdxResult;
1686 if (!EvaluateInteger(Idx, IdxResult, Info))
1687 return false;
1688 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1689 if (!AT)
1690 return false;
1691 CurrentType = AT->getElementType();
1692 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1693 Result += IdxResult.getSExtValue() * ElementSize;
1694 break;
1695 }
1696
1697 case OffsetOfExpr::OffsetOfNode::Field: {
1698 FieldDecl *MemberDecl = ON.getField();
1699 const RecordType *RT = CurrentType->getAs<RecordType>();
1700 if (!RT)
1701 return false;
1702 RecordDecl *RD = RT->getDecl();
1703 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00001704 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00001705 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00001706 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00001707 CurrentType = MemberDecl->getType().getNonReferenceType();
1708 break;
1709 }
1710
1711 case OffsetOfExpr::OffsetOfNode::Identifier:
1712 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregord1702062010-04-29 00:18:15 +00001713 return false;
1714
1715 case OffsetOfExpr::OffsetOfNode::Base: {
1716 CXXBaseSpecifier *BaseSpec = ON.getBase();
1717 if (BaseSpec->isVirtual())
1718 return false;
1719
1720 // Find the layout of the class whose base we are looking into.
1721 const RecordType *RT = CurrentType->getAs<RecordType>();
1722 if (!RT)
1723 return false;
1724 RecordDecl *RD = RT->getDecl();
1725 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1726
1727 // Find the base class itself.
1728 CurrentType = BaseSpec->getType();
1729 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1730 if (!BaseRT)
1731 return false;
1732
1733 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00001734 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00001735 break;
1736 }
Douglas Gregor882211c2010-04-28 22:16:22 +00001737 }
1738 }
Peter Collingbournee9200682011-05-13 03:29:01 +00001739 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00001740}
1741
Chris Lattnere13042c2008-07-11 19:10:17 +00001742bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00001743 if (E->getOpcode() == UO_LNot) {
Eli Friedman5a332ea2008-11-13 06:09:17 +00001744 // LNot's operand isn't necessarily an integer, so we handle it specially.
1745 bool bres;
1746 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1747 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001748 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00001749 }
1750
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001751 // Only handle integral operations...
Douglas Gregorb90df602010-06-16 00:17:44 +00001752 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar79e042a2009-02-21 18:14:20 +00001753 return false;
1754
Chris Lattnercdf34e72008-07-11 22:52:41 +00001755 // Get the operand value into 'Result'.
1756 if (!Visit(E->getSubExpr()))
Chris Lattnerf09ad162008-07-11 22:15:16 +00001757 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001758
Chris Lattnerf09ad162008-07-11 22:15:16 +00001759 switch (E->getOpcode()) {
Chris Lattner7174bf32008-07-12 00:38:25 +00001760 default:
Chris Lattnerf09ad162008-07-11 22:15:16 +00001761 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1762 // See C99 6.6p3.
Anders Carlssonb33d6c82008-11-30 18:37:00 +00001763 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCalle3027922010-08-25 11:45:40 +00001764 case UO_Extension:
Chris Lattner7174bf32008-07-12 00:38:25 +00001765 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1766 // If so, we could clear the diagnostic ID.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001767 return true;
John McCalle3027922010-08-25 11:45:40 +00001768 case UO_Plus:
Mike Stump11289f42009-09-09 15:08:12 +00001769 // The result is always just the subexpr.
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00001770 return true;
John McCalle3027922010-08-25 11:45:40 +00001771 case UO_Minus:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001772 if (!Result.isInt()) return false;
1773 return Success(-Result.getInt(), E);
John McCalle3027922010-08-25 11:45:40 +00001774 case UO_Not:
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001775 if (!Result.isInt()) return false;
1776 return Success(~Result.getInt(), E);
Anders Carlsson9c181652008-07-08 14:35:21 +00001777 }
Anders Carlsson9c181652008-07-08 14:35:21 +00001778}
Mike Stump11289f42009-09-09 15:08:12 +00001779
Chris Lattner477c4be2008-07-12 01:15:53 +00001780/// HandleCast - This is used to evaluate implicit or explicit casts where the
1781/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00001782bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1783 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001784 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00001785 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00001786
Eli Friedmanc757de22011-03-25 00:43:55 +00001787 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00001788 case CK_BaseToDerived:
1789 case CK_DerivedToBase:
1790 case CK_UncheckedDerivedToBase:
1791 case CK_Dynamic:
1792 case CK_ToUnion:
1793 case CK_ArrayToPointerDecay:
1794 case CK_FunctionToPointerDecay:
1795 case CK_NullToPointer:
1796 case CK_NullToMemberPointer:
1797 case CK_BaseToDerivedMemberPointer:
1798 case CK_DerivedToBaseMemberPointer:
1799 case CK_ConstructorConversion:
1800 case CK_IntegralToPointer:
1801 case CK_ToVoid:
1802 case CK_VectorSplat:
1803 case CK_IntegralToFloating:
1804 case CK_FloatingCast:
1805 case CK_AnyPointerToObjCPointerCast:
1806 case CK_AnyPointerToBlockPointerCast:
1807 case CK_ObjCObjectLValueCast:
1808 case CK_FloatingRealToComplex:
1809 case CK_FloatingComplexToReal:
1810 case CK_FloatingComplexCast:
1811 case CK_FloatingComplexToIntegralComplex:
1812 case CK_IntegralRealToComplex:
1813 case CK_IntegralComplexCast:
1814 case CK_IntegralComplexToFloatingComplex:
1815 llvm_unreachable("invalid cast kind for integral value");
1816
Eli Friedman9faf2f92011-03-25 19:07:11 +00001817 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00001818 case CK_Dependent:
1819 case CK_GetObjCProperty:
1820 case CK_LValueBitCast:
1821 case CK_UserDefinedConversion:
John McCall31168b02011-06-15 23:02:42 +00001822 case CK_ObjCProduceObject:
1823 case CK_ObjCConsumeObject:
John McCall4db5c3c2011-07-07 06:58:02 +00001824 case CK_ObjCReclaimReturnedObject:
Eli Friedmanc757de22011-03-25 00:43:55 +00001825 return false;
1826
1827 case CK_LValueToRValue:
1828 case CK_NoOp:
1829 return Visit(E->getSubExpr());
1830
1831 case CK_MemberPointerToBoolean:
1832 case CK_PointerToBoolean:
1833 case CK_IntegralToBoolean:
1834 case CK_FloatingToBoolean:
1835 case CK_FloatingComplexToBoolean:
1836 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00001837 bool BoolResult;
1838 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1839 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00001840 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00001841 }
1842
Eli Friedmanc757de22011-03-25 00:43:55 +00001843 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00001844 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00001845 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001846
Eli Friedman742421e2009-02-20 01:15:07 +00001847 if (!Result.isInt()) {
1848 // Only allow casts of lvalues if they are lossless.
1849 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1850 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001851
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001852 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbarca097ad2009-02-19 20:17:33 +00001853 Result.getInt(), Info.Ctx), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00001854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
Eli Friedmanc757de22011-03-25 00:43:55 +00001856 case CK_PointerToIntegral: {
John McCall45d55e42010-05-07 21:00:08 +00001857 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00001858 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00001859 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001860
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001861 if (LV.getLValueBase()) {
1862 // Only allow based lvalue casts if they are lossless.
1863 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1864 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001865
John McCall45d55e42010-05-07 21:00:08 +00001866 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001867 return true;
1868 }
1869
Ken Dyck02990832010-01-15 12:37:54 +00001870 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1871 SrcType);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00001872 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001873 }
Eli Friedman9a156e52008-11-12 09:44:48 +00001874
Eli Friedmanc757de22011-03-25 00:43:55 +00001875 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00001876 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001877 if (!EvaluateComplex(SubExpr, C, Info))
1878 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00001879 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00001880 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00001881
Eli Friedmanc757de22011-03-25 00:43:55 +00001882 case CK_FloatingToIntegral: {
1883 APFloat F(0.0);
1884 if (!EvaluateFloat(SubExpr, F, Info))
1885 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00001886
Eli Friedmanc757de22011-03-25 00:43:55 +00001887 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1888 }
1889 }
Mike Stump11289f42009-09-09 15:08:12 +00001890
Eli Friedmanc757de22011-03-25 00:43:55 +00001891 llvm_unreachable("unknown cast resulting in integral value");
1892 return false;
Anders Carlsson9c181652008-07-08 14:35:21 +00001893}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00001894
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001895bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1896 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001897 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001898 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1899 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1900 return Success(LV.getComplexIntReal(), E);
1901 }
1902
1903 return Visit(E->getSubExpr());
1904}
1905
Eli Friedman4e7a2412009-02-27 04:45:43 +00001906bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001907 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00001908 ComplexValue LV;
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00001909 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1910 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1911 return Success(LV.getComplexIntImag(), E);
1912 }
1913
Eli Friedman4e7a2412009-02-27 04:45:43 +00001914 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1915 Info.EvalResult.HasSideEffects = true;
1916 return Success(0, E);
1917}
1918
Douglas Gregor820ba7b2011-01-04 17:33:58 +00001919bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1920 return Success(E->getPackLength(), E);
1921}
1922
Sebastian Redl5f0180d2010-09-10 20:55:47 +00001923bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1924 return Success(E->getValue(), E);
1925}
1926
Chris Lattner05706e882008-07-11 18:11:29 +00001927//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00001928// Float Evaluation
1929//===----------------------------------------------------------------------===//
1930
1931namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00001932class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00001933 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00001934 APFloat &Result;
1935public:
1936 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00001937 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00001938
Peter Collingbournee9200682011-05-13 03:29:01 +00001939 bool Success(const APValue &V, const Expr *e) {
1940 Result = V.getFloat();
1941 return true;
1942 }
1943 bool Error(const Stmt *S) {
Eli Friedman24c01542008-08-22 00:06:13 +00001944 return false;
1945 }
1946
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001947 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001948
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00001949 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00001950 bool VisitBinaryOperator(const BinaryOperator *E);
1951 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00001952 bool VisitCastExpr(const CastExpr *E);
1953 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00001954
John McCallb1fb0d32010-05-07 22:08:54 +00001955 bool VisitUnaryReal(const UnaryOperator *E);
1956 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00001957
John McCalla2fabff2010-10-09 01:34:31 +00001958 bool VisitDeclRefExpr(const DeclRefExpr *E);
1959
John McCallb1fb0d32010-05-07 22:08:54 +00001960 // FIXME: Missing: array subscript of vector, member of vector,
1961 // ImplicitValueInitExpr
Eli Friedman24c01542008-08-22 00:06:13 +00001962};
1963} // end anonymous namespace
1964
1965static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00001966 assert(E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00001967 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00001968}
1969
Jay Foad39c79802011-01-12 09:06:06 +00001970static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00001971 QualType ResultTy,
1972 const Expr *Arg,
1973 bool SNaN,
1974 llvm::APFloat &Result) {
1975 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1976 if (!S) return false;
1977
1978 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1979
1980 llvm::APInt fill;
1981
1982 // Treat empty strings as if they were zero.
1983 if (S->getString().empty())
1984 fill = llvm::APInt(32, 0);
1985 else if (S->getString().getAsInteger(0, fill))
1986 return false;
1987
1988 if (SNaN)
1989 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1990 else
1991 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1992 return true;
1993}
1994
Chris Lattner4deaa4e2008-10-06 05:28:25 +00001995bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregore711f702009-02-14 18:57:46 +00001996 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbournee9200682011-05-13 03:29:01 +00001997 default:
1998 return ExprEvaluatorBaseTy::VisitCallExpr(E);
1999
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002000 case Builtin::BI__builtin_huge_val:
2001 case Builtin::BI__builtin_huge_valf:
2002 case Builtin::BI__builtin_huge_vall:
2003 case Builtin::BI__builtin_inf:
2004 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002005 case Builtin::BI__builtin_infl: {
2006 const llvm::fltSemantics &Sem =
2007 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00002008 Result = llvm::APFloat::getInf(Sem);
2009 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00002010 }
Mike Stump11289f42009-09-09 15:08:12 +00002011
John McCall16291492010-02-28 13:00:19 +00002012 case Builtin::BI__builtin_nans:
2013 case Builtin::BI__builtin_nansf:
2014 case Builtin::BI__builtin_nansl:
2015 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2016 true, Result);
2017
Chris Lattner0b7282e2008-10-06 06:31:58 +00002018 case Builtin::BI__builtin_nan:
2019 case Builtin::BI__builtin_nanf:
2020 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00002021 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00002022 // can't constant fold it.
John McCall16291492010-02-28 13:00:19 +00002023 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2024 false, Result);
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002025
2026 case Builtin::BI__builtin_fabs:
2027 case Builtin::BI__builtin_fabsf:
2028 case Builtin::BI__builtin_fabsl:
2029 if (!EvaluateFloat(E->getArg(0), Result, Info))
2030 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002031
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002032 if (Result.isNegative())
2033 Result.changeSign();
2034 return true;
2035
Mike Stump11289f42009-09-09 15:08:12 +00002036 case Builtin::BI__builtin_copysign:
2037 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002038 case Builtin::BI__builtin_copysignl: {
2039 APFloat RHS(0.);
2040 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2041 !EvaluateFloat(E->getArg(1), RHS, Info))
2042 return false;
2043 Result.copySign(RHS);
2044 return true;
2045 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002046 }
2047}
2048
John McCalla2fabff2010-10-09 01:34:31 +00002049bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002050 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2051 return true;
2052
John McCalla2fabff2010-10-09 01:34:31 +00002053 const Decl *D = E->getDecl();
2054 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2055 const VarDecl *VD = cast<VarDecl>(D);
2056
2057 // Require the qualifiers to be const and not volatile.
2058 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2059 if (!T.isConstQualified() || T.isVolatileQualified())
2060 return false;
2061
2062 const Expr *Init = VD->getAnyInitializer();
2063 if (!Init) return false;
2064
2065 if (APValue *V = VD->getEvaluatedValue()) {
2066 if (V->isFloat()) {
2067 Result = V->getFloat();
2068 return true;
2069 }
2070 return false;
2071 }
2072
2073 if (VD->isEvaluatingValue())
2074 return false;
2075
2076 VD->setEvaluatingValue();
2077
2078 Expr::EvalResult InitResult;
2079 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2080 InitResult.Val.isFloat()) {
2081 // Cache the evaluated value in the variable declaration.
2082 Result = InitResult.Val.getFloat();
2083 VD->setEvaluatedValue(InitResult.Val);
2084 return true;
2085 }
2086
2087 VD->setEvaluatedValue(APValue());
2088 return false;
2089}
2090
John McCallb1fb0d32010-05-07 22:08:54 +00002091bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002092 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2093 ComplexValue CV;
2094 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2095 return false;
2096 Result = CV.FloatReal;
2097 return true;
2098 }
2099
2100 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00002101}
2102
2103bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00002104 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2105 ComplexValue CV;
2106 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2107 return false;
2108 Result = CV.FloatImag;
2109 return true;
2110 }
2111
2112 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2113 Info.EvalResult.HasSideEffects = true;
2114 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2115 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00002116 return true;
2117}
2118
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002119bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002120 if (E->getOpcode() == UO_Deref)
Nuno Lopes0e33c682008-11-19 17:44:31 +00002121 return false;
2122
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002123 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2124 return false;
2125
2126 switch (E->getOpcode()) {
2127 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002128 case UO_Plus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002129 return true;
John McCalle3027922010-08-25 11:45:40 +00002130 case UO_Minus:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002131 Result.changeSign();
2132 return true;
2133 }
2134}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00002135
Eli Friedman24c01542008-08-22 00:06:13 +00002136bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00002137 if (E->getOpcode() == BO_Comma) {
Eli Friedman141fbf32009-11-16 04:25:37 +00002138 if (!EvaluateFloat(E->getRHS(), Result, Info))
2139 return false;
2140
2141 // If we can't evaluate the LHS, it might have side effects;
2142 // conservatively mark it.
2143 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2144 Info.EvalResult.HasSideEffects = true;
2145
2146 return true;
2147 }
2148
Anders Carlssona5df61a2010-10-31 01:21:47 +00002149 // We can't evaluate pointer-to-member operations.
2150 if (E->isPtrMemOp())
2151 return false;
2152
Eli Friedman24c01542008-08-22 00:06:13 +00002153 // FIXME: Diagnostics? I really don't understand how the warnings
2154 // and errors are supposed to work.
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00002155 APFloat RHS(0.0);
Eli Friedman24c01542008-08-22 00:06:13 +00002156 if (!EvaluateFloat(E->getLHS(), Result, Info))
2157 return false;
2158 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2159 return false;
2160
2161 switch (E->getOpcode()) {
2162 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002163 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00002164 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2165 return true;
John McCalle3027922010-08-25 11:45:40 +00002166 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00002167 Result.add(RHS, APFloat::rmNearestTiesToEven);
2168 return true;
John McCalle3027922010-08-25 11:45:40 +00002169 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00002170 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2171 return true;
John McCalle3027922010-08-25 11:45:40 +00002172 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00002173 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2174 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00002175 }
2176}
2177
2178bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2179 Result = E->getValue();
2180 return true;
2181}
2182
Peter Collingbournee9200682011-05-13 03:29:01 +00002183bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2184 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002185
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002186 switch (E->getCastKind()) {
2187 default:
2188 return false;
2189
2190 case CK_LValueToRValue:
2191 case CK_NoOp:
2192 return Visit(SubExpr);
2193
2194 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002195 APSInt IntResult;
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00002196 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00002197 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002198 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002199 IntResult, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002200 return true;
2201 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002202
2203 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00002204 if (!Visit(SubExpr))
2205 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00002206 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2207 Result, Info.Ctx);
Eli Friedman9a156e52008-11-12 09:44:48 +00002208 return true;
2209 }
John McCalld7646252010-11-14 08:17:51 +00002210
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002211 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00002212 ComplexValue V;
2213 if (!EvaluateComplex(SubExpr, V, Info))
2214 return false;
2215 Result = V.getComplexFloatReal();
2216 return true;
2217 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00002218 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002219
2220 return false;
2221}
2222
Peter Collingbournee9200682011-05-13 03:29:01 +00002223bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman9a156e52008-11-12 09:44:48 +00002224 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2225 return true;
2226}
2227
Eli Friedman24c01542008-08-22 00:06:13 +00002228//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002229// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00002230//===----------------------------------------------------------------------===//
2231
2232namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002233class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002234 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00002235 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00002236
Anders Carlsson537969c2008-11-16 20:27:53 +00002237public:
John McCall93d91dc2010-05-07 17:22:02 +00002238 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002239 : ExprEvaluatorBaseTy(info), Result(Result) {}
2240
2241 bool Success(const APValue &V, const Expr *e) {
2242 Result.setFrom(V);
2243 return true;
2244 }
2245 bool Error(const Expr *E) {
2246 return false;
2247 }
Mike Stump11289f42009-09-09 15:08:12 +00002248
Anders Carlsson537969c2008-11-16 20:27:53 +00002249 //===--------------------------------------------------------------------===//
2250 // Visitor Methods
2251 //===--------------------------------------------------------------------===//
2252
Peter Collingbournee9200682011-05-13 03:29:01 +00002253 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump11289f42009-09-09 15:08:12 +00002254
Peter Collingbournee9200682011-05-13 03:29:01 +00002255 bool VisitCastExpr(const CastExpr *E);
Mike Stump11289f42009-09-09 15:08:12 +00002256
John McCall93d91dc2010-05-07 17:22:02 +00002257 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002258 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002259 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson537969c2008-11-16 20:27:53 +00002260};
2261} // end anonymous namespace
2262
John McCall93d91dc2010-05-07 17:22:02 +00002263static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2264 EvalInfo &Info) {
John McCallf0c4f352010-05-07 05:46:35 +00002265 assert(E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00002266 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00002267}
2268
Peter Collingbournee9200682011-05-13 03:29:01 +00002269bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2270 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002271
2272 if (SubExpr->getType()->isRealFloatingType()) {
2273 Result.makeComplexFloat();
2274 APFloat &Imag = Result.FloatImag;
2275 if (!EvaluateFloat(SubExpr, Imag, Info))
2276 return false;
2277
2278 Result.FloatReal = APFloat(Imag.getSemantics());
2279 return true;
2280 } else {
2281 assert(SubExpr->getType()->isIntegerType() &&
2282 "Unexpected imaginary literal.");
2283
2284 Result.makeComplexInt();
2285 APSInt &Imag = Result.IntImag;
2286 if (!EvaluateInteger(SubExpr, Imag, Info))
2287 return false;
2288
2289 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2290 return true;
2291 }
2292}
2293
Peter Collingbournee9200682011-05-13 03:29:01 +00002294bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002295
John McCallfcef3cf2010-12-14 17:51:41 +00002296 switch (E->getCastKind()) {
2297 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002298 case CK_BaseToDerived:
2299 case CK_DerivedToBase:
2300 case CK_UncheckedDerivedToBase:
2301 case CK_Dynamic:
2302 case CK_ToUnion:
2303 case CK_ArrayToPointerDecay:
2304 case CK_FunctionToPointerDecay:
2305 case CK_NullToPointer:
2306 case CK_NullToMemberPointer:
2307 case CK_BaseToDerivedMemberPointer:
2308 case CK_DerivedToBaseMemberPointer:
2309 case CK_MemberPointerToBoolean:
2310 case CK_ConstructorConversion:
2311 case CK_IntegralToPointer:
2312 case CK_PointerToIntegral:
2313 case CK_PointerToBoolean:
2314 case CK_ToVoid:
2315 case CK_VectorSplat:
2316 case CK_IntegralCast:
2317 case CK_IntegralToBoolean:
2318 case CK_IntegralToFloating:
2319 case CK_FloatingToIntegral:
2320 case CK_FloatingToBoolean:
2321 case CK_FloatingCast:
2322 case CK_AnyPointerToObjCPointerCast:
2323 case CK_AnyPointerToBlockPointerCast:
2324 case CK_ObjCObjectLValueCast:
2325 case CK_FloatingComplexToReal:
2326 case CK_FloatingComplexToBoolean:
2327 case CK_IntegralComplexToReal:
2328 case CK_IntegralComplexToBoolean:
John McCall31168b02011-06-15 23:02:42 +00002329 case CK_ObjCProduceObject:
2330 case CK_ObjCConsumeObject:
John McCall4db5c3c2011-07-07 06:58:02 +00002331 case CK_ObjCReclaimReturnedObject:
John McCallfcef3cf2010-12-14 17:51:41 +00002332 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00002333
John McCallfcef3cf2010-12-14 17:51:41 +00002334 case CK_LValueToRValue:
2335 case CK_NoOp:
2336 return Visit(E->getSubExpr());
2337
2338 case CK_Dependent:
2339 case CK_GetObjCProperty:
Eli Friedmanc757de22011-03-25 00:43:55 +00002340 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00002341 case CK_UserDefinedConversion:
2342 return false;
2343
2344 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002345 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00002346 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002347 return false;
2348
John McCallfcef3cf2010-12-14 17:51:41 +00002349 Result.makeComplexFloat();
2350 Result.FloatImag = APFloat(Real.getSemantics());
2351 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002352 }
2353
John McCallfcef3cf2010-12-14 17:51:41 +00002354 case CK_FloatingComplexCast: {
2355 if (!Visit(E->getSubExpr()))
2356 return false;
2357
2358 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2359 QualType From
2360 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2361
2362 Result.FloatReal
2363 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2364 Result.FloatImag
2365 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2366 return true;
2367 }
2368
2369 case CK_FloatingComplexToIntegralComplex: {
2370 if (!Visit(E->getSubExpr()))
2371 return false;
2372
2373 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2374 QualType From
2375 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2376 Result.makeComplexInt();
2377 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2378 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2379 return true;
2380 }
2381
2382 case CK_IntegralRealToComplex: {
2383 APSInt &Real = Result.IntReal;
2384 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2385 return false;
2386
2387 Result.makeComplexInt();
2388 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2389 return true;
2390 }
2391
2392 case CK_IntegralComplexCast: {
2393 if (!Visit(E->getSubExpr()))
2394 return false;
2395
2396 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2397 QualType From
2398 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2399
2400 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2401 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2402 return true;
2403 }
2404
2405 case CK_IntegralComplexToFloatingComplex: {
2406 if (!Visit(E->getSubExpr()))
2407 return false;
2408
2409 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2410 QualType From
2411 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2412 Result.makeComplexFloat();
2413 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2414 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2415 return true;
2416 }
2417 }
2418
2419 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00002420 return false;
2421}
2422
John McCall93d91dc2010-05-07 17:22:02 +00002423bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002424 if (E->getOpcode() == BO_Comma) {
2425 if (!Visit(E->getRHS()))
2426 return false;
2427
2428 // If we can't evaluate the LHS, it might have side effects;
2429 // conservatively mark it.
2430 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2431 Info.EvalResult.HasSideEffects = true;
2432
2433 return true;
2434 }
John McCall93d91dc2010-05-07 17:22:02 +00002435 if (!Visit(E->getLHS()))
2436 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002437
John McCall93d91dc2010-05-07 17:22:02 +00002438 ComplexValue RHS;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002439 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCall93d91dc2010-05-07 17:22:02 +00002440 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002441
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002442 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2443 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002444 switch (E->getOpcode()) {
John McCall93d91dc2010-05-07 17:22:02 +00002445 default: return false;
John McCalle3027922010-08-25 11:45:40 +00002446 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002447 if (Result.isComplexFloat()) {
2448 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2449 APFloat::rmNearestTiesToEven);
2450 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2451 APFloat::rmNearestTiesToEven);
2452 } else {
2453 Result.getComplexIntReal() += RHS.getComplexIntReal();
2454 Result.getComplexIntImag() += RHS.getComplexIntImag();
2455 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002456 break;
John McCalle3027922010-08-25 11:45:40 +00002457 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002458 if (Result.isComplexFloat()) {
2459 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2460 APFloat::rmNearestTiesToEven);
2461 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2462 APFloat::rmNearestTiesToEven);
2463 } else {
2464 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2465 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2466 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002467 break;
John McCalle3027922010-08-25 11:45:40 +00002468 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002469 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00002470 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002471 APFloat &LHS_r = LHS.getComplexFloatReal();
2472 APFloat &LHS_i = LHS.getComplexFloatImag();
2473 APFloat &RHS_r = RHS.getComplexFloatReal();
2474 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00002475
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002476 APFloat Tmp = LHS_r;
2477 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2478 Result.getComplexFloatReal() = Tmp;
2479 Tmp = LHS_i;
2480 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2481 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2482
2483 Tmp = LHS_r;
2484 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2485 Result.getComplexFloatImag() = Tmp;
2486 Tmp = LHS_i;
2487 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2488 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2489 } else {
John McCall93d91dc2010-05-07 17:22:02 +00002490 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00002491 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002492 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2493 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00002494 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00002495 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2496 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2497 }
2498 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002499 case BO_Div:
2500 if (Result.isComplexFloat()) {
2501 ComplexValue LHS = Result;
2502 APFloat &LHS_r = LHS.getComplexFloatReal();
2503 APFloat &LHS_i = LHS.getComplexFloatImag();
2504 APFloat &RHS_r = RHS.getComplexFloatReal();
2505 APFloat &RHS_i = RHS.getComplexFloatImag();
2506 APFloat &Res_r = Result.getComplexFloatReal();
2507 APFloat &Res_i = Result.getComplexFloatImag();
2508
2509 APFloat Den = RHS_r;
2510 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2511 APFloat Tmp = RHS_i;
2512 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2513 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2514
2515 Res_r = LHS_r;
2516 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2517 Tmp = LHS_i;
2518 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2519 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2520 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2521
2522 Res_i = LHS_i;
2523 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2524 Tmp = LHS_r;
2525 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2526 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2527 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2528 } else {
2529 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2530 // FIXME: what about diagnostics?
2531 return false;
2532 }
2533 ComplexValue LHS = Result;
2534 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2535 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2536 Result.getComplexIntReal() =
2537 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2538 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2539 Result.getComplexIntImag() =
2540 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2541 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2542 }
2543 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002544 }
2545
John McCall93d91dc2010-05-07 17:22:02 +00002546 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00002547}
2548
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00002549bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2550 // Get the operand value into 'Result'.
2551 if (!Visit(E->getSubExpr()))
2552 return false;
2553
2554 switch (E->getOpcode()) {
2555 default:
2556 // FIXME: what about diagnostics?
2557 return false;
2558 case UO_Extension:
2559 return true;
2560 case UO_Plus:
2561 // The result is always just the subexpr.
2562 return true;
2563 case UO_Minus:
2564 if (Result.isComplexFloat()) {
2565 Result.getComplexFloatReal().changeSign();
2566 Result.getComplexFloatImag().changeSign();
2567 }
2568 else {
2569 Result.getComplexIntReal() = -Result.getComplexIntReal();
2570 Result.getComplexIntImag() = -Result.getComplexIntImag();
2571 }
2572 return true;
2573 case UO_Not:
2574 if (Result.isComplexFloat())
2575 Result.getComplexFloatImag().changeSign();
2576 else
2577 Result.getComplexIntImag() = -Result.getComplexIntImag();
2578 return true;
2579 }
2580}
2581
Anders Carlsson537969c2008-11-16 20:27:53 +00002582//===----------------------------------------------------------------------===//
Chris Lattner67d7b922008-11-16 21:24:15 +00002583// Top level Expr::Evaluate method.
Chris Lattner05706e882008-07-11 18:11:29 +00002584//===----------------------------------------------------------------------===//
2585
John McCallc07a0c72011-02-17 10:25:35 +00002586static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCall45d55e42010-05-07 21:00:08 +00002587 if (E->getType()->isVectorType()) {
2588 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002589 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002590 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002591 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002592 return false;
John McCallc07a0c72011-02-17 10:25:35 +00002593 if (Info.EvalResult.Val.isLValue() &&
2594 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall11086fc2010-07-07 05:08:32 +00002595 return false;
John McCall45d55e42010-05-07 21:00:08 +00002596 } else if (E->getType()->hasPointerRepresentation()) {
2597 LValue LV;
2598 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002599 return false;
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002600 if (!IsGlobalLValue(LV.Base))
John McCall95007602010-05-10 23:27:23 +00002601 return false;
John McCall45d55e42010-05-07 21:00:08 +00002602 LV.moveInto(Info.EvalResult.Val);
2603 } else if (E->getType()->isRealFloatingType()) {
2604 llvm::APFloat F(0.0);
2605 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002606 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002607
John McCall45d55e42010-05-07 21:00:08 +00002608 Info.EvalResult.Val = APValue(F);
2609 } else if (E->getType()->isAnyComplexType()) {
2610 ComplexValue C;
2611 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002612 return false;
John McCall45d55e42010-05-07 21:00:08 +00002613 C.moveInto(Info.EvalResult.Val);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00002614 } else
Anders Carlsson7c282e42008-11-22 22:56:32 +00002615 return false;
Anders Carlsson475f4bc2008-11-22 21:50:49 +00002616
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00002617 return true;
2618}
2619
John McCallc07a0c72011-02-17 10:25:35 +00002620/// Evaluate - Return true if this is a constant which we can fold using
2621/// any crazy technique (that has nothing to do with language standards) that
2622/// we want to. If this function returns true, it returns the folded constant
2623/// in Result.
2624bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2625 EvalInfo Info(Ctx, Result);
2626 return ::Evaluate(Info, this);
2627}
2628
Jay Foad39c79802011-01-12 09:06:06 +00002629bool Expr::EvaluateAsBooleanCondition(bool &Result,
2630 const ASTContext &Ctx) const {
John McCall1be1c632010-01-05 23:42:56 +00002631 EvalResult Scratch;
2632 EvalInfo Info(Ctx, Scratch);
2633
2634 return HandleConversionToBool(this, Result, Info);
2635}
2636
Jay Foad39c79802011-01-12 09:06:06 +00002637bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00002638 EvalInfo Info(Ctx, Result);
2639
John McCall45d55e42010-05-07 21:00:08 +00002640 LValue LV;
John McCall95007602010-05-10 23:27:23 +00002641 if (EvaluateLValue(this, LV, Info) &&
2642 !Result.HasSideEffects &&
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002643 IsGlobalLValue(LV.Base)) {
2644 LV.moveInto(Result.Val);
2645 return true;
2646 }
2647 return false;
2648}
2649
Jay Foad39c79802011-01-12 09:06:06 +00002650bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2651 const ASTContext &Ctx) const {
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002652 EvalInfo Info(Ctx, Result);
2653
2654 LValue LV;
2655 if (EvaluateLValue(this, LV, Info)) {
John McCall45d55e42010-05-07 21:00:08 +00002656 LV.moveInto(Result.Val);
2657 return true;
2658 }
2659 return false;
Eli Friedman7d45c482009-09-13 10:17:44 +00002660}
2661
Chris Lattner67d7b922008-11-16 21:24:15 +00002662/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattnercb136912008-10-06 06:49:02 +00002663/// folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00002664bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00002665 EvalResult Result;
2666 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00002667}
Anders Carlsson59689ed2008-11-22 21:04:56 +00002668
Jay Foad39c79802011-01-12 09:06:06 +00002669bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002670 Expr::EvalResult Result;
2671 EvalInfo Info(Ctx, Result);
Peter Collingbournee9200682011-05-13 03:29:01 +00002672 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00002673}
2674
Jay Foad39c79802011-01-12 09:06:06 +00002675APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002676 EvalResult EvalResult;
2677 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00002678 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00002679 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002680 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00002681
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002682 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00002683}
John McCall864e3962010-05-07 05:32:02 +00002684
Abramo Bagnaraf8199452010-05-14 17:07:14 +00002685 bool Expr::EvalResult::isGlobalLValue() const {
2686 assert(Val.isLValue());
2687 return IsGlobalLValue(Val.getLValueBase());
2688 }
2689
2690
John McCall864e3962010-05-07 05:32:02 +00002691/// isIntegerConstantExpr - this recursive routine will test if an expression is
2692/// an integer constant expression.
2693
2694/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2695/// comma, etc
2696///
2697/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2698/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2699/// cast+dereference.
2700
2701// CheckICE - This function does the fundamental ICE checking: the returned
2702// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2703// Note that to reduce code duplication, this helper does no evaluation
2704// itself; the caller checks whether the expression is evaluatable, and
2705// in the rare cases where CheckICE actually cares about the evaluated
2706// value, it calls into Evalute.
2707//
2708// Meanings of Val:
2709// 0: This expression is an ICE if it can be evaluated by Evaluate.
2710// 1: This expression is not an ICE, but if it isn't evaluated, it's
2711// a legal subexpression for an ICE. This return value is used to handle
2712// the comma operator in C99 mode.
2713// 2: This expression is not an ICE, and is not a legal subexpression for one.
2714
Dan Gohman28ade552010-07-26 21:25:24 +00002715namespace {
2716
John McCall864e3962010-05-07 05:32:02 +00002717struct ICEDiag {
2718 unsigned Val;
2719 SourceLocation Loc;
2720
2721 public:
2722 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2723 ICEDiag() : Val(0) {}
2724};
2725
Dan Gohman28ade552010-07-26 21:25:24 +00002726}
2727
2728static ICEDiag NoDiag() { return ICEDiag(); }
John McCall864e3962010-05-07 05:32:02 +00002729
2730static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2731 Expr::EvalResult EVResult;
2732 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2733 !EVResult.Val.isInt()) {
2734 return ICEDiag(2, E->getLocStart());
2735 }
2736 return NoDiag();
2737}
2738
2739static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2740 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregorb90df602010-06-16 00:17:44 +00002741 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCall864e3962010-05-07 05:32:02 +00002742 return ICEDiag(2, E->getLocStart());
2743 }
2744
2745 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00002746#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00002747#define STMT(Node, Base) case Expr::Node##Class:
2748#define EXPR(Node, Base)
2749#include "clang/AST/StmtNodes.inc"
2750 case Expr::PredefinedExprClass:
2751 case Expr::FloatingLiteralClass:
2752 case Expr::ImaginaryLiteralClass:
2753 case Expr::StringLiteralClass:
2754 case Expr::ArraySubscriptExprClass:
2755 case Expr::MemberExprClass:
2756 case Expr::CompoundAssignOperatorClass:
2757 case Expr::CompoundLiteralExprClass:
2758 case Expr::ExtVectorElementExprClass:
2759 case Expr::InitListExprClass:
2760 case Expr::DesignatedInitExprClass:
2761 case Expr::ImplicitValueInitExprClass:
2762 case Expr::ParenListExprClass:
2763 case Expr::VAArgExprClass:
2764 case Expr::AddrLabelExprClass:
2765 case Expr::StmtExprClass:
2766 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00002767 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00002768 case Expr::CXXDynamicCastExprClass:
2769 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00002770 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00002771 case Expr::CXXNullPtrLiteralExprClass:
2772 case Expr::CXXThisExprClass:
2773 case Expr::CXXThrowExprClass:
2774 case Expr::CXXNewExprClass:
2775 case Expr::CXXDeleteExprClass:
2776 case Expr::CXXPseudoDestructorExprClass:
2777 case Expr::UnresolvedLookupExprClass:
2778 case Expr::DependentScopeDeclRefExprClass:
2779 case Expr::CXXConstructExprClass:
2780 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00002781 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00002782 case Expr::CXXTemporaryObjectExprClass:
2783 case Expr::CXXUnresolvedConstructExprClass:
2784 case Expr::CXXDependentScopeMemberExprClass:
2785 case Expr::UnresolvedMemberExprClass:
2786 case Expr::ObjCStringLiteralClass:
2787 case Expr::ObjCEncodeExprClass:
2788 case Expr::ObjCMessageExprClass:
2789 case Expr::ObjCSelectorExprClass:
2790 case Expr::ObjCProtocolExprClass:
2791 case Expr::ObjCIvarRefExprClass:
2792 case Expr::ObjCPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00002793 case Expr::ObjCIsaExprClass:
2794 case Expr::ShuffleVectorExprClass:
2795 case Expr::BlockExprClass:
2796 case Expr::BlockDeclRefExprClass:
2797 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00002798 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00002799 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00002800 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00002801 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00002802 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00002803 case Expr::MaterializeTemporaryExprClass:
John McCall864e3962010-05-07 05:32:02 +00002804 return ICEDiag(2, E->getLocStart());
2805
Douglas Gregor820ba7b2011-01-04 17:33:58 +00002806 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00002807 case Expr::GNUNullExprClass:
2808 // GCC considers the GNU __null value to be an integral constant expression.
2809 return NoDiag();
2810
John McCall7c454bb2011-07-15 05:09:51 +00002811 case Expr::SubstNonTypeTemplateParmExprClass:
2812 return
2813 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
2814
John McCall864e3962010-05-07 05:32:02 +00002815 case Expr::ParenExprClass:
2816 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00002817 case Expr::GenericSelectionExprClass:
2818 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002819 case Expr::IntegerLiteralClass:
2820 case Expr::CharacterLiteralClass:
2821 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00002822 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00002823 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00002824 case Expr::BinaryTypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00002825 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00002826 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00002827 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00002828 return NoDiag();
2829 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00002830 case Expr::CXXOperatorCallExprClass: {
John McCall864e3962010-05-07 05:32:02 +00002831 const CallExpr *CE = cast<CallExpr>(E);
2832 if (CE->isBuiltinCall(Ctx))
2833 return CheckEvalInICE(E, Ctx);
2834 return ICEDiag(2, E->getLocStart());
2835 }
2836 case Expr::DeclRefExprClass:
2837 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2838 return NoDiag();
2839 if (Ctx.getLangOptions().CPlusPlus &&
2840 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2841 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2842
2843 // Parameter variables are never constants. Without this check,
2844 // getAnyInitializer() can find a default argument, which leads
2845 // to chaos.
2846 if (isa<ParmVarDecl>(D))
2847 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2848
2849 // C++ 7.1.5.1p2
2850 // A variable of non-volatile const-qualified integral or enumeration
2851 // type initialized by an ICE can be used in ICEs.
2852 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2853 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2854 if (Quals.hasVolatile() || !Quals.hasConst())
2855 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2856
2857 // Look for a declaration of this variable that has an initializer.
2858 const VarDecl *ID = 0;
2859 const Expr *Init = Dcl->getAnyInitializer(ID);
2860 if (Init) {
2861 if (ID->isInitKnownICE()) {
2862 // We have already checked whether this subexpression is an
2863 // integral constant expression.
2864 if (ID->isInitICE())
2865 return NoDiag();
2866 else
2867 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2868 }
2869
2870 // It's an ICE whether or not the definition we found is
2871 // out-of-line. See DR 721 and the discussion in Clang PR
2872 // 6206 for details.
2873
2874 if (Dcl->isCheckingICE()) {
2875 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2876 }
2877
2878 Dcl->setCheckingICE();
2879 ICEDiag Result = CheckICE(Init, Ctx);
2880 // Cache the result of the ICE test.
2881 Dcl->setInitKnownICE(Result.Val == 0);
2882 return Result;
2883 }
2884 }
2885 }
2886 return ICEDiag(2, E->getLocStart());
2887 case Expr::UnaryOperatorClass: {
2888 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2889 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002890 case UO_PostInc:
2891 case UO_PostDec:
2892 case UO_PreInc:
2893 case UO_PreDec:
2894 case UO_AddrOf:
2895 case UO_Deref:
John McCall864e3962010-05-07 05:32:02 +00002896 return ICEDiag(2, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00002897 case UO_Extension:
2898 case UO_LNot:
2899 case UO_Plus:
2900 case UO_Minus:
2901 case UO_Not:
2902 case UO_Real:
2903 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00002904 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00002905 }
2906
2907 // OffsetOf falls through here.
2908 }
2909 case Expr::OffsetOfExprClass: {
2910 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2911 // Evaluate matches the proposed gcc behavior for cases like
2912 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2913 // compliance: we should warn earlier for offsetof expressions with
2914 // array subscripts that aren't ICEs, and if the array subscripts
2915 // are ICEs, the value of the offsetof must be an integer constant.
2916 return CheckEvalInICE(E, Ctx);
2917 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00002918 case Expr::UnaryExprOrTypeTraitExprClass: {
2919 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2920 if ((Exp->getKind() == UETT_SizeOf) &&
2921 Exp->getTypeOfArgument()->isVariableArrayType())
John McCall864e3962010-05-07 05:32:02 +00002922 return ICEDiag(2, E->getLocStart());
2923 return NoDiag();
2924 }
2925 case Expr::BinaryOperatorClass: {
2926 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2927 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00002928 case BO_PtrMemD:
2929 case BO_PtrMemI:
2930 case BO_Assign:
2931 case BO_MulAssign:
2932 case BO_DivAssign:
2933 case BO_RemAssign:
2934 case BO_AddAssign:
2935 case BO_SubAssign:
2936 case BO_ShlAssign:
2937 case BO_ShrAssign:
2938 case BO_AndAssign:
2939 case BO_XorAssign:
2940 case BO_OrAssign:
John McCall864e3962010-05-07 05:32:02 +00002941 return ICEDiag(2, E->getLocStart());
2942
John McCalle3027922010-08-25 11:45:40 +00002943 case BO_Mul:
2944 case BO_Div:
2945 case BO_Rem:
2946 case BO_Add:
2947 case BO_Sub:
2948 case BO_Shl:
2949 case BO_Shr:
2950 case BO_LT:
2951 case BO_GT:
2952 case BO_LE:
2953 case BO_GE:
2954 case BO_EQ:
2955 case BO_NE:
2956 case BO_And:
2957 case BO_Xor:
2958 case BO_Or:
2959 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00002960 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2961 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00002962 if (Exp->getOpcode() == BO_Div ||
2963 Exp->getOpcode() == BO_Rem) {
John McCall864e3962010-05-07 05:32:02 +00002964 // Evaluate gives an error for undefined Div/Rem, so make sure
2965 // we don't evaluate one.
John McCall4b136332011-02-26 08:27:17 +00002966 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCall864e3962010-05-07 05:32:02 +00002967 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2968 if (REval == 0)
2969 return ICEDiag(1, E->getLocStart());
2970 if (REval.isSigned() && REval.isAllOnesValue()) {
2971 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2972 if (LEval.isMinSignedValue())
2973 return ICEDiag(1, E->getLocStart());
2974 }
2975 }
2976 }
John McCalle3027922010-08-25 11:45:40 +00002977 if (Exp->getOpcode() == BO_Comma) {
John McCall864e3962010-05-07 05:32:02 +00002978 if (Ctx.getLangOptions().C99) {
2979 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2980 // if it isn't evaluated.
2981 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2982 return ICEDiag(1, E->getLocStart());
2983 } else {
2984 // In both C89 and C++, commas in ICEs are illegal.
2985 return ICEDiag(2, E->getLocStart());
2986 }
2987 }
2988 if (LHSResult.Val >= RHSResult.Val)
2989 return LHSResult;
2990 return RHSResult;
2991 }
John McCalle3027922010-08-25 11:45:40 +00002992 case BO_LAnd:
2993 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00002994 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00002995
2996 // C++0x [expr.const]p2:
2997 // [...] subexpressions of logical AND (5.14), logical OR
2998 // (5.15), and condi- tional (5.16) operations that are not
2999 // evaluated are not considered.
3000 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
3001 if (Exp->getOpcode() == BO_LAnd &&
3002 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
3003 return LHSResult;
3004
3005 if (Exp->getOpcode() == BO_LOr &&
3006 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
3007 return LHSResult;
3008 }
3009
John McCall864e3962010-05-07 05:32:02 +00003010 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3011 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3012 // Rare case where the RHS has a comma "side-effect"; we need
3013 // to actually check the condition to see whether the side
3014 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00003015 if ((Exp->getOpcode() == BO_LAnd) !=
John McCall864e3962010-05-07 05:32:02 +00003016 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3017 return RHSResult;
3018 return NoDiag();
3019 }
3020
3021 if (LHSResult.Val >= RHSResult.Val)
3022 return LHSResult;
3023 return RHSResult;
3024 }
3025 }
3026 }
3027 case Expr::ImplicitCastExprClass:
3028 case Expr::CStyleCastExprClass:
3029 case Expr::CXXFunctionalCastExprClass:
3030 case Expr::CXXStaticCastExprClass:
3031 case Expr::CXXReinterpretCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00003032 case Expr::CXXConstCastExprClass:
3033 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00003034 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregorb90df602010-06-16 00:17:44 +00003035 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCall864e3962010-05-07 05:32:02 +00003036 return CheckICE(SubExpr, Ctx);
3037 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3038 return NoDiag();
3039 return ICEDiag(2, E->getLocStart());
3040 }
John McCallc07a0c72011-02-17 10:25:35 +00003041 case Expr::BinaryConditionalOperatorClass: {
3042 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3043 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3044 if (CommonResult.Val == 2) return CommonResult;
3045 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3046 if (FalseResult.Val == 2) return FalseResult;
3047 if (CommonResult.Val == 1) return CommonResult;
3048 if (FalseResult.Val == 1 &&
3049 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3050 return FalseResult;
3051 }
John McCall864e3962010-05-07 05:32:02 +00003052 case Expr::ConditionalOperatorClass: {
3053 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3054 // If the condition (ignoring parens) is a __builtin_constant_p call,
3055 // then only the true side is actually considered in an integer constant
3056 // expression, and it is fully evaluated. This is an important GNU
3057 // extension. See GCC PR38377 for discussion.
3058 if (const CallExpr *CallCE
3059 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3060 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3061 Expr::EvalResult EVResult;
3062 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3063 !EVResult.Val.isInt()) {
3064 return ICEDiag(2, E->getLocStart());
3065 }
3066 return NoDiag();
3067 }
3068 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00003069 if (CondResult.Val == 2)
3070 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00003071
3072 // C++0x [expr.const]p2:
3073 // subexpressions of [...] conditional (5.16) operations that
3074 // are not evaluated are not considered
3075 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3076 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3077 : false;
3078 ICEDiag TrueResult = NoDiag();
3079 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3080 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3081 ICEDiag FalseResult = NoDiag();
3082 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3083 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3084
John McCall864e3962010-05-07 05:32:02 +00003085 if (TrueResult.Val == 2)
3086 return TrueResult;
3087 if (FalseResult.Val == 2)
3088 return FalseResult;
3089 if (CondResult.Val == 1)
3090 return CondResult;
3091 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3092 return NoDiag();
3093 // Rare case where the diagnostics depend on which side is evaluated
3094 // Note that if we get here, CondResult is 0, and at least one of
3095 // TrueResult and FalseResult is non-zero.
3096 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3097 return FalseResult;
3098 }
3099 return TrueResult;
3100 }
3101 case Expr::CXXDefaultArgExprClass:
3102 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3103 case Expr::ChooseExprClass: {
3104 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3105 }
3106 }
3107
3108 // Silence a GCC warning
3109 return ICEDiag(2, E->getLocStart());
3110}
3111
3112bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3113 SourceLocation *Loc, bool isEvaluated) const {
3114 ICEDiag d = CheckICE(this, Ctx);
3115 if (d.Val != 0) {
3116 if (Loc) *Loc = d.Loc;
3117 return false;
3118 }
3119 EvalResult EvalResult;
3120 if (!Evaluate(EvalResult, Ctx))
3121 llvm_unreachable("ICE cannot be evaluated!");
3122 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3123 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3124 Result = EvalResult.Val.getInt();
3125 return true;
3126}