blob: 9943222b1dd30d9761731fca984d20d6b578f788 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-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 Dyck199c3d62010-01-11 17:06:35 +000016#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000017#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000018#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000019#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000020#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000021#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000022#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000023#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000024#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000025#include <cstring>
26
Anders Carlssonc44eec62008-07-03 04:20:39 +000027using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000028using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000029using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000030
Chris Lattner87eae5e2008-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 McCallf4cf1a12010-05-07 17:22:02 +000045namespace {
Benjamin Kramerc54061a2011-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 McCallf4cf1a12010-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 McCall56ca35d2011-02-17 10:25:35 +000084 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +000085 if (isComplexFloat())
86 v = APValue(FloatReal, FloatImag);
87 else
88 v = APValue(IntReal, IntImag);
89 }
John McCall56ca35d2011-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 McCallf4cf1a12010-05-07 17:22:02 +0000102 };
John McCallefdb83e2010-05-07 21:00:08 +0000103
104 struct LValue {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000105 const Expr *Base;
John McCallefdb83e2010-05-07 21:00:08 +0000106 CharUnits Offset;
107
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000108 const Expr *getLValueBase() { return Base; }
John McCallefdb83e2010-05-07 21:00:08 +0000109 CharUnits getLValueOffset() { return Offset; }
110
John McCall56ca35d2011-02-17 10:25:35 +0000111 void moveInto(APValue &v) const {
John McCallefdb83e2010-05-07 21:00:08 +0000112 v = APValue(Base, Offset);
113 }
John McCall56ca35d2011-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 McCallefdb83e2010-05-07 21:00:08 +0000119 };
John McCallf4cf1a12010-05-07 17:22:02 +0000120}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000121
John McCall56ca35d2011-02-17 10:25:35 +0000122static bool Evaluate(EvalInfo &info, const Expr *E);
John McCallefdb83e2010-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 Lattner87eae5e2008-07-11 22:52:41 +0000125static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Chris Lattnerd9becd12009-10-28 23:59:40 +0000126static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
127 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000128static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000129static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000130
131//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000132// Misc utilities
133//===----------------------------------------------------------------------===//
134
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000135static bool IsGlobalLValue(const Expr* E) {
John McCall42c8f872010-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 McCallefdb83e2010-05-07 21:00:08 +0000152static bool EvalPointerValueAsBool(LValue& Value, bool& Result) {
153 const Expr* Base = Value.Base;
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000154
John McCall35542832010-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 Espindolaa7d3c042010-05-07 15:18:43 +0000161
John McCall42c8f872010-05-10 23:27:23 +0000162 // Require the base expression to be a global l-value.
Abramo Bagnarae17a6432010-05-14 17:07:14 +0000163 if (!IsGlobalLValue(Base)) return false;
John McCall42c8f872010-05-10 23:27:23 +0000164
John McCall35542832010-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 McCall35542832010-05-07 21:34:32 +0000168 Result = true;
169
170 const DeclRefExpr* DeclRef = dyn_cast<DeclRefExpr>(Base);
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000171 if (!DeclRef)
172 return true;
173
John McCall35542832010-05-07 21:34:32 +0000174 // If it's a weak symbol, it isn't constant-evaluable.
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000175 const ValueDecl* Decl = DeclRef->getDecl();
176 if (Decl->hasAttr<WeakAttr>() ||
177 Decl->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000178 Decl->isWeakImported())
Rafael Espindolaa7d3c042010-05-07 15:18:43 +0000179 return false;
180
Eli Friedman5bc86102009-06-14 02:17:33 +0000181 return true;
182}
183
John McCallcd7a4452010-01-05 23:42:56 +0000184static bool HandleConversionToBool(const Expr* E, bool& Result,
185 EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000186 if (E->getType()->isIntegralOrEnumerationType()) {
Eli Friedman4efaa272008-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 Friedmana1f47c42009-03-23 04:38:34 +0000198 } else if (E->getType()->hasPointerRepresentation()) {
John McCallefdb83e2010-05-07 21:00:08 +0000199 LValue PointerResult;
Eli Friedman4efaa272008-11-12 09:44:48 +0000200 if (!EvaluatePointer(E, PointerResult, Info))
201 return false;
Eli Friedman5bc86102009-06-14 02:17:33 +0000202 return EvalPointerValueAsBool(PointerResult, Result);
Eli Friedmana1f47c42009-03-23 04:38:34 +0000203 } else if (E->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +0000204 ComplexValue ComplexResult;
Eli Friedmana1f47c42009-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 Friedman4efaa272008-11-12 09:44:48 +0000215 }
216
217 return false;
218}
219
Mike Stump1eb44332009-09-09 15:08:12 +0000220static APSInt HandleFloatToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000221 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000222 unsigned DestWidth = Ctx.getIntWidth(DestType);
223 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +0000224 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Daniel Dunbara2cfd342009-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 Stump1eb44332009-09-09 15:08:12 +0000234static APFloat HandleFloatToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000235 APFloat &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000236 bool ignored;
237 APFloat Result = Value;
Mike Stump1eb44332009-09-09 15:08:12 +0000238 Result.convert(Ctx.getFloatTypeSemantics(DestType),
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000239 APFloat::rmNearestTiesToEven, &ignored);
240 return Result;
241}
242
Mike Stump1eb44332009-09-09 15:08:12 +0000243static APSInt HandleIntToIntCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000244 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-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 Foad9f71a8f2010-12-07 08:25:34 +0000249 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +0000250 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +0000251 return Result;
252}
253
Mike Stump1eb44332009-09-09 15:08:12 +0000254static APFloat HandleIntToFloatCast(QualType DestType, QualType SrcType,
Jay Foad4ba2a172011-01-12 09:06:06 +0000255 APSInt &Value, const ASTContext &Ctx) {
Daniel Dunbara2cfd342009-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 Stumpc4c90452009-10-27 22:09:17 +0000263namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000264class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000265 : public ConstStmtVisitor<HasSideEffect, bool> {
Mike Stumpc4c90452009-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 Collingbourne8cad3042011-05-13 03:29:01 +0000272 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +0000273 return true;
274 }
275
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000276 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
277 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +0000278 return Visit(E->getResultExpr());
279 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000280 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Mike Stumpdf317bf2009-11-03 23:25:48 +0000281 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000282 return true;
283 return false;
284 }
John McCallf85e1932011-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 Stumpc4c90452009-10-27 22:09:17 +0000296 // We don't want to evaluate BlockExprs multiple times, as they generate
297 // a ton of code.
Peter Collingbourne8cad3042011-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 Stumpc4c90452009-10-27 22:09:17 +0000301 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-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 Collingbournef4e3cfb2011-03-11 19:24:49 +0000308 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000309 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +0000310 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000311 bool VisitChooseExpr(const ChooseExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +0000312 { return Visit(E->getChosenSubExpr(Info.Ctx)); }
Peter Collingbourne8cad3042011-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 Stump980ca222009-10-29 20:48:09 +0000317 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-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 Stumpdf317bf2009-11-03 23:25:48 +0000323 if (Info.Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +0000324 return true;
Mike Stump980ca222009-10-29 20:48:09 +0000325 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +0000326 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000327 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +0000328
329 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000330 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-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 Collingbourne8cad3042011-05-13 03:29:01 +0000333 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +0000334 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +0000335 return false;
336 }
Douglas Gregoree8aff02011-01-04 17:33:58 +0000337
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000338 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +0000339};
340
John McCall56ca35d2011-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 Stumpc4c90452009-10-27 22:09:17 +0000365} // end anonymous namespace
366
Eli Friedman4efaa272008-11-12 09:44:48 +0000367//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-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()); }
409
410 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
411 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
412 if (opaque.hasError())
413 return DerivedError(E);
414
415 bool cond;
416 if (!HandleConversionToBool(E->getCond(), cond, Info))
417 return DerivedError(E);
418
419 return StmtVisitorTy::Visit(cond ? E->getTrueExpr() : E->getFalseExpr());
420 }
421
422 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
423 bool BoolResult;
424 if (!HandleConversionToBool(E->getCond(), BoolResult, Info))
425 return DerivedError(E);
426
427 Expr* EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
428 return StmtVisitorTy::Visit(EvalExpr);
429 }
430
431 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
432 const APValue *value = Info.getOpaqueValue(E);
433 if (!value)
434 return (E->getSourceExpr() ? StmtVisitorTy::Visit(E->getSourceExpr())
435 : DerivedError(E));
436 return DerivedSuccess(*value, E);
437 }
438};
439
440}
441
442//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000443// LValue Evaluation
444//===----------------------------------------------------------------------===//
445namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000446class LValueExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000447 : public ExprEvaluatorBase<LValueExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000448 LValue &Result;
449
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000450 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000451 Result.Base = E;
452 Result.Offset = CharUnits::Zero();
453 return true;
454 }
Eli Friedman4efaa272008-11-12 09:44:48 +0000455public:
Mike Stump1eb44332009-09-09 15:08:12 +0000456
John McCallefdb83e2010-05-07 21:00:08 +0000457 LValueExprEvaluator(EvalInfo &info, LValue &Result) :
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000458 ExprEvaluatorBaseTy(info), Result(Result) {}
Eli Friedman4efaa272008-11-12 09:44:48 +0000459
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000460 bool Success(const APValue &V, const Expr *E) {
461 Result.setFrom(V);
462 return true;
463 }
464 bool Error(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000465 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000466 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000467
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000468 bool VisitDeclRefExpr(const DeclRefExpr *E);
469 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
470 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
471 bool VisitMemberExpr(const MemberExpr *E);
472 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
473 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
474 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
475 bool VisitUnaryDeref(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +0000476
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000477 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +0000478 switch (E->getCastKind()) {
479 default:
John McCallefdb83e2010-05-07 21:00:08 +0000480 return false;
Anders Carlsson26bc2202009-10-03 16:30:22 +0000481
John McCall2de56d12010-08-25 11:45:40 +0000482 case CK_NoOp:
Anders Carlsson26bc2202009-10-03 16:30:22 +0000483 return Visit(E->getSubExpr());
484 }
485 }
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000486 // FIXME: Missing: __real__, __imag__
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000487
Eli Friedman4efaa272008-11-12 09:44:48 +0000488};
489} // end anonymous namespace
490
John McCallefdb83e2010-05-07 21:00:08 +0000491static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000492 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000493}
494
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000495bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000496 if (isa<FunctionDecl>(E->getDecl())) {
John McCallefdb83e2010-05-07 21:00:08 +0000497 return Success(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000498 } else if (const VarDecl* VD = dyn_cast<VarDecl>(E->getDecl())) {
Eli Friedman50c39ea2009-05-27 06:04:58 +0000499 if (!VD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000500 return Success(E);
Chandler Carruth761c94e2010-05-16 09:32:51 +0000501 // Reference parameters can refer to anything even if they have an
502 // "initializer" in the form of a default argument.
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000503 if (!isa<ParmVarDecl>(VD))
504 // FIXME: Check whether VD might be overridden!
505 if (const Expr *Init = VD->getAnyInitializer())
506 return Visit(Init);
Eli Friedman50c39ea2009-05-27 06:04:58 +0000507 }
508
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000509 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Anders Carlsson35873c42008-11-24 04:41:22 +0000510}
511
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000512bool
513LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000514 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000515}
516
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000517bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +0000518 QualType Ty;
519 if (E->isArrow()) {
John McCallefdb83e2010-05-07 21:00:08 +0000520 if (!EvaluatePointer(E->getBase(), Result, Info))
521 return false;
Ted Kremenek6217b802009-07-29 21:53:49 +0000522 Ty = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Eli Friedman4efaa272008-11-12 09:44:48 +0000523 } else {
John McCallefdb83e2010-05-07 21:00:08 +0000524 if (!Visit(E->getBase()))
525 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +0000526 Ty = E->getBase()->getType();
527 }
528
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000529 const RecordDecl *RD = Ty->getAs<RecordType>()->getDecl();
Eli Friedman4efaa272008-11-12 09:44:48 +0000530 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
Douglas Gregor86f19402008-12-20 23:49:58 +0000531
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000532 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Douglas Gregor86f19402008-12-20 23:49:58 +0000533 if (!FD) // FIXME: deal with other kinds of member expressions
John McCallefdb83e2010-05-07 21:00:08 +0000534 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000535
536 if (FD->getType()->isReferenceType())
John McCallefdb83e2010-05-07 21:00:08 +0000537 return false;
Eli Friedman2be58612009-05-30 21:09:44 +0000538
Eli Friedman82905742011-07-07 01:54:01 +0000539 unsigned i = FD->getFieldIndex();
Ken Dyckfb1e3bc2011-01-18 01:56:16 +0000540 Result.Offset += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
John McCallefdb83e2010-05-07 21:00:08 +0000541 return true;
Eli Friedman4efaa272008-11-12 09:44:48 +0000542}
543
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000544bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Anders Carlsson3068d112008-11-16 19:01:22 +0000545 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000546 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000547
Anders Carlsson3068d112008-11-16 19:01:22 +0000548 APSInt Index;
549 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +0000550 return false;
Anders Carlsson3068d112008-11-16 19:01:22 +0000551
Ken Dyck199c3d62010-01-11 17:06:35 +0000552 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(E->getType());
John McCallefdb83e2010-05-07 21:00:08 +0000553 Result.Offset += Index.getSExtValue() * ElementSize;
554 return true;
Anders Carlsson3068d112008-11-16 19:01:22 +0000555}
Eli Friedman4efaa272008-11-12 09:44:48 +0000556
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000557bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000558 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +0000559}
560
Eli Friedman4efaa272008-11-12 09:44:48 +0000561//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000562// Pointer Evaluation
563//===----------------------------------------------------------------------===//
564
Anders Carlssonc754aa62008-07-08 05:13:58 +0000565namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000566class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000567 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +0000568 LValue &Result;
569
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000570 bool Success(const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +0000571 Result.Base = E;
572 Result.Offset = CharUnits::Zero();
573 return true;
574 }
Anders Carlsson2bad1682008-07-08 14:30:00 +0000575public:
Mike Stump1eb44332009-09-09 15:08:12 +0000576
John McCallefdb83e2010-05-07 21:00:08 +0000577 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000578 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000579
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000580 bool Success(const APValue &V, const Expr *E) {
581 Result.setFrom(V);
582 return true;
583 }
584 bool Error(const Stmt *S) {
John McCallefdb83e2010-05-07 21:00:08 +0000585 return false;
Anders Carlsson2bad1682008-07-08 14:30:00 +0000586 }
587
John McCallefdb83e2010-05-07 21:00:08 +0000588 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000589 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +0000590 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000591 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +0000592 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000593 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000594 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000595 bool VisitCallExpr(const CallExpr *E);
596 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +0000597 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +0000598 return Success(E);
599 return false;
Mike Stumpb83d2872009-02-19 22:01:56 +0000600 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000601 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000602 { return Success((Expr*)0); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000603 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +0000604 { return Success((Expr*)0); }
John McCall56ca35d2011-02-17 10:25:35 +0000605
Eli Friedmanba98d6b2009-03-23 04:56:01 +0000606 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +0000607};
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000608} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +0000609
John McCallefdb83e2010-05-07 21:00:08 +0000610static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +0000611 assert(E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000612 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000613}
614
John McCallefdb83e2010-05-07 21:00:08 +0000615bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +0000616 if (E->getOpcode() != BO_Add &&
617 E->getOpcode() != BO_Sub)
John McCallefdb83e2010-05-07 21:00:08 +0000618 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000619
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000620 const Expr *PExp = E->getLHS();
621 const Expr *IExp = E->getRHS();
622 if (IExp->getType()->isPointerType())
623 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +0000624
John McCallefdb83e2010-05-07 21:00:08 +0000625 if (!EvaluatePointer(PExp, Result, Info))
626 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000627
John McCallefdb83e2010-05-07 21:00:08 +0000628 llvm::APSInt Offset;
629 if (!EvaluateInteger(IExp, Offset, Info))
630 return false;
631 int64_t AdditionalOffset
632 = Offset.isSigned() ? Offset.getSExtValue()
633 : static_cast<int64_t>(Offset.getZExtValue());
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000634
Daniel Dunbare0cdb4e2010-03-20 05:53:45 +0000635 // Compute the new offset in the appropriate width.
636
637 QualType PointeeType =
638 PExp->getType()->getAs<PointerType>()->getPointeeType();
John McCallefdb83e2010-05-07 21:00:08 +0000639 CharUnits SizeOfPointee;
Mike Stump1eb44332009-09-09 15:08:12 +0000640
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000641 // Explicitly handle GNU void* and function pointer arithmetic extensions.
642 if (PointeeType->isVoidType() || PointeeType->isFunctionType())
John McCallefdb83e2010-05-07 21:00:08 +0000643 SizeOfPointee = CharUnits::One();
Anders Carlsson4d4c50d2009-02-19 04:55:58 +0000644 else
John McCallefdb83e2010-05-07 21:00:08 +0000645 SizeOfPointee = Info.Ctx.getTypeSizeInChars(PointeeType);
Eli Friedman4efaa272008-11-12 09:44:48 +0000646
John McCall2de56d12010-08-25 11:45:40 +0000647 if (E->getOpcode() == BO_Add)
John McCallefdb83e2010-05-07 21:00:08 +0000648 Result.Offset += AdditionalOffset * SizeOfPointee;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000649 else
John McCallefdb83e2010-05-07 21:00:08 +0000650 Result.Offset -= AdditionalOffset * SizeOfPointee;
Eli Friedman4efaa272008-11-12 09:44:48 +0000651
John McCallefdb83e2010-05-07 21:00:08 +0000652 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000653}
Eli Friedman4efaa272008-11-12 09:44:48 +0000654
John McCallefdb83e2010-05-07 21:00:08 +0000655bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
656 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000657}
Mike Stump1eb44332009-09-09 15:08:12 +0000658
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000659
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000660bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
661 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000662
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000663 switch (E->getCastKind()) {
664 default:
665 break;
666
John McCall2de56d12010-08-25 11:45:40 +0000667 case CK_NoOp:
668 case CK_BitCast:
John McCall2de56d12010-08-25 11:45:40 +0000669 case CK_AnyPointerToObjCPointerCast:
670 case CK_AnyPointerToBlockPointerCast:
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000671 return Visit(SubExpr);
672
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000673 case CK_DerivedToBase:
674 case CK_UncheckedDerivedToBase: {
675 LValue BaseLV;
676 if (!EvaluatePointer(E->getSubExpr(), BaseLV, Info))
677 return false;
678
679 // Now figure out the necessary offset to add to the baseLV to get from
680 // the derived class to the base class.
Ken Dyck7c7f8202011-01-26 02:17:08 +0000681 CharUnits Offset = CharUnits::Zero();
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000682
683 QualType Ty = E->getSubExpr()->getType();
684 const CXXRecordDecl *DerivedDecl =
685 Ty->getAs<PointerType>()->getPointeeType()->getAsCXXRecordDecl();
686
687 for (CastExpr::path_const_iterator PathI = E->path_begin(),
688 PathE = E->path_end(); PathI != PathE; ++PathI) {
689 const CXXBaseSpecifier *Base = *PathI;
690
691 // FIXME: If the base is virtual, we'd need to determine the type of the
692 // most derived class and we don't support that right now.
693 if (Base->isVirtual())
694 return false;
695
696 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
697 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
698
Ken Dyck7c7f8202011-01-26 02:17:08 +0000699 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000700 DerivedDecl = BaseDecl;
701 }
702
703 Result.Base = BaseLV.getLValueBase();
Ken Dyck7c7f8202011-01-26 02:17:08 +0000704 Result.Offset = BaseLV.getLValueOffset() + Offset;
Anders Carlsson5c5a7642010-10-31 20:41:46 +0000705 return true;
706 }
707
John McCall404cd162010-11-13 01:35:44 +0000708 case CK_NullToPointer: {
709 Result.Base = 0;
710 Result.Offset = CharUnits::Zero();
711 return true;
712 }
713
John McCall2de56d12010-08-25 11:45:40 +0000714 case CK_IntegralToPointer: {
John McCallefdb83e2010-05-07 21:00:08 +0000715 APValue Value;
716 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +0000717 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +0000718
John McCallefdb83e2010-05-07 21:00:08 +0000719 if (Value.isInt()) {
Jay Foad9f71a8f2010-12-07 08:25:34 +0000720 Value.getInt() = Value.getInt().extOrTrunc((unsigned)Info.Ctx.getTypeSize(E->getType()));
John McCallefdb83e2010-05-07 21:00:08 +0000721 Result.Base = 0;
722 Result.Offset = CharUnits::fromQuantity(Value.getInt().getZExtValue());
723 return true;
724 } else {
725 // Cast is of an lvalue, no need to change value.
726 Result.Base = Value.getLValueBase();
727 Result.Offset = Value.getLValueOffset();
728 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000729 }
730 }
John McCall2de56d12010-08-25 11:45:40 +0000731 case CK_ArrayToPointerDecay:
732 case CK_FunctionToPointerDecay:
John McCallefdb83e2010-05-07 21:00:08 +0000733 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +0000734 }
735
John McCallefdb83e2010-05-07 21:00:08 +0000736 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000737}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000738
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000739bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Mike Stump1eb44332009-09-09 15:08:12 +0000740 if (E->isBuiltinCall(Info.Ctx) ==
David Chisnall0d13f6f2010-01-23 02:40:42 +0000741 Builtin::BI__builtin___CFStringMakeConstantString ||
742 E->isBuiltinCall(Info.Ctx) ==
743 Builtin::BI__builtin___NSStringMakeConstantString)
John McCallefdb83e2010-05-07 21:00:08 +0000744 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +0000745
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000746 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +0000747}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000748
749//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +0000750// Vector Evaluation
751//===----------------------------------------------------------------------===//
752
753namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000754 class VectorExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000755 : public ExprEvaluatorBase<VectorExprEvaluator, APValue> {
Eli Friedman91110ee2009-02-23 04:23:56 +0000756 APValue GetZeroVector(QualType VecType);
Nate Begeman59b5da62009-01-18 03:20:47 +0000757 public:
Mike Stump1eb44332009-09-09 15:08:12 +0000758
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000759 VectorExprEvaluator(EvalInfo &info) : ExprEvaluatorBaseTy(info) {}
Mike Stump1eb44332009-09-09 15:08:12 +0000760
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000761 APValue Success(const APValue &V, const Expr *E) { return V; }
762 APValue Error(const Expr *E) { return APValue(); }
Mike Stump1eb44332009-09-09 15:08:12 +0000763
Eli Friedman91110ee2009-02-23 04:23:56 +0000764 APValue VisitUnaryReal(const UnaryOperator *E)
765 { return Visit(E->getSubExpr()); }
766 APValue VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
767 { return GetZeroVector(E->getType()); }
Nate Begeman59b5da62009-01-18 03:20:47 +0000768 APValue VisitCastExpr(const CastExpr* E);
769 APValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
770 APValue VisitInitListExpr(const InitListExpr *E);
Eli Friedman91110ee2009-02-23 04:23:56 +0000771 APValue VisitUnaryImag(const UnaryOperator *E);
772 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +0000773 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +0000774 // shufflevector, ExtVectorElementExpr
775 // (Note that these require implementing conversions
776 // between vector types.)
Nate Begeman59b5da62009-01-18 03:20:47 +0000777 };
778} // end anonymous namespace
779
780static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
781 if (!E->getType()->isVectorType())
782 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000783 Result = VectorExprEvaluator(Info).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +0000784 return !Result.isUninit();
785}
786
787APValue VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
John McCall183700f2009-09-21 23:43:11 +0000788 const VectorType *VTy = E->getType()->getAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +0000789 QualType EltTy = VTy->getElementType();
790 unsigned NElts = VTy->getNumElements();
791 unsigned EltWidth = Info.Ctx.getTypeSize(EltTy);
Mike Stump1eb44332009-09-09 15:08:12 +0000792
Nate Begeman59b5da62009-01-18 03:20:47 +0000793 const Expr* SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +0000794 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +0000795
Eli Friedman46a52322011-03-25 00:43:55 +0000796 switch (E->getCastKind()) {
797 case CK_VectorSplat: {
798 APValue Result = APValue();
799 if (SETy->isIntegerType()) {
800 APSInt IntResult;
801 if (!EvaluateInteger(SE, IntResult, Info))
802 return APValue();
803 Result = APValue(IntResult);
804 } else if (SETy->isRealFloatingType()) {
805 APFloat F(0.0);
806 if (!EvaluateFloat(SE, F, Info))
807 return APValue();
808 Result = APValue(F);
809 } else {
Anders Carlsson0254e702011-03-25 11:22:47 +0000810 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000811 }
Nate Begemanc0b8b192009-07-01 07:50:47 +0000812
813 // Splat and create vector APValue.
814 llvm::SmallVector<APValue, 4> Elts(NElts, Result);
815 return APValue(&Elts[0], Elts.size());
Nate Begemane8c9e922009-06-26 18:22:18 +0000816 }
Eli Friedman46a52322011-03-25 00:43:55 +0000817 case CK_BitCast: {
818 if (SETy->isVectorType())
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000819 return Visit(SE);
Nate Begemanc0b8b192009-07-01 07:50:47 +0000820
Eli Friedman46a52322011-03-25 00:43:55 +0000821 if (!SETy->isIntegerType())
Anders Carlsson0254e702011-03-25 11:22:47 +0000822 return APValue();
Mike Stump1eb44332009-09-09 15:08:12 +0000823
Eli Friedman46a52322011-03-25 00:43:55 +0000824 APSInt Init;
825 if (!EvaluateInteger(SE, Init, Info))
Nate Begemanc0b8b192009-07-01 07:50:47 +0000826 return APValue();
827
Eli Friedman46a52322011-03-25 00:43:55 +0000828 assert((EltTy->isIntegerType() || EltTy->isRealFloatingType()) &&
829 "Vectors must be composed of ints or floats");
830
831 llvm::SmallVector<APValue, 4> Elts;
832 for (unsigned i = 0; i != NElts; ++i) {
833 APSInt Tmp = Init.extOrTrunc(EltWidth);
834
835 if (EltTy->isIntegerType())
836 Elts.push_back(APValue(Tmp));
837 else
838 Elts.push_back(APValue(APFloat(Tmp)));
839
840 Init >>= EltWidth;
841 }
842 return APValue(&Elts[0], Elts.size());
Nate Begemanc0b8b192009-07-01 07:50:47 +0000843 }
Eli Friedman46a52322011-03-25 00:43:55 +0000844 case CK_LValueToRValue:
845 case CK_NoOp:
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000846 return Visit(SE);
Eli Friedman46a52322011-03-25 00:43:55 +0000847 default:
Anders Carlsson0254e702011-03-25 11:22:47 +0000848 return APValue();
Eli Friedman46a52322011-03-25 00:43:55 +0000849 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000850}
851
Mike Stump1eb44332009-09-09 15:08:12 +0000852APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000853VectorExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000854 return this->Visit(E->getInitializer());
Nate Begeman59b5da62009-01-18 03:20:47 +0000855}
856
Mike Stump1eb44332009-09-09 15:08:12 +0000857APValue
Nate Begeman59b5da62009-01-18 03:20:47 +0000858VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
John McCall183700f2009-09-21 23:43:11 +0000859 const VectorType *VT = E->getType()->getAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +0000860 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +0000861 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +0000862
Nate Begeman59b5da62009-01-18 03:20:47 +0000863 QualType EltTy = VT->getElementType();
864 llvm::SmallVector<APValue, 4> Elements;
865
John McCalla7d6c222010-06-11 17:54:15 +0000866 // If a vector is initialized with a single element, that value
867 // becomes every element of the vector, not just the first.
868 // This is the behavior described in the IBM AltiVec documentation.
869 if (NumInits == 1) {
Tanya Lattnerb92ae0e2011-04-15 22:42:59 +0000870
871 // Handle the case where the vector is initialized by a another
872 // vector (OpenCL 6.1.6).
873 if (E->getInit(0)->getType()->isVectorType())
874 return this->Visit(const_cast<Expr*>(E->getInit(0)));
875
John McCalla7d6c222010-06-11 17:54:15 +0000876 APValue InitValue;
Nate Begeman59b5da62009-01-18 03:20:47 +0000877 if (EltTy->isIntegerType()) {
878 llvm::APSInt sInt(32);
John McCalla7d6c222010-06-11 17:54:15 +0000879 if (!EvaluateInteger(E->getInit(0), sInt, Info))
880 return APValue();
881 InitValue = APValue(sInt);
Nate Begeman59b5da62009-01-18 03:20:47 +0000882 } else {
883 llvm::APFloat f(0.0);
John McCalla7d6c222010-06-11 17:54:15 +0000884 if (!EvaluateFloat(E->getInit(0), f, Info))
885 return APValue();
886 InitValue = APValue(f);
887 }
888 for (unsigned i = 0; i < NumElements; i++) {
889 Elements.push_back(InitValue);
890 }
891 } else {
892 for (unsigned i = 0; i < NumElements; i++) {
893 if (EltTy->isIntegerType()) {
894 llvm::APSInt sInt(32);
895 if (i < NumInits) {
896 if (!EvaluateInteger(E->getInit(i), sInt, Info))
897 return APValue();
898 } else {
899 sInt = Info.Ctx.MakeIntValue(0, EltTy);
900 }
901 Elements.push_back(APValue(sInt));
Eli Friedman91110ee2009-02-23 04:23:56 +0000902 } else {
John McCalla7d6c222010-06-11 17:54:15 +0000903 llvm::APFloat f(0.0);
904 if (i < NumInits) {
905 if (!EvaluateFloat(E->getInit(i), f, Info))
906 return APValue();
907 } else {
908 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
909 }
910 Elements.push_back(APValue(f));
Eli Friedman91110ee2009-02-23 04:23:56 +0000911 }
Nate Begeman59b5da62009-01-18 03:20:47 +0000912 }
913 }
914 return APValue(&Elements[0], Elements.size());
915}
916
Mike Stump1eb44332009-09-09 15:08:12 +0000917APValue
Eli Friedman91110ee2009-02-23 04:23:56 +0000918VectorExprEvaluator::GetZeroVector(QualType T) {
John McCall183700f2009-09-21 23:43:11 +0000919 const VectorType *VT = T->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +0000920 QualType EltTy = VT->getElementType();
921 APValue ZeroElement;
922 if (EltTy->isIntegerType())
923 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
924 else
925 ZeroElement =
926 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
927
928 llvm::SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
929 return APValue(&Elements[0], Elements.size());
930}
931
Eli Friedman91110ee2009-02-23 04:23:56 +0000932APValue VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
933 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
934 Info.EvalResult.HasSideEffects = true;
935 return GetZeroVector(E->getType());
936}
937
Nate Begeman59b5da62009-01-18 03:20:47 +0000938//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000939// Integer Evaluation
940//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000941
942namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +0000943class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000944 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000945 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +0000946public:
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000947 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000948 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000949
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000950 bool Success(const llvm::APSInt &SI, const Expr *E) {
951 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000952 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000953 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000954 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +0000955 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000956 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000957 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000958 return true;
959 }
960
Daniel Dunbar131eb432009-02-19 09:06:44 +0000961 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000962 assert(E->getType()->isIntegralOrEnumerationType() &&
963 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000964 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +0000965 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000966 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +0000967 Result.getInt().setIsUnsigned(
968 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +0000969 return true;
970 }
971
972 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +0000973 assert(E->getType()->isIntegralOrEnumerationType() &&
974 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +0000975 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +0000976 return true;
977 }
978
Ken Dyck4f3bc8f2011-03-11 02:13:43 +0000979 bool Success(CharUnits Size, const Expr *E) {
980 return Success(Size.getQuantity(), E);
981 }
982
983
Anders Carlsson82206e22008-11-30 18:14:57 +0000984 bool Error(SourceLocation L, diag::kind D, const Expr *E) {
Chris Lattner32fea9d2008-11-12 07:43:42 +0000985 // Take the first error.
Anders Carlsson54da0492008-11-30 16:38:33 +0000986 if (Info.EvalResult.Diag == 0) {
987 Info.EvalResult.DiagLoc = L;
988 Info.EvalResult.Diag = D;
Anders Carlsson82206e22008-11-30 18:14:57 +0000989 Info.EvalResult.DiagExpr = E;
Chris Lattner32fea9d2008-11-12 07:43:42 +0000990 }
Chris Lattner54176fd2008-07-12 00:14:42 +0000991 return false;
Chris Lattner7a767782008-07-11 19:24:49 +0000992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000994 bool Success(const APValue &V, const Expr *E) {
995 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +0000996 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +0000997 bool Error(const Expr *E) {
Anders Carlsson0e8acbb2008-11-30 18:37:00 +0000998 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Anders Carlssonc754aa62008-07-08 05:13:58 +0000999 }
Mike Stump1eb44332009-09-09 15:08:12 +00001000
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001001 //===--------------------------------------------------------------------===//
1002 // Visitor Methods
1003 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00001004
Chris Lattner4c4867e2008-07-12 00:38:25 +00001005 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001006 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001007 }
1008 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001009 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00001010 }
Eli Friedman04309752009-11-24 05:28:59 +00001011
1012 bool CheckReferencedDecl(const Expr *E, const Decl *D);
1013 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001014 if (CheckReferencedDecl(E, E->getDecl()))
1015 return true;
1016
1017 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001018 }
1019 bool VisitMemberExpr(const MemberExpr *E) {
1020 if (CheckReferencedDecl(E, E->getMemberDecl())) {
1021 // Conservatively assume a MemberExpr will have side-effects
1022 Info.EvalResult.HasSideEffects = true;
1023 return true;
1024 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001025
1026 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00001027 }
1028
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001029 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001030 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001031 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00001032 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00001033
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001034 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001035 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00001036
Anders Carlsson3068d112008-11-16 19:01:22 +00001037 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001038 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001039 }
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Anders Carlsson3f704562008-12-21 22:39:40 +00001041 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001042 return Success(0, E);
Anders Carlsson3f704562008-12-21 22:39:40 +00001043 }
Mike Stump1eb44332009-09-09 15:08:12 +00001044
Douglas Gregored8abf12010-07-08 06:14:04 +00001045 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001046 return Success(0, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001047 }
1048
Eli Friedman664a1042009-02-27 04:45:43 +00001049 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
1050 return Success(0, E);
1051 }
1052
Sebastian Redl64b45f72009-01-05 20:52:13 +00001053 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00001054 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001055 }
1056
Francois Pichet6ad6f282010-12-07 00:08:36 +00001057 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
1058 return Success(E->getValue(), E);
1059 }
1060
John Wiegley21ff2e52011-04-28 00:16:57 +00001061 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
1062 return Success(E->getValue(), E);
1063 }
1064
John Wiegley55262202011-04-25 06:54:41 +00001065 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
1066 return Success(E->getValue(), E);
1067 }
1068
Eli Friedman722c7172009-02-28 03:59:05 +00001069 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001070 bool VisitUnaryImag(const UnaryOperator *E);
1071
Sebastian Redl295995c2010-09-10 20:55:47 +00001072 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00001073 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
1074
Chris Lattnerfcee0012008-07-11 21:24:13 +00001075private:
Ken Dyck8b752f12010-01-27 17:10:57 +00001076 CharUnits GetAlignOfExpr(const Expr *E);
1077 CharUnits GetAlignOfType(QualType T);
John McCall42c8f872010-05-10 23:27:23 +00001078 static QualType GetObjectType(const Expr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001079 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00001080 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001081};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001082} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00001083
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001084static bool EvaluateIntegerOrLValue(const Expr* E, APValue &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001085 assert(E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001086 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001087}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001088
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001089static bool EvaluateInteger(const Expr* E, APSInt &Result, EvalInfo &Info) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001090 assert(E->getType()->isIntegralOrEnumerationType());
John McCall7db7acb2010-05-07 05:46:35 +00001091
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00001092 APValue Val;
1093 if (!EvaluateIntegerOrLValue(E, Val, Info) || !Val.isInt())
1094 return false;
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001095 Result = Val.getInt();
1096 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00001097}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001098
Eli Friedman04309752009-11-24 05:28:59 +00001099bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001100 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001101 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00001102 // Check for signedness/width mismatches between E type and ECD value.
1103 bool SameSign = (ECD->getInitVal().isSigned()
1104 == E->getType()->isSignedIntegerOrEnumerationType());
1105 bool SameWidth = (ECD->getInitVal().getBitWidth()
1106 == Info.Ctx.getIntWidth(E->getType()));
1107 if (SameSign && SameWidth)
1108 return Success(ECD->getInitVal(), E);
1109 else {
1110 // Get rid of mismatch (otherwise Success assertions will fail)
1111 // by computing a new value matching the type of E.
1112 llvm::APSInt Val = ECD->getInitVal();
1113 if (!SameSign)
1114 Val.setIsSigned(!ECD->getInitVal().isSigned());
1115 if (!SameWidth)
1116 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
1117 return Success(Val, E);
1118 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00001119 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001120
1121 // In C++, const, non-volatile integers initialized with ICEs are ICEs.
Eli Friedmane1646da2009-03-30 23:39:01 +00001122 // In C, they can also be folded, although they are not ICEs.
Douglas Gregorcf3293e2009-11-01 20:32:48 +00001123 if (Info.Ctx.getCanonicalType(E->getType()).getCVRQualifiers()
1124 == Qualifiers::Const) {
Anders Carlssonf6b60252010-02-03 21:58:41 +00001125
1126 if (isa<ParmVarDecl>(D))
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001127 return false;
Anders Carlssonf6b60252010-02-03 21:58:41 +00001128
Eli Friedman04309752009-11-24 05:28:59 +00001129 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
Sebastian Redl31310a22010-02-01 20:16:42 +00001130 if (const Expr *Init = VD->getAnyInitializer()) {
Eli Friedmanc0131182009-12-03 20:31:57 +00001131 if (APValue *V = VD->getEvaluatedValue()) {
1132 if (V->isInt())
1133 return Success(V->getInt(), E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001134 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001135 }
1136
1137 if (VD->isEvaluatingValue())
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001138 return false;
Eli Friedmanc0131182009-12-03 20:31:57 +00001139
1140 VD->setEvaluatingValue();
1141
Eli Friedmana7dedf72010-09-06 00:10:32 +00001142 Expr::EvalResult EResult;
1143 if (Init->Evaluate(EResult, Info.Ctx) && !EResult.HasSideEffects &&
1144 EResult.Val.isInt()) {
Douglas Gregor78d15832009-05-26 18:54:04 +00001145 // Cache the evaluated value in the variable declaration.
Eli Friedmana7dedf72010-09-06 00:10:32 +00001146 Result = EResult.Val;
Eli Friedmanc0131182009-12-03 20:31:57 +00001147 VD->setEvaluatedValue(Result);
Douglas Gregor78d15832009-05-26 18:54:04 +00001148 return true;
1149 }
1150
Eli Friedmanc0131182009-12-03 20:31:57 +00001151 VD->setEvaluatedValue(APValue());
Douglas Gregor78d15832009-05-26 18:54:04 +00001152 }
Sebastian Redlb2bc62b2009-02-08 15:51:17 +00001153 }
1154 }
1155
Chris Lattner4c4867e2008-07-12 00:38:25 +00001156 // Otherwise, random variable references are not constants.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001157 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00001158}
1159
Chris Lattnera4d55d82008-10-06 06:40:35 +00001160/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
1161/// as GCC.
1162static int EvaluateBuiltinClassifyType(const CallExpr *E) {
1163 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00001164 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00001165 enum gcc_type_class {
1166 no_type_class = -1,
1167 void_type_class, integer_type_class, char_type_class,
1168 enumeral_type_class, boolean_type_class,
1169 pointer_type_class, reference_type_class, offset_type_class,
1170 real_type_class, complex_type_class,
1171 function_type_class, method_type_class,
1172 record_type_class, union_type_class,
1173 array_type_class, string_type_class,
1174 lang_type_class
1175 };
Mike Stump1eb44332009-09-09 15:08:12 +00001176
1177 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00001178 // ideal, however it is what gcc does.
1179 if (E->getNumArgs() == 0)
1180 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Chris Lattnera4d55d82008-10-06 06:40:35 +00001182 QualType ArgTy = E->getArg(0)->getType();
1183 if (ArgTy->isVoidType())
1184 return void_type_class;
1185 else if (ArgTy->isEnumeralType())
1186 return enumeral_type_class;
1187 else if (ArgTy->isBooleanType())
1188 return boolean_type_class;
1189 else if (ArgTy->isCharType())
1190 return string_type_class; // gcc doesn't appear to use char_type_class
1191 else if (ArgTy->isIntegerType())
1192 return integer_type_class;
1193 else if (ArgTy->isPointerType())
1194 return pointer_type_class;
1195 else if (ArgTy->isReferenceType())
1196 return reference_type_class;
1197 else if (ArgTy->isRealType())
1198 return real_type_class;
1199 else if (ArgTy->isComplexType())
1200 return complex_type_class;
1201 else if (ArgTy->isFunctionType())
1202 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00001203 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00001204 return record_type_class;
1205 else if (ArgTy->isUnionType())
1206 return union_type_class;
1207 else if (ArgTy->isArrayType())
1208 return array_type_class;
1209 else if (ArgTy->isUnionType())
1210 return union_type_class;
1211 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
1212 assert(0 && "CallExpr::isBuiltinClassifyType(): unimplemented type");
1213 return -1;
1214}
1215
John McCall42c8f872010-05-10 23:27:23 +00001216/// Retrieves the "underlying object type" of the given expression,
1217/// as used by __builtin_object_size.
1218QualType IntExprEvaluator::GetObjectType(const Expr *E) {
1219 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
1220 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1221 return VD->getType();
1222 } else if (isa<CompoundLiteralExpr>(E)) {
1223 return E->getType();
1224 }
1225
1226 return QualType();
1227}
1228
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001229bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00001230 // TODO: Perhaps we should let LLVM lower this?
1231 LValue Base;
1232 if (!EvaluatePointer(E->getArg(0), Base, Info))
1233 return false;
1234
1235 // If we can prove the base is null, lower to zero now.
1236 const Expr *LVBase = Base.getLValueBase();
1237 if (!LVBase) return Success(0, E);
1238
1239 QualType T = GetObjectType(LVBase);
1240 if (T.isNull() ||
1241 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00001242 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00001243 T->isVariablyModifiedType() ||
1244 T->isDependentType())
1245 return false;
1246
1247 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
1248 CharUnits Offset = Base.getLValueOffset();
1249
1250 if (!Offset.isNegative() && Offset <= Size)
1251 Size -= Offset;
1252 else
1253 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001254 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00001255}
1256
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001257bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001258 switch (E->isBuiltinCall(Info.Ctx)) {
Chris Lattner019f4e82008-10-06 05:28:25 +00001259 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001260 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001261
1262 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00001263 if (TryEvaluateBuiltinObjectSize(E))
1264 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00001265
Eric Christopherb2aaf512010-01-19 22:58:35 +00001266 // If evaluating the argument has side-effects we can't determine
1267 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00001268 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Benjamin Kramer3f27b382010-01-03 18:18:37 +00001269 if (E->getArg(1)->EvaluateAsInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00001270 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00001271 return Success(0, E);
1272 }
Mike Stumpc4c90452009-10-27 22:09:17 +00001273
Mike Stump64eda9e2009-10-26 18:35:08 +00001274 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
1275 }
1276
Chris Lattner019f4e82008-10-06 05:28:25 +00001277 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001278 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00001279
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001280 case Builtin::BI__builtin_constant_p:
Chris Lattner019f4e82008-10-06 05:28:25 +00001281 // __builtin_constant_p always has one operand: it returns true if that
1282 // operand can be folded, false otherwise.
Daniel Dunbar131eb432009-02-19 09:06:44 +00001283 return Success(E->getArg(0)->isEvaluatable(Info.Ctx), E);
Chris Lattner21fb98e2009-09-23 06:06:36 +00001284
1285 case Builtin::BI__builtin_eh_return_data_regno: {
1286 int Operand = E->getArg(0)->EvaluateAsInt(Info.Ctx).getZExtValue();
1287 Operand = Info.Ctx.Target.getEHDataRegisterNumber(Operand);
1288 return Success(Operand, E);
1289 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00001290
1291 case Builtin::BI__builtin_expect:
1292 return Visit(E->getArg(0));
Douglas Gregor5726d402010-09-10 06:27:15 +00001293
1294 case Builtin::BIstrlen:
1295 case Builtin::BI__builtin_strlen:
1296 // As an extension, we support strlen() and __builtin_strlen() as constant
1297 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001298 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00001299 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
1300 // The string literal may have embedded null characters. Find the first
1301 // one and truncate there.
1302 llvm::StringRef Str = S->getString();
1303 llvm::StringRef::size_type Pos = Str.find(0);
1304 if (Pos != llvm::StringRef::npos)
1305 Str = Str.substr(0, Pos);
1306
1307 return Success(Str.size(), E);
1308 }
1309
1310 return Error(E->getLocStart(), diag::note_invalid_subexpr_in_ice, E);
Chris Lattner019f4e82008-10-06 05:28:25 +00001311 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00001312}
Anders Carlsson650c92f2008-07-08 15:34:11 +00001313
Chris Lattnerb542afe2008-07-11 19:10:17 +00001314bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001315 if (E->getOpcode() == BO_Comma) {
Anders Carlsson027f62e2008-12-01 02:07:06 +00001316 if (!Visit(E->getRHS()))
1317 return false;
Anders Carlsson4fdfb092008-12-01 06:44:05 +00001318
Eli Friedman33ef1452009-02-26 10:19:36 +00001319 // If we can't evaluate the LHS, it might have side effects;
1320 // conservatively mark it.
1321 if (!E->getLHS()->isEvaluatable(Info.Ctx))
1322 Info.EvalResult.HasSideEffects = true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001323
Anders Carlsson027f62e2008-12-01 02:07:06 +00001324 return true;
Eli Friedmana6afa762008-11-13 06:09:17 +00001325 }
1326
1327 if (E->isLogicalOp()) {
1328 // These need to be handled specially because the operands aren't
1329 // necessarily integral
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001330 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00001331
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001332 if (HandleConversionToBool(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00001333 // We were able to evaluate the LHS, see if we can get away with not
1334 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00001335 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001336 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001337
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001338 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00001339 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001340 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001341 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00001342 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001343 }
1344 } else {
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001345 if (HandleConversionToBool(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001346 // We can't evaluate the LHS; however, sometimes the result
1347 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
John McCall2de56d12010-08-25 11:45:40 +00001348 if (rhsResult == (E->getOpcode() == BO_LOr) ||
1349 !rhsResult == (E->getOpcode() == BO_LAnd)) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00001350 // Since we weren't able to evaluate the left hand side, it
Anders Carlssonfcb4d092008-11-30 16:51:17 +00001351 // must have had side effects.
1352 Info.EvalResult.HasSideEffects = true;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001353
1354 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00001355 }
1356 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00001357 }
Eli Friedmana6afa762008-11-13 06:09:17 +00001358
Eli Friedmana6afa762008-11-13 06:09:17 +00001359 return false;
1360 }
1361
Anders Carlsson286f85e2008-11-16 07:17:21 +00001362 QualType LHSTy = E->getLHS()->getType();
1363 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00001364
1365 if (LHSTy->isAnyComplexType()) {
1366 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00001367 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00001368
1369 if (!EvaluateComplex(E->getLHS(), LHS, Info))
1370 return false;
1371
1372 if (!EvaluateComplex(E->getRHS(), RHS, Info))
1373 return false;
1374
1375 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001376 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001377 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00001378 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00001379 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
1380
John McCall2de56d12010-08-25 11:45:40 +00001381 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001382 return Success((CR_r == APFloat::cmpEqual &&
1383 CR_i == APFloat::cmpEqual), E);
1384 else {
John McCall2de56d12010-08-25 11:45:40 +00001385 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001386 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00001387 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001388 CR_r == APFloat::cmpLessThan ||
1389 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00001390 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00001391 CR_i == APFloat::cmpLessThan ||
1392 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00001393 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001394 } else {
John McCall2de56d12010-08-25 11:45:40 +00001395 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00001396 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
1397 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
1398 else {
John McCall2de56d12010-08-25 11:45:40 +00001399 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00001400 "Invalid compex comparison.");
1401 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
1402 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
1403 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00001404 }
1405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Anders Carlsson286f85e2008-11-16 07:17:21 +00001407 if (LHSTy->isRealFloatingType() &&
1408 RHSTy->isRealFloatingType()) {
1409 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00001410
Anders Carlsson286f85e2008-11-16 07:17:21 +00001411 if (!EvaluateFloat(E->getRHS(), RHS, Info))
1412 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Anders Carlsson286f85e2008-11-16 07:17:21 +00001414 if (!EvaluateFloat(E->getLHS(), LHS, Info))
1415 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001416
Anders Carlsson286f85e2008-11-16 07:17:21 +00001417 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00001418
Anders Carlsson286f85e2008-11-16 07:17:21 +00001419 switch (E->getOpcode()) {
1420 default:
1421 assert(0 && "Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00001422 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001423 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001424 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001425 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00001426 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001427 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001428 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00001429 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00001430 E);
John McCall2de56d12010-08-25 11:45:40 +00001431 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00001432 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00001433 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00001434 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00001435 || CR == APFloat::cmpLessThan
1436 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00001437 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00001438 }
Mike Stump1eb44332009-09-09 15:08:12 +00001439
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001440 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
John McCall2de56d12010-08-25 11:45:40 +00001441 if (E->getOpcode() == BO_Sub || E->isEqualityOp()) {
John McCallefdb83e2010-05-07 21:00:08 +00001442 LValue LHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001443 if (!EvaluatePointer(E->getLHS(), LHSValue, Info))
1444 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001445
John McCallefdb83e2010-05-07 21:00:08 +00001446 LValue RHSValue;
Anders Carlsson3068d112008-11-16 19:01:22 +00001447 if (!EvaluatePointer(E->getRHS(), RHSValue, Info))
1448 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00001449
Eli Friedman5bc86102009-06-14 02:17:33 +00001450 // Reject any bases from the normal codepath; we special-case comparisons
1451 // to null.
1452 if (LHSValue.getLValueBase()) {
1453 if (!E->isEqualityOp())
1454 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001455 if (RHSValue.getLValueBase() || !RHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001456 return false;
1457 bool bres;
1458 if (!EvalPointerValueAsBool(LHSValue, bres))
1459 return false;
John McCall2de56d12010-08-25 11:45:40 +00001460 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001461 } else if (RHSValue.getLValueBase()) {
1462 if (!E->isEqualityOp())
1463 return false;
Ken Dycka7305832010-01-15 12:37:54 +00001464 if (LHSValue.getLValueBase() || !LHSValue.getLValueOffset().isZero())
Eli Friedman5bc86102009-06-14 02:17:33 +00001465 return false;
1466 bool bres;
1467 if (!EvalPointerValueAsBool(RHSValue, bres))
1468 return false;
John McCall2de56d12010-08-25 11:45:40 +00001469 return Success(bres ^ (E->getOpcode() == BO_EQ), E);
Eli Friedman5bc86102009-06-14 02:17:33 +00001470 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001471
John McCall2de56d12010-08-25 11:45:40 +00001472 if (E->getOpcode() == BO_Sub) {
Chris Lattner4992bdd2010-04-20 17:13:14 +00001473 QualType Type = E->getLHS()->getType();
1474 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00001475
Ken Dycka7305832010-01-15 12:37:54 +00001476 CharUnits ElementSize = CharUnits::One();
Eli Friedmance1bca72009-06-04 20:23:20 +00001477 if (!ElementType->isVoidType() && !ElementType->isFunctionType())
Ken Dycka7305832010-01-15 12:37:54 +00001478 ElementSize = Info.Ctx.getTypeSizeInChars(ElementType);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001479
Ken Dycka7305832010-01-15 12:37:54 +00001480 CharUnits Diff = LHSValue.getLValueOffset() -
1481 RHSValue.getLValueOffset();
1482 return Success(Diff / ElementSize, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001483 }
1484 bool Result;
John McCall2de56d12010-08-25 11:45:40 +00001485 if (E->getOpcode() == BO_EQ) {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001486 Result = LHSValue.getLValueOffset() == RHSValue.getLValueOffset();
Eli Friedman267c0ab2009-04-29 20:29:43 +00001487 } else {
Eli Friedmanad02d7d2009-04-28 19:17:36 +00001488 Result = LHSValue.getLValueOffset() != RHSValue.getLValueOffset();
1489 }
1490 return Success(Result, E);
Anders Carlsson3068d112008-11-16 19:01:22 +00001491 }
1492 }
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001493 if (!LHSTy->isIntegralOrEnumerationType() ||
1494 !RHSTy->isIntegralOrEnumerationType()) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001495 // We can't continue from here for non-integral types, and they
1496 // could potentially confuse the following operations.
Eli Friedmana6afa762008-11-13 06:09:17 +00001497 return false;
1498 }
1499
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001500 // The LHS of a constant expr is always evaluated and needed.
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001501 if (!Visit(E->getLHS()))
Chris Lattner54176fd2008-07-12 00:14:42 +00001502 return false; // error in subexpression.
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00001503
Eli Friedman42edd0d2009-03-24 01:14:50 +00001504 APValue RHSVal;
1505 if (!EvaluateIntegerOrLValue(E->getRHS(), RHSVal, Info))
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001506 return false;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001507
1508 // Handle cases like (unsigned long)&a + 4.
1509 if (E->isAdditiveOp() && Result.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001510 CharUnits Offset = Result.getLValueOffset();
1511 CharUnits AdditionalOffset = CharUnits::fromQuantity(
1512 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00001513 if (E->getOpcode() == BO_Add)
Ken Dycka7305832010-01-15 12:37:54 +00001514 Offset += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00001515 else
Ken Dycka7305832010-01-15 12:37:54 +00001516 Offset -= AdditionalOffset;
1517 Result = APValue(Result.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001518 return true;
1519 }
1520
1521 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00001522 if (E->getOpcode() == BO_Add &&
Eli Friedman42edd0d2009-03-24 01:14:50 +00001523 RHSVal.isLValue() && Result.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00001524 CharUnits Offset = RHSVal.getLValueOffset();
1525 Offset += CharUnits::fromQuantity(Result.getInt().getZExtValue());
1526 Result = APValue(RHSVal.getLValueBase(), Offset);
Eli Friedman42edd0d2009-03-24 01:14:50 +00001527 return true;
1528 }
1529
1530 // All the following cases expect both operands to be an integer
1531 if (!Result.isInt() || !RHSVal.isInt())
Chris Lattnerb542afe2008-07-11 19:10:17 +00001532 return false;
Eli Friedmana6afa762008-11-13 06:09:17 +00001533
Eli Friedman42edd0d2009-03-24 01:14:50 +00001534 APSInt& RHS = RHSVal.getInt();
1535
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001536 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00001537 default:
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001538 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001539 case BO_Mul: return Success(Result.getInt() * RHS, E);
1540 case BO_Add: return Success(Result.getInt() + RHS, E);
1541 case BO_Sub: return Success(Result.getInt() - RHS, E);
1542 case BO_And: return Success(Result.getInt() & RHS, E);
1543 case BO_Xor: return Success(Result.getInt() ^ RHS, E);
1544 case BO_Or: return Success(Result.getInt() | RHS, E);
1545 case BO_Div:
Chris Lattner54176fd2008-07-12 00:14:42 +00001546 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001547 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001548 return Success(Result.getInt() / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001549 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00001550 if (RHS == 0)
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001551 return Error(E->getOperatorLoc(), diag::note_expr_divide_by_zero, E);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001552 return Success(Result.getInt() % RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00001553 case BO_Shl: {
John McCall091f23f2010-11-09 22:22:12 +00001554 // During constant-folding, a negative shift is an opposite shift.
1555 if (RHS.isSigned() && RHS.isNegative()) {
1556 RHS = -RHS;
1557 goto shift_right;
1558 }
1559
1560 shift_left:
1561 unsigned SA
1562 = (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001563 return Success(Result.getInt() << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001564 }
John McCall2de56d12010-08-25 11:45:40 +00001565 case BO_Shr: {
John McCall091f23f2010-11-09 22:22:12 +00001566 // During constant-folding, a negative shift is an opposite shift.
1567 if (RHS.isSigned() && RHS.isNegative()) {
1568 RHS = -RHS;
1569 goto shift_left;
1570 }
1571
1572 shift_right:
Mike Stump1eb44332009-09-09 15:08:12 +00001573 unsigned SA =
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001574 (unsigned) RHS.getLimitedValue(Result.getInt().getBitWidth()-1);
1575 return Success(Result.getInt() >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001576 }
Mike Stump1eb44332009-09-09 15:08:12 +00001577
John McCall2de56d12010-08-25 11:45:40 +00001578 case BO_LT: return Success(Result.getInt() < RHS, E);
1579 case BO_GT: return Success(Result.getInt() > RHS, E);
1580 case BO_LE: return Success(Result.getInt() <= RHS, E);
1581 case BO_GE: return Success(Result.getInt() >= RHS, E);
1582 case BO_EQ: return Success(Result.getInt() == RHS, E);
1583 case BO_NE: return Success(Result.getInt() != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00001584 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001585}
1586
Ken Dyck8b752f12010-01-27 17:10:57 +00001587CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00001588 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1589 // the result is the size of the referenced type."
1590 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1591 // result shall be the alignment of the referenced type."
1592 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
1593 T = Ref->getPointeeType();
1594
Eli Friedman2be58612009-05-30 21:09:44 +00001595 // __alignof is defined to return the preferred alignment.
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001596 return Info.Ctx.toCharUnitsFromBits(
1597 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00001598}
1599
Ken Dyck8b752f12010-01-27 17:10:57 +00001600CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00001601 E = E->IgnoreParens();
1602
1603 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00001604 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00001605 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001606 return Info.Ctx.getDeclAlign(DRE->getDecl(),
1607 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00001608
Chris Lattneraf707ab2009-01-24 21:53:27 +00001609 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00001610 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
1611 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00001612
Chris Lattnere9feb472009-01-24 21:09:06 +00001613 return GetAlignOfType(E->getType());
1614}
1615
1616
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001617/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
1618/// a result as the expression's type.
1619bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
1620 const UnaryExprOrTypeTraitExpr *E) {
1621 switch(E->getKind()) {
1622 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00001623 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001624 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001625 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00001626 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00001627 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00001628
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001629 case UETT_VecStep: {
1630 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00001631
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001632 if (Ty->isVectorType()) {
1633 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00001634
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001635 // The vec_step built-in functions that take a 3-component
1636 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1637 if (n == 3)
1638 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001639
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001640 return Success(n, E);
1641 } else
1642 return Success(1, E);
1643 }
1644
1645 case UETT_SizeOf: {
1646 QualType SrcTy = E->getTypeOfArgument();
1647 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1648 // the result is the size of the referenced type."
1649 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
1650 // result shall be the alignment of the referenced type."
1651 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
1652 SrcTy = Ref->getPointeeType();
1653
1654 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1655 // extension.
1656 if (SrcTy->isVoidType() || SrcTy->isFunctionType())
1657 return Success(1, E);
1658
1659 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
1660 if (!SrcTy->isConstantSizeType())
1661 return false;
1662
1663 // Get information about the size.
1664 return Success(Info.Ctx.getTypeSizeInChars(SrcTy), E);
1665 }
1666 }
1667
1668 llvm_unreachable("unknown expr/type trait");
1669 return false;
Chris Lattnerfcee0012008-07-11 21:24:13 +00001670}
1671
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001672bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001673 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001674 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001675 if (n == 0)
1676 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001677 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001678 for (unsigned i = 0; i != n; ++i) {
1679 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
1680 switch (ON.getKind()) {
1681 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001682 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001683 APSInt IdxResult;
1684 if (!EvaluateInteger(Idx, IdxResult, Info))
1685 return false;
1686 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
1687 if (!AT)
1688 return false;
1689 CurrentType = AT->getElementType();
1690 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
1691 Result += IdxResult.getSExtValue() * ElementSize;
1692 break;
1693 }
1694
1695 case OffsetOfExpr::OffsetOfNode::Field: {
1696 FieldDecl *MemberDecl = ON.getField();
1697 const RecordType *RT = CurrentType->getAs<RecordType>();
1698 if (!RT)
1699 return false;
1700 RecordDecl *RD = RT->getDecl();
1701 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00001702 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001703 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00001704 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001705 CurrentType = MemberDecl->getType().getNonReferenceType();
1706 break;
1707 }
1708
1709 case OffsetOfExpr::OffsetOfNode::Identifier:
1710 llvm_unreachable("dependent __builtin_offsetof");
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001711 return false;
1712
1713 case OffsetOfExpr::OffsetOfNode::Base: {
1714 CXXBaseSpecifier *BaseSpec = ON.getBase();
1715 if (BaseSpec->isVirtual())
1716 return false;
1717
1718 // Find the layout of the class whose base we are looking into.
1719 const RecordType *RT = CurrentType->getAs<RecordType>();
1720 if (!RT)
1721 return false;
1722 RecordDecl *RD = RT->getDecl();
1723 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
1724
1725 // Find the base class itself.
1726 CurrentType = BaseSpec->getType();
1727 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1728 if (!BaseRT)
1729 return false;
1730
1731 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00001732 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00001733 break;
1734 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001735 }
1736 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001737 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001738}
1739
Chris Lattnerb542afe2008-07-11 19:10:17 +00001740bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00001741 if (E->getOpcode() == UO_LNot) {
Eli Friedmana6afa762008-11-13 06:09:17 +00001742 // LNot's operand isn't necessarily an integer, so we handle it specially.
1743 bool bres;
1744 if (!HandleConversionToBool(E->getSubExpr(), bres, Info))
1745 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001746 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00001747 }
1748
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001749 // Only handle integral operations...
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001750 if (!E->getSubExpr()->getType()->isIntegralOrEnumerationType())
Daniel Dunbar4fff4812009-02-21 18:14:20 +00001751 return false;
1752
Chris Lattner87eae5e2008-07-11 22:52:41 +00001753 // Get the operand value into 'Result'.
1754 if (!Visit(E->getSubExpr()))
Chris Lattner75a48812008-07-11 22:15:16 +00001755 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001756
Chris Lattner75a48812008-07-11 22:15:16 +00001757 switch (E->getOpcode()) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00001758 default:
Chris Lattner75a48812008-07-11 22:15:16 +00001759 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1760 // See C99 6.6p3.
Anders Carlsson0e8acbb2008-11-30 18:37:00 +00001761 return Error(E->getOperatorLoc(), diag::note_invalid_subexpr_in_ice, E);
John McCall2de56d12010-08-25 11:45:40 +00001762 case UO_Extension:
Chris Lattner4c4867e2008-07-12 00:38:25 +00001763 // FIXME: Should extension allow i-c-e extension expressions in its scope?
1764 // If so, we could clear the diagnostic ID.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001765 return true;
John McCall2de56d12010-08-25 11:45:40 +00001766 case UO_Plus:
Mike Stump1eb44332009-09-09 15:08:12 +00001767 // The result is always just the subexpr.
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00001768 return true;
John McCall2de56d12010-08-25 11:45:40 +00001769 case UO_Minus:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001770 if (!Result.isInt()) return false;
1771 return Success(-Result.getInt(), E);
John McCall2de56d12010-08-25 11:45:40 +00001772 case UO_Not:
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001773 if (!Result.isInt()) return false;
1774 return Success(~Result.getInt(), E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001775 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001776}
Mike Stump1eb44332009-09-09 15:08:12 +00001777
Chris Lattner732b2232008-07-12 01:15:53 +00001778/// HandleCast - This is used to evaluate implicit or explicit casts where the
1779/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001780bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
1781 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00001782 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00001783 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00001784
Eli Friedman46a52322011-03-25 00:43:55 +00001785 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00001786 case CK_BaseToDerived:
1787 case CK_DerivedToBase:
1788 case CK_UncheckedDerivedToBase:
1789 case CK_Dynamic:
1790 case CK_ToUnion:
1791 case CK_ArrayToPointerDecay:
1792 case CK_FunctionToPointerDecay:
1793 case CK_NullToPointer:
1794 case CK_NullToMemberPointer:
1795 case CK_BaseToDerivedMemberPointer:
1796 case CK_DerivedToBaseMemberPointer:
1797 case CK_ConstructorConversion:
1798 case CK_IntegralToPointer:
1799 case CK_ToVoid:
1800 case CK_VectorSplat:
1801 case CK_IntegralToFloating:
1802 case CK_FloatingCast:
1803 case CK_AnyPointerToObjCPointerCast:
1804 case CK_AnyPointerToBlockPointerCast:
1805 case CK_ObjCObjectLValueCast:
1806 case CK_FloatingRealToComplex:
1807 case CK_FloatingComplexToReal:
1808 case CK_FloatingComplexCast:
1809 case CK_FloatingComplexToIntegralComplex:
1810 case CK_IntegralRealToComplex:
1811 case CK_IntegralComplexCast:
1812 case CK_IntegralComplexToFloatingComplex:
1813 llvm_unreachable("invalid cast kind for integral value");
1814
Eli Friedmane50c2972011-03-25 19:07:11 +00001815 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00001816 case CK_Dependent:
1817 case CK_GetObjCProperty:
1818 case CK_LValueBitCast:
1819 case CK_UserDefinedConversion:
John McCallf85e1932011-06-15 23:02:42 +00001820 case CK_ObjCProduceObject:
1821 case CK_ObjCConsumeObject:
John McCall7e5e5f42011-07-07 06:58:02 +00001822 case CK_ObjCReclaimReturnedObject:
Eli Friedman46a52322011-03-25 00:43:55 +00001823 return false;
1824
1825 case CK_LValueToRValue:
1826 case CK_NoOp:
1827 return Visit(E->getSubExpr());
1828
1829 case CK_MemberPointerToBoolean:
1830 case CK_PointerToBoolean:
1831 case CK_IntegralToBoolean:
1832 case CK_FloatingToBoolean:
1833 case CK_FloatingComplexToBoolean:
1834 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00001835 bool BoolResult;
1836 if (!HandleConversionToBool(SubExpr, BoolResult, Info))
1837 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00001838 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00001839 }
1840
Eli Friedman46a52322011-03-25 00:43:55 +00001841 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00001842 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001843 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001844
Eli Friedmanbe265702009-02-20 01:15:07 +00001845 if (!Result.isInt()) {
1846 // Only allow casts of lvalues if they are lossless.
1847 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
1848 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001849
Daniel Dunbardd211642009-02-19 22:24:01 +00001850 return Success(HandleIntToIntCast(DestType, SrcType,
Daniel Dunbar30c37f42009-02-19 20:17:33 +00001851 Result.getInt(), Info.Ctx), E);
Chris Lattner732b2232008-07-12 01:15:53 +00001852 }
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Eli Friedman46a52322011-03-25 00:43:55 +00001854 case CK_PointerToIntegral: {
John McCallefdb83e2010-05-07 21:00:08 +00001855 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00001856 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00001857 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001858
Daniel Dunbardd211642009-02-19 22:24:01 +00001859 if (LV.getLValueBase()) {
1860 // Only allow based lvalue casts if they are lossless.
1861 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
1862 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001863
John McCallefdb83e2010-05-07 21:00:08 +00001864 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00001865 return true;
1866 }
1867
Ken Dycka7305832010-01-15 12:37:54 +00001868 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
1869 SrcType);
Daniel Dunbardd211642009-02-19 22:24:01 +00001870 return Success(HandleIntToIntCast(DestType, SrcType, AsInt, Info.Ctx), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00001871 }
Eli Friedman4efaa272008-11-12 09:44:48 +00001872
Eli Friedman46a52322011-03-25 00:43:55 +00001873 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00001874 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00001875 if (!EvaluateComplex(SubExpr, C, Info))
1876 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00001877 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00001878 }
Eli Friedman2217c872009-02-22 11:46:18 +00001879
Eli Friedman46a52322011-03-25 00:43:55 +00001880 case CK_FloatingToIntegral: {
1881 APFloat F(0.0);
1882 if (!EvaluateFloat(SubExpr, F, Info))
1883 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00001884
Eli Friedman46a52322011-03-25 00:43:55 +00001885 return Success(HandleFloatToIntCast(DestType, SrcType, F, Info.Ctx), E);
1886 }
1887 }
Mike Stump1eb44332009-09-09 15:08:12 +00001888
Eli Friedman46a52322011-03-25 00:43:55 +00001889 llvm_unreachable("unknown cast resulting in integral value");
1890 return false;
Anders Carlssona25ae3d2008-07-08 14:35:21 +00001891}
Anders Carlsson2bad1682008-07-08 14:30:00 +00001892
Eli Friedman722c7172009-02-28 03:59:05 +00001893bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
1894 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001895 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001896 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1897 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1898 return Success(LV.getComplexIntReal(), E);
1899 }
1900
1901 return Visit(E->getSubExpr());
1902}
1903
Eli Friedman664a1042009-02-27 04:45:43 +00001904bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00001905 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00001906 ComplexValue LV;
Eli Friedman722c7172009-02-28 03:59:05 +00001907 if (!EvaluateComplex(E->getSubExpr(), LV, Info) || !LV.isComplexInt())
1908 return Error(E->getExprLoc(), diag::note_invalid_subexpr_in_ice, E);
1909 return Success(LV.getComplexIntImag(), E);
1910 }
1911
Eli Friedman664a1042009-02-27 04:45:43 +00001912 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
1913 Info.EvalResult.HasSideEffects = true;
1914 return Success(0, E);
1915}
1916
Douglas Gregoree8aff02011-01-04 17:33:58 +00001917bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
1918 return Success(E->getPackLength(), E);
1919}
1920
Sebastian Redl295995c2010-09-10 20:55:47 +00001921bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
1922 return Success(E->getValue(), E);
1923}
1924
Chris Lattnerf5eeb052008-07-11 18:11:29 +00001925//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001926// Float Evaluation
1927//===----------------------------------------------------------------------===//
1928
1929namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00001930class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001931 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001932 APFloat &Result;
1933public:
1934 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001935 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001936
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001937 bool Success(const APValue &V, const Expr *e) {
1938 Result = V.getFloat();
1939 return true;
1940 }
1941 bool Error(const Stmt *S) {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001942 return false;
1943 }
1944
Chris Lattner019f4e82008-10-06 05:28:25 +00001945 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001946
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00001947 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001948 bool VisitBinaryOperator(const BinaryOperator *E);
1949 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001950 bool VisitCastExpr(const CastExpr *E);
1951 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00001952
John McCallabd3a852010-05-07 22:08:54 +00001953 bool VisitUnaryReal(const UnaryOperator *E);
1954 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00001955
John McCall189d6ef2010-10-09 01:34:31 +00001956 bool VisitDeclRefExpr(const DeclRefExpr *E);
1957
John McCallabd3a852010-05-07 22:08:54 +00001958 // FIXME: Missing: array subscript of vector, member of vector,
1959 // ImplicitValueInitExpr
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001960};
1961} // end anonymous namespace
1962
1963static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00001964 assert(E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001965 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00001966}
1967
Jay Foad4ba2a172011-01-12 09:06:06 +00001968static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00001969 QualType ResultTy,
1970 const Expr *Arg,
1971 bool SNaN,
1972 llvm::APFloat &Result) {
1973 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
1974 if (!S) return false;
1975
1976 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
1977
1978 llvm::APInt fill;
1979
1980 // Treat empty strings as if they were zero.
1981 if (S->getString().empty())
1982 fill = llvm::APInt(32, 0);
1983 else if (S->getString().getAsInteger(0, fill))
1984 return false;
1985
1986 if (SNaN)
1987 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
1988 else
1989 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
1990 return true;
1991}
1992
Chris Lattner019f4e82008-10-06 05:28:25 +00001993bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Douglas Gregor3c385e52009-02-14 18:57:46 +00001994 switch (E->isBuiltinCall(Info.Ctx)) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00001995 default:
1996 return ExprEvaluatorBaseTy::VisitCallExpr(E);
1997
Chris Lattner019f4e82008-10-06 05:28:25 +00001998 case Builtin::BI__builtin_huge_val:
1999 case Builtin::BI__builtin_huge_valf:
2000 case Builtin::BI__builtin_huge_vall:
2001 case Builtin::BI__builtin_inf:
2002 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002003 case Builtin::BI__builtin_infl: {
2004 const llvm::fltSemantics &Sem =
2005 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00002006 Result = llvm::APFloat::getInf(Sem);
2007 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00002008 }
Mike Stump1eb44332009-09-09 15:08:12 +00002009
John McCalldb7b72a2010-02-28 13:00:19 +00002010 case Builtin::BI__builtin_nans:
2011 case Builtin::BI__builtin_nansf:
2012 case Builtin::BI__builtin_nansl:
2013 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2014 true, Result);
2015
Chris Lattner9e621712008-10-06 06:31:58 +00002016 case Builtin::BI__builtin_nan:
2017 case Builtin::BI__builtin_nanf:
2018 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00002019 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00002020 // can't constant fold it.
John McCalldb7b72a2010-02-28 13:00:19 +00002021 return TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
2022 false, Result);
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002023
2024 case Builtin::BI__builtin_fabs:
2025 case Builtin::BI__builtin_fabsf:
2026 case Builtin::BI__builtin_fabsl:
2027 if (!EvaluateFloat(E->getArg(0), Result, Info))
2028 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002029
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002030 if (Result.isNegative())
2031 Result.changeSign();
2032 return true;
2033
Mike Stump1eb44332009-09-09 15:08:12 +00002034 case Builtin::BI__builtin_copysign:
2035 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002036 case Builtin::BI__builtin_copysignl: {
2037 APFloat RHS(0.);
2038 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
2039 !EvaluateFloat(E->getArg(1), RHS, Info))
2040 return false;
2041 Result.copySign(RHS);
2042 return true;
2043 }
Chris Lattner019f4e82008-10-06 05:28:25 +00002044 }
2045}
2046
John McCall189d6ef2010-10-09 01:34:31 +00002047bool FloatExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002048 if (ExprEvaluatorBaseTy::VisitDeclRefExpr(E))
2049 return true;
2050
John McCall189d6ef2010-10-09 01:34:31 +00002051 const Decl *D = E->getDecl();
2052 if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D)) return false;
2053 const VarDecl *VD = cast<VarDecl>(D);
2054
2055 // Require the qualifiers to be const and not volatile.
2056 CanQualType T = Info.Ctx.getCanonicalType(E->getType());
2057 if (!T.isConstQualified() || T.isVolatileQualified())
2058 return false;
2059
2060 const Expr *Init = VD->getAnyInitializer();
2061 if (!Init) return false;
2062
2063 if (APValue *V = VD->getEvaluatedValue()) {
2064 if (V->isFloat()) {
2065 Result = V->getFloat();
2066 return true;
2067 }
2068 return false;
2069 }
2070
2071 if (VD->isEvaluatingValue())
2072 return false;
2073
2074 VD->setEvaluatingValue();
2075
2076 Expr::EvalResult InitResult;
2077 if (Init->Evaluate(InitResult, Info.Ctx) && !InitResult.HasSideEffects &&
2078 InitResult.Val.isFloat()) {
2079 // Cache the evaluated value in the variable declaration.
2080 Result = InitResult.Val.getFloat();
2081 VD->setEvaluatedValue(InitResult.Val);
2082 return true;
2083 }
2084
2085 VD->setEvaluatedValue(APValue());
2086 return false;
2087}
2088
John McCallabd3a852010-05-07 22:08:54 +00002089bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002090 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2091 ComplexValue CV;
2092 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2093 return false;
2094 Result = CV.FloatReal;
2095 return true;
2096 }
2097
2098 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00002099}
2100
2101bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00002102 if (E->getSubExpr()->getType()->isAnyComplexType()) {
2103 ComplexValue CV;
2104 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
2105 return false;
2106 Result = CV.FloatImag;
2107 return true;
2108 }
2109
2110 if (!E->getSubExpr()->isEvaluatable(Info.Ctx))
2111 Info.EvalResult.HasSideEffects = true;
2112 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
2113 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00002114 return true;
2115}
2116
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002117bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002118 if (E->getOpcode() == UO_Deref)
Nuno Lopesa468d342008-11-19 17:44:31 +00002119 return false;
2120
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002121 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
2122 return false;
2123
2124 switch (E->getOpcode()) {
2125 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002126 case UO_Plus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002127 return true;
John McCall2de56d12010-08-25 11:45:40 +00002128 case UO_Minus:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002129 Result.changeSign();
2130 return true;
2131 }
2132}
Chris Lattner019f4e82008-10-06 05:28:25 +00002133
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002134bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00002135 if (E->getOpcode() == BO_Comma) {
Eli Friedman7f92f032009-11-16 04:25:37 +00002136 if (!EvaluateFloat(E->getRHS(), Result, Info))
2137 return false;
2138
2139 // If we can't evaluate the LHS, it might have side effects;
2140 // conservatively mark it.
2141 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2142 Info.EvalResult.HasSideEffects = true;
2143
2144 return true;
2145 }
2146
Anders Carlsson96e93662010-10-31 01:21:47 +00002147 // We can't evaluate pointer-to-member operations.
2148 if (E->isPtrMemOp())
2149 return false;
2150
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002151 // FIXME: Diagnostics? I really don't understand how the warnings
2152 // and errors are supposed to work.
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00002153 APFloat RHS(0.0);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002154 if (!EvaluateFloat(E->getLHS(), Result, Info))
2155 return false;
2156 if (!EvaluateFloat(E->getRHS(), RHS, Info))
2157 return false;
2158
2159 switch (E->getOpcode()) {
2160 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002161 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002162 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
2163 return true;
John McCall2de56d12010-08-25 11:45:40 +00002164 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002165 Result.add(RHS, APFloat::rmNearestTiesToEven);
2166 return true;
John McCall2de56d12010-08-25 11:45:40 +00002167 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002168 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
2169 return true;
John McCall2de56d12010-08-25 11:45:40 +00002170 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002171 Result.divide(RHS, APFloat::rmNearestTiesToEven);
2172 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002173 }
2174}
2175
2176bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
2177 Result = E->getValue();
2178 return true;
2179}
2180
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002181bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
2182 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00002183
Eli Friedman2a523ee2011-03-25 00:54:52 +00002184 switch (E->getCastKind()) {
2185 default:
2186 return false;
2187
2188 case CK_LValueToRValue:
2189 case CK_NoOp:
2190 return Visit(SubExpr);
2191
2192 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002193 APSInt IntResult;
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00002194 if (!EvaluateInteger(SubExpr, IntResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00002195 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002196 Result = HandleIntToFloatCast(E->getType(), SubExpr->getType(),
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002197 IntResult, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002198 return true;
2199 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002200
2201 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00002202 if (!Visit(SubExpr))
2203 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00002204 Result = HandleFloatToFloatCast(E->getType(), SubExpr->getType(),
2205 Result, Info.Ctx);
Eli Friedman4efaa272008-11-12 09:44:48 +00002206 return true;
2207 }
John McCallf3ea8cf2010-11-14 08:17:51 +00002208
Eli Friedman2a523ee2011-03-25 00:54:52 +00002209 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00002210 ComplexValue V;
2211 if (!EvaluateComplex(SubExpr, V, Info))
2212 return false;
2213 Result = V.getComplexFloatReal();
2214 return true;
2215 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00002216 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002217
2218 return false;
2219}
2220
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002221bool FloatExprEvaluator::VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Eli Friedman4efaa272008-11-12 09:44:48 +00002222 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
2223 return true;
2224}
2225
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00002226//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002227// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002228//===----------------------------------------------------------------------===//
2229
2230namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002231class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002232 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00002233 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002234
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002235public:
John McCallf4cf1a12010-05-07 17:22:02 +00002236 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002237 : ExprEvaluatorBaseTy(info), Result(Result) {}
2238
2239 bool Success(const APValue &V, const Expr *e) {
2240 Result.setFrom(V);
2241 return true;
2242 }
2243 bool Error(const Expr *E) {
2244 return false;
2245 }
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002247 //===--------------------------------------------------------------------===//
2248 // Visitor Methods
2249 //===--------------------------------------------------------------------===//
2250
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002251 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002252
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002253 bool VisitCastExpr(const CastExpr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00002254
John McCallf4cf1a12010-05-07 17:22:02 +00002255 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002256 bool VisitUnaryOperator(const UnaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002257 // FIXME Missing: ImplicitValueInitExpr
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002258};
2259} // end anonymous namespace
2260
John McCallf4cf1a12010-05-07 17:22:02 +00002261static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
2262 EvalInfo &Info) {
John McCall7db7acb2010-05-07 05:46:35 +00002263 assert(E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002264 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002265}
2266
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002267bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
2268 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002269
2270 if (SubExpr->getType()->isRealFloatingType()) {
2271 Result.makeComplexFloat();
2272 APFloat &Imag = Result.FloatImag;
2273 if (!EvaluateFloat(SubExpr, Imag, Info))
2274 return false;
2275
2276 Result.FloatReal = APFloat(Imag.getSemantics());
2277 return true;
2278 } else {
2279 assert(SubExpr->getType()->isIntegerType() &&
2280 "Unexpected imaginary literal.");
2281
2282 Result.makeComplexInt();
2283 APSInt &Imag = Result.IntImag;
2284 if (!EvaluateInteger(SubExpr, Imag, Info))
2285 return false;
2286
2287 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
2288 return true;
2289 }
2290}
2291
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002292bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002293
John McCall8786da72010-12-14 17:51:41 +00002294 switch (E->getCastKind()) {
2295 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00002296 case CK_BaseToDerived:
2297 case CK_DerivedToBase:
2298 case CK_UncheckedDerivedToBase:
2299 case CK_Dynamic:
2300 case CK_ToUnion:
2301 case CK_ArrayToPointerDecay:
2302 case CK_FunctionToPointerDecay:
2303 case CK_NullToPointer:
2304 case CK_NullToMemberPointer:
2305 case CK_BaseToDerivedMemberPointer:
2306 case CK_DerivedToBaseMemberPointer:
2307 case CK_MemberPointerToBoolean:
2308 case CK_ConstructorConversion:
2309 case CK_IntegralToPointer:
2310 case CK_PointerToIntegral:
2311 case CK_PointerToBoolean:
2312 case CK_ToVoid:
2313 case CK_VectorSplat:
2314 case CK_IntegralCast:
2315 case CK_IntegralToBoolean:
2316 case CK_IntegralToFloating:
2317 case CK_FloatingToIntegral:
2318 case CK_FloatingToBoolean:
2319 case CK_FloatingCast:
2320 case CK_AnyPointerToObjCPointerCast:
2321 case CK_AnyPointerToBlockPointerCast:
2322 case CK_ObjCObjectLValueCast:
2323 case CK_FloatingComplexToReal:
2324 case CK_FloatingComplexToBoolean:
2325 case CK_IntegralComplexToReal:
2326 case CK_IntegralComplexToBoolean:
John McCallf85e1932011-06-15 23:02:42 +00002327 case CK_ObjCProduceObject:
2328 case CK_ObjCConsumeObject:
John McCall7e5e5f42011-07-07 06:58:02 +00002329 case CK_ObjCReclaimReturnedObject:
John McCall8786da72010-12-14 17:51:41 +00002330 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00002331
John McCall8786da72010-12-14 17:51:41 +00002332 case CK_LValueToRValue:
2333 case CK_NoOp:
2334 return Visit(E->getSubExpr());
2335
2336 case CK_Dependent:
2337 case CK_GetObjCProperty:
Eli Friedman46a52322011-03-25 00:43:55 +00002338 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00002339 case CK_UserDefinedConversion:
2340 return false;
2341
2342 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002343 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00002344 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002345 return false;
2346
John McCall8786da72010-12-14 17:51:41 +00002347 Result.makeComplexFloat();
2348 Result.FloatImag = APFloat(Real.getSemantics());
2349 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002350 }
2351
John McCall8786da72010-12-14 17:51:41 +00002352 case CK_FloatingComplexCast: {
2353 if (!Visit(E->getSubExpr()))
2354 return false;
2355
2356 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2357 QualType From
2358 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2359
2360 Result.FloatReal
2361 = HandleFloatToFloatCast(To, From, Result.FloatReal, Info.Ctx);
2362 Result.FloatImag
2363 = HandleFloatToFloatCast(To, From, Result.FloatImag, Info.Ctx);
2364 return true;
2365 }
2366
2367 case CK_FloatingComplexToIntegralComplex: {
2368 if (!Visit(E->getSubExpr()))
2369 return false;
2370
2371 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2372 QualType From
2373 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2374 Result.makeComplexInt();
2375 Result.IntReal = HandleFloatToIntCast(To, From, Result.FloatReal, Info.Ctx);
2376 Result.IntImag = HandleFloatToIntCast(To, From, Result.FloatImag, Info.Ctx);
2377 return true;
2378 }
2379
2380 case CK_IntegralRealToComplex: {
2381 APSInt &Real = Result.IntReal;
2382 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
2383 return false;
2384
2385 Result.makeComplexInt();
2386 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
2387 return true;
2388 }
2389
2390 case CK_IntegralComplexCast: {
2391 if (!Visit(E->getSubExpr()))
2392 return false;
2393
2394 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2395 QualType From
2396 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2397
2398 Result.IntReal = HandleIntToIntCast(To, From, Result.IntReal, Info.Ctx);
2399 Result.IntImag = HandleIntToIntCast(To, From, Result.IntImag, Info.Ctx);
2400 return true;
2401 }
2402
2403 case CK_IntegralComplexToFloatingComplex: {
2404 if (!Visit(E->getSubExpr()))
2405 return false;
2406
2407 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
2408 QualType From
2409 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
2410 Result.makeComplexFloat();
2411 Result.FloatReal = HandleIntToFloatCast(To, From, Result.IntReal, Info.Ctx);
2412 Result.FloatImag = HandleIntToFloatCast(To, From, Result.IntImag, Info.Ctx);
2413 return true;
2414 }
2415 }
2416
2417 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00002418 return false;
2419}
2420
John McCallf4cf1a12010-05-07 17:22:02 +00002421bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002422 if (E->getOpcode() == BO_Comma) {
2423 if (!Visit(E->getRHS()))
2424 return false;
2425
2426 // If we can't evaluate the LHS, it might have side effects;
2427 // conservatively mark it.
2428 if (!E->getLHS()->isEvaluatable(Info.Ctx))
2429 Info.EvalResult.HasSideEffects = true;
2430
2431 return true;
2432 }
John McCallf4cf1a12010-05-07 17:22:02 +00002433 if (!Visit(E->getLHS()))
2434 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002435
John McCallf4cf1a12010-05-07 17:22:02 +00002436 ComplexValue RHS;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002437 if (!EvaluateComplex(E->getRHS(), RHS, Info))
John McCallf4cf1a12010-05-07 17:22:02 +00002438 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002439
Daniel Dunbar3f279872009-01-29 01:32:56 +00002440 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
2441 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002442 switch (E->getOpcode()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002443 default: return false;
John McCall2de56d12010-08-25 11:45:40 +00002444 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002445 if (Result.isComplexFloat()) {
2446 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
2447 APFloat::rmNearestTiesToEven);
2448 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
2449 APFloat::rmNearestTiesToEven);
2450 } else {
2451 Result.getComplexIntReal() += RHS.getComplexIntReal();
2452 Result.getComplexIntImag() += RHS.getComplexIntImag();
2453 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002454 break;
John McCall2de56d12010-08-25 11:45:40 +00002455 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002456 if (Result.isComplexFloat()) {
2457 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
2458 APFloat::rmNearestTiesToEven);
2459 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
2460 APFloat::rmNearestTiesToEven);
2461 } else {
2462 Result.getComplexIntReal() -= RHS.getComplexIntReal();
2463 Result.getComplexIntImag() -= RHS.getComplexIntImag();
2464 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00002465 break;
John McCall2de56d12010-08-25 11:45:40 +00002466 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00002467 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00002468 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00002469 APFloat &LHS_r = LHS.getComplexFloatReal();
2470 APFloat &LHS_i = LHS.getComplexFloatImag();
2471 APFloat &RHS_r = RHS.getComplexFloatReal();
2472 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Daniel Dunbar3f279872009-01-29 01:32:56 +00002474 APFloat Tmp = LHS_r;
2475 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2476 Result.getComplexFloatReal() = Tmp;
2477 Tmp = LHS_i;
2478 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2479 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
2480
2481 Tmp = LHS_r;
2482 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2483 Result.getComplexFloatImag() = Tmp;
2484 Tmp = LHS_i;
2485 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2486 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
2487 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00002488 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00002489 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002490 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
2491 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00002492 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00002493 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
2494 LHS.getComplexIntImag() * RHS.getComplexIntReal());
2495 }
2496 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002497 case BO_Div:
2498 if (Result.isComplexFloat()) {
2499 ComplexValue LHS = Result;
2500 APFloat &LHS_r = LHS.getComplexFloatReal();
2501 APFloat &LHS_i = LHS.getComplexFloatImag();
2502 APFloat &RHS_r = RHS.getComplexFloatReal();
2503 APFloat &RHS_i = RHS.getComplexFloatImag();
2504 APFloat &Res_r = Result.getComplexFloatReal();
2505 APFloat &Res_i = Result.getComplexFloatImag();
2506
2507 APFloat Den = RHS_r;
2508 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2509 APFloat Tmp = RHS_i;
2510 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2511 Den.add(Tmp, APFloat::rmNearestTiesToEven);
2512
2513 Res_r = LHS_r;
2514 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2515 Tmp = LHS_i;
2516 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2517 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
2518 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
2519
2520 Res_i = LHS_i;
2521 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
2522 Tmp = LHS_r;
2523 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
2524 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
2525 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
2526 } else {
2527 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0) {
2528 // FIXME: what about diagnostics?
2529 return false;
2530 }
2531 ComplexValue LHS = Result;
2532 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
2533 RHS.getComplexIntImag() * RHS.getComplexIntImag();
2534 Result.getComplexIntReal() =
2535 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
2536 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
2537 Result.getComplexIntImag() =
2538 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
2539 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
2540 }
2541 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002542 }
2543
John McCallf4cf1a12010-05-07 17:22:02 +00002544 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00002545}
2546
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00002547bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
2548 // Get the operand value into 'Result'.
2549 if (!Visit(E->getSubExpr()))
2550 return false;
2551
2552 switch (E->getOpcode()) {
2553 default:
2554 // FIXME: what about diagnostics?
2555 return false;
2556 case UO_Extension:
2557 return true;
2558 case UO_Plus:
2559 // The result is always just the subexpr.
2560 return true;
2561 case UO_Minus:
2562 if (Result.isComplexFloat()) {
2563 Result.getComplexFloatReal().changeSign();
2564 Result.getComplexFloatImag().changeSign();
2565 }
2566 else {
2567 Result.getComplexIntReal() = -Result.getComplexIntReal();
2568 Result.getComplexIntImag() = -Result.getComplexIntImag();
2569 }
2570 return true;
2571 case UO_Not:
2572 if (Result.isComplexFloat())
2573 Result.getComplexFloatImag().changeSign();
2574 else
2575 Result.getComplexIntImag() = -Result.getComplexIntImag();
2576 return true;
2577 }
2578}
2579
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00002580//===----------------------------------------------------------------------===//
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002581// Top level Expr::Evaluate method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002582//===----------------------------------------------------------------------===//
2583
John McCall56ca35d2011-02-17 10:25:35 +00002584static bool Evaluate(EvalInfo &Info, const Expr *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002585 if (E->getType()->isVectorType()) {
2586 if (!EvaluateVector(E, Info.EvalResult.Val, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00002587 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00002588 } else if (E->getType()->isIntegralOrEnumerationType()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002589 if (!IntExprEvaluator(Info, Info.EvalResult.Val).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002590 return false;
John McCall56ca35d2011-02-17 10:25:35 +00002591 if (Info.EvalResult.Val.isLValue() &&
2592 !IsGlobalLValue(Info.EvalResult.Val.getLValueBase()))
John McCall0f2b6922010-07-07 05:08:32 +00002593 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002594 } else if (E->getType()->hasPointerRepresentation()) {
2595 LValue LV;
2596 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002597 return false;
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002598 if (!IsGlobalLValue(LV.Base))
John McCall42c8f872010-05-10 23:27:23 +00002599 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002600 LV.moveInto(Info.EvalResult.Val);
2601 } else if (E->getType()->isRealFloatingType()) {
2602 llvm::APFloat F(0.0);
2603 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002604 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002605
John McCallefdb83e2010-05-07 21:00:08 +00002606 Info.EvalResult.Val = APValue(F);
2607 } else if (E->getType()->isAnyComplexType()) {
2608 ComplexValue C;
2609 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002610 return false;
John McCallefdb83e2010-05-07 21:00:08 +00002611 C.moveInto(Info.EvalResult.Val);
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00002612 } else
Anders Carlsson9d4c1572008-11-22 22:56:32 +00002613 return false;
Anders Carlsson6dde0d52008-11-22 21:50:49 +00002614
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00002615 return true;
2616}
2617
John McCall56ca35d2011-02-17 10:25:35 +00002618/// Evaluate - Return true if this is a constant which we can fold using
2619/// any crazy technique (that has nothing to do with language standards) that
2620/// we want to. If this function returns true, it returns the folded constant
2621/// in Result.
2622bool Expr::Evaluate(EvalResult &Result, const ASTContext &Ctx) const {
2623 EvalInfo Info(Ctx, Result);
2624 return ::Evaluate(Info, this);
2625}
2626
Jay Foad4ba2a172011-01-12 09:06:06 +00002627bool Expr::EvaluateAsBooleanCondition(bool &Result,
2628 const ASTContext &Ctx) const {
John McCallcd7a4452010-01-05 23:42:56 +00002629 EvalResult Scratch;
2630 EvalInfo Info(Ctx, Scratch);
2631
2632 return HandleConversionToBool(this, Result, Info);
2633}
2634
Jay Foad4ba2a172011-01-12 09:06:06 +00002635bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00002636 EvalInfo Info(Ctx, Result);
2637
John McCallefdb83e2010-05-07 21:00:08 +00002638 LValue LV;
John McCall42c8f872010-05-10 23:27:23 +00002639 if (EvaluateLValue(this, LV, Info) &&
2640 !Result.HasSideEffects &&
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002641 IsGlobalLValue(LV.Base)) {
2642 LV.moveInto(Result.Val);
2643 return true;
2644 }
2645 return false;
2646}
2647
Jay Foad4ba2a172011-01-12 09:06:06 +00002648bool Expr::EvaluateAsAnyLValue(EvalResult &Result,
2649 const ASTContext &Ctx) const {
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002650 EvalInfo Info(Ctx, Result);
2651
2652 LValue LV;
2653 if (EvaluateLValue(this, LV, Info)) {
John McCallefdb83e2010-05-07 21:00:08 +00002654 LV.moveInto(Result.Val);
2655 return true;
2656 }
2657 return false;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00002658}
2659
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002660/// isEvaluatable - Call Evaluate to see if this expression can be constant
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002661/// folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00002662bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00002663 EvalResult Result;
2664 return Evaluate(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002665}
Anders Carlsson51fe9962008-11-22 21:04:56 +00002666
Jay Foad4ba2a172011-01-12 09:06:06 +00002667bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002668 Expr::EvalResult Result;
2669 EvalInfo Info(Ctx, Result);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002670 return HasSideEffect(Info).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00002671}
2672
Jay Foad4ba2a172011-01-12 09:06:06 +00002673APSInt Expr::EvaluateAsInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002674 EvalResult EvalResult;
2675 bool Result = Evaluate(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00002676 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00002677 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002678 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00002679
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002680 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00002681}
John McCalld905f5a2010-05-07 05:32:02 +00002682
Abramo Bagnarae17a6432010-05-14 17:07:14 +00002683 bool Expr::EvalResult::isGlobalLValue() const {
2684 assert(Val.isLValue());
2685 return IsGlobalLValue(Val.getLValueBase());
2686 }
2687
2688
John McCalld905f5a2010-05-07 05:32:02 +00002689/// isIntegerConstantExpr - this recursive routine will test if an expression is
2690/// an integer constant expression.
2691
2692/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
2693/// comma, etc
2694///
2695/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
2696/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
2697/// cast+dereference.
2698
2699// CheckICE - This function does the fundamental ICE checking: the returned
2700// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
2701// Note that to reduce code duplication, this helper does no evaluation
2702// itself; the caller checks whether the expression is evaluatable, and
2703// in the rare cases where CheckICE actually cares about the evaluated
2704// value, it calls into Evalute.
2705//
2706// Meanings of Val:
2707// 0: This expression is an ICE if it can be evaluated by Evaluate.
2708// 1: This expression is not an ICE, but if it isn't evaluated, it's
2709// a legal subexpression for an ICE. This return value is used to handle
2710// the comma operator in C99 mode.
2711// 2: This expression is not an ICE, and is not a legal subexpression for one.
2712
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002713namespace {
2714
John McCalld905f5a2010-05-07 05:32:02 +00002715struct ICEDiag {
2716 unsigned Val;
2717 SourceLocation Loc;
2718
2719 public:
2720 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
2721 ICEDiag() : Val(0) {}
2722};
2723
Dan Gohman3c46e8d2010-07-26 21:25:24 +00002724}
2725
2726static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00002727
2728static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
2729 Expr::EvalResult EVResult;
2730 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
2731 !EVResult.Val.isInt()) {
2732 return ICEDiag(2, E->getLocStart());
2733 }
2734 return NoDiag();
2735}
2736
2737static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
2738 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00002739 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00002740 return ICEDiag(2, E->getLocStart());
2741 }
2742
2743 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00002744#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00002745#define STMT(Node, Base) case Expr::Node##Class:
2746#define EXPR(Node, Base)
2747#include "clang/AST/StmtNodes.inc"
2748 case Expr::PredefinedExprClass:
2749 case Expr::FloatingLiteralClass:
2750 case Expr::ImaginaryLiteralClass:
2751 case Expr::StringLiteralClass:
2752 case Expr::ArraySubscriptExprClass:
2753 case Expr::MemberExprClass:
2754 case Expr::CompoundAssignOperatorClass:
2755 case Expr::CompoundLiteralExprClass:
2756 case Expr::ExtVectorElementExprClass:
2757 case Expr::InitListExprClass:
2758 case Expr::DesignatedInitExprClass:
2759 case Expr::ImplicitValueInitExprClass:
2760 case Expr::ParenListExprClass:
2761 case Expr::VAArgExprClass:
2762 case Expr::AddrLabelExprClass:
2763 case Expr::StmtExprClass:
2764 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00002765 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002766 case Expr::CXXDynamicCastExprClass:
2767 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00002768 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002769 case Expr::CXXNullPtrLiteralExprClass:
2770 case Expr::CXXThisExprClass:
2771 case Expr::CXXThrowExprClass:
2772 case Expr::CXXNewExprClass:
2773 case Expr::CXXDeleteExprClass:
2774 case Expr::CXXPseudoDestructorExprClass:
2775 case Expr::UnresolvedLookupExprClass:
2776 case Expr::DependentScopeDeclRefExprClass:
2777 case Expr::CXXConstructExprClass:
2778 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00002779 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00002780 case Expr::CXXTemporaryObjectExprClass:
2781 case Expr::CXXUnresolvedConstructExprClass:
2782 case Expr::CXXDependentScopeMemberExprClass:
2783 case Expr::UnresolvedMemberExprClass:
2784 case Expr::ObjCStringLiteralClass:
2785 case Expr::ObjCEncodeExprClass:
2786 case Expr::ObjCMessageExprClass:
2787 case Expr::ObjCSelectorExprClass:
2788 case Expr::ObjCProtocolExprClass:
2789 case Expr::ObjCIvarRefExprClass:
2790 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002791 case Expr::ObjCIsaExprClass:
2792 case Expr::ShuffleVectorExprClass:
2793 case Expr::BlockExprClass:
2794 case Expr::BlockDeclRefExprClass:
2795 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00002796 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00002797 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00002798 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002799 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00002800 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00002801 case Expr::MaterializeTemporaryExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002802 return ICEDiag(2, E->getLocStart());
2803
Douglas Gregoree8aff02011-01-04 17:33:58 +00002804 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002805 case Expr::GNUNullExprClass:
2806 // GCC considers the GNU __null value to be an integral constant expression.
2807 return NoDiag();
2808
2809 case Expr::ParenExprClass:
2810 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00002811 case Expr::GenericSelectionExprClass:
2812 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002813 case Expr::IntegerLiteralClass:
2814 case Expr::CharacterLiteralClass:
2815 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00002816 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002817 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00002818 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00002819 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00002820 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00002821 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00002822 return NoDiag();
2823 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00002824 case Expr::CXXOperatorCallExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00002825 const CallExpr *CE = cast<CallExpr>(E);
2826 if (CE->isBuiltinCall(Ctx))
2827 return CheckEvalInICE(E, Ctx);
2828 return ICEDiag(2, E->getLocStart());
2829 }
2830 case Expr::DeclRefExprClass:
2831 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
2832 return NoDiag();
2833 if (Ctx.getLangOptions().CPlusPlus &&
2834 E->getType().getCVRQualifiers() == Qualifiers::Const) {
2835 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2836
2837 // Parameter variables are never constants. Without this check,
2838 // getAnyInitializer() can find a default argument, which leads
2839 // to chaos.
2840 if (isa<ParmVarDecl>(D))
2841 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2842
2843 // C++ 7.1.5.1p2
2844 // A variable of non-volatile const-qualified integral or enumeration
2845 // type initialized by an ICE can be used in ICEs.
2846 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
2847 Qualifiers Quals = Ctx.getCanonicalType(Dcl->getType()).getQualifiers();
2848 if (Quals.hasVolatile() || !Quals.hasConst())
2849 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2850
2851 // Look for a declaration of this variable that has an initializer.
2852 const VarDecl *ID = 0;
2853 const Expr *Init = Dcl->getAnyInitializer(ID);
2854 if (Init) {
2855 if (ID->isInitKnownICE()) {
2856 // We have already checked whether this subexpression is an
2857 // integral constant expression.
2858 if (ID->isInitICE())
2859 return NoDiag();
2860 else
2861 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2862 }
2863
2864 // It's an ICE whether or not the definition we found is
2865 // out-of-line. See DR 721 and the discussion in Clang PR
2866 // 6206 for details.
2867
2868 if (Dcl->isCheckingICE()) {
2869 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
2870 }
2871
2872 Dcl->setCheckingICE();
2873 ICEDiag Result = CheckICE(Init, Ctx);
2874 // Cache the result of the ICE test.
2875 Dcl->setInitKnownICE(Result.Val == 0);
2876 return Result;
2877 }
2878 }
2879 }
2880 return ICEDiag(2, E->getLocStart());
2881 case Expr::UnaryOperatorClass: {
2882 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2883 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002884 case UO_PostInc:
2885 case UO_PostDec:
2886 case UO_PreInc:
2887 case UO_PreDec:
2888 case UO_AddrOf:
2889 case UO_Deref:
John McCalld905f5a2010-05-07 05:32:02 +00002890 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00002891 case UO_Extension:
2892 case UO_LNot:
2893 case UO_Plus:
2894 case UO_Minus:
2895 case UO_Not:
2896 case UO_Real:
2897 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00002898 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00002899 }
2900
2901 // OffsetOf falls through here.
2902 }
2903 case Expr::OffsetOfExprClass: {
2904 // Note that per C99, offsetof must be an ICE. And AFAIK, using
2905 // Evaluate matches the proposed gcc behavior for cases like
2906 // "offsetof(struct s{int x[4];}, x[!.0])". This doesn't affect
2907 // compliance: we should warn earlier for offsetof expressions with
2908 // array subscripts that aren't ICEs, and if the array subscripts
2909 // are ICEs, the value of the offsetof must be an integer constant.
2910 return CheckEvalInICE(E, Ctx);
2911 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002912 case Expr::UnaryExprOrTypeTraitExprClass: {
2913 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
2914 if ((Exp->getKind() == UETT_SizeOf) &&
2915 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00002916 return ICEDiag(2, E->getLocStart());
2917 return NoDiag();
2918 }
2919 case Expr::BinaryOperatorClass: {
2920 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2921 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00002922 case BO_PtrMemD:
2923 case BO_PtrMemI:
2924 case BO_Assign:
2925 case BO_MulAssign:
2926 case BO_DivAssign:
2927 case BO_RemAssign:
2928 case BO_AddAssign:
2929 case BO_SubAssign:
2930 case BO_ShlAssign:
2931 case BO_ShrAssign:
2932 case BO_AndAssign:
2933 case BO_XorAssign:
2934 case BO_OrAssign:
John McCalld905f5a2010-05-07 05:32:02 +00002935 return ICEDiag(2, E->getLocStart());
2936
John McCall2de56d12010-08-25 11:45:40 +00002937 case BO_Mul:
2938 case BO_Div:
2939 case BO_Rem:
2940 case BO_Add:
2941 case BO_Sub:
2942 case BO_Shl:
2943 case BO_Shr:
2944 case BO_LT:
2945 case BO_GT:
2946 case BO_LE:
2947 case BO_GE:
2948 case BO_EQ:
2949 case BO_NE:
2950 case BO_And:
2951 case BO_Xor:
2952 case BO_Or:
2953 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00002954 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
2955 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00002956 if (Exp->getOpcode() == BO_Div ||
2957 Exp->getOpcode() == BO_Rem) {
John McCalld905f5a2010-05-07 05:32:02 +00002958 // Evaluate gives an error for undefined Div/Rem, so make sure
2959 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00002960 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00002961 llvm::APSInt REval = Exp->getRHS()->EvaluateAsInt(Ctx);
2962 if (REval == 0)
2963 return ICEDiag(1, E->getLocStart());
2964 if (REval.isSigned() && REval.isAllOnesValue()) {
2965 llvm::APSInt LEval = Exp->getLHS()->EvaluateAsInt(Ctx);
2966 if (LEval.isMinSignedValue())
2967 return ICEDiag(1, E->getLocStart());
2968 }
2969 }
2970 }
John McCall2de56d12010-08-25 11:45:40 +00002971 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00002972 if (Ctx.getLangOptions().C99) {
2973 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
2974 // if it isn't evaluated.
2975 if (LHSResult.Val == 0 && RHSResult.Val == 0)
2976 return ICEDiag(1, E->getLocStart());
2977 } else {
2978 // In both C89 and C++, commas in ICEs are illegal.
2979 return ICEDiag(2, E->getLocStart());
2980 }
2981 }
2982 if (LHSResult.Val >= RHSResult.Val)
2983 return LHSResult;
2984 return RHSResult;
2985 }
John McCall2de56d12010-08-25 11:45:40 +00002986 case BO_LAnd:
2987 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00002988 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00002989
2990 // C++0x [expr.const]p2:
2991 // [...] subexpressions of logical AND (5.14), logical OR
2992 // (5.15), and condi- tional (5.16) operations that are not
2993 // evaluated are not considered.
2994 if (Ctx.getLangOptions().CPlusPlus0x && LHSResult.Val == 0) {
2995 if (Exp->getOpcode() == BO_LAnd &&
2996 Exp->getLHS()->EvaluateAsInt(Ctx) == 0)
2997 return LHSResult;
2998
2999 if (Exp->getOpcode() == BO_LOr &&
3000 Exp->getLHS()->EvaluateAsInt(Ctx) != 0)
3001 return LHSResult;
3002 }
3003
John McCalld905f5a2010-05-07 05:32:02 +00003004 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
3005 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
3006 // Rare case where the RHS has a comma "side-effect"; we need
3007 // to actually check the condition to see whether the side
3008 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00003009 if ((Exp->getOpcode() == BO_LAnd) !=
John McCalld905f5a2010-05-07 05:32:02 +00003010 (Exp->getLHS()->EvaluateAsInt(Ctx) == 0))
3011 return RHSResult;
3012 return NoDiag();
3013 }
3014
3015 if (LHSResult.Val >= RHSResult.Val)
3016 return LHSResult;
3017 return RHSResult;
3018 }
3019 }
3020 }
3021 case Expr::ImplicitCastExprClass:
3022 case Expr::CStyleCastExprClass:
3023 case Expr::CXXFunctionalCastExprClass:
3024 case Expr::CXXStaticCastExprClass:
3025 case Expr::CXXReinterpretCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00003026 case Expr::CXXConstCastExprClass:
3027 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00003028 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003029 if (SubExpr->getType()->isIntegralOrEnumerationType())
John McCalld905f5a2010-05-07 05:32:02 +00003030 return CheckICE(SubExpr, Ctx);
3031 if (isa<FloatingLiteral>(SubExpr->IgnoreParens()))
3032 return NoDiag();
3033 return ICEDiag(2, E->getLocStart());
3034 }
John McCall56ca35d2011-02-17 10:25:35 +00003035 case Expr::BinaryConditionalOperatorClass: {
3036 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
3037 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
3038 if (CommonResult.Val == 2) return CommonResult;
3039 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3040 if (FalseResult.Val == 2) return FalseResult;
3041 if (CommonResult.Val == 1) return CommonResult;
3042 if (FalseResult.Val == 1 &&
3043 Exp->getCommon()->EvaluateAsInt(Ctx) == 0) return NoDiag();
3044 return FalseResult;
3045 }
John McCalld905f5a2010-05-07 05:32:02 +00003046 case Expr::ConditionalOperatorClass: {
3047 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
3048 // If the condition (ignoring parens) is a __builtin_constant_p call,
3049 // then only the true side is actually considered in an integer constant
3050 // expression, and it is fully evaluated. This is an important GNU
3051 // extension. See GCC PR38377 for discussion.
3052 if (const CallExpr *CallCE
3053 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
3054 if (CallCE->isBuiltinCall(Ctx) == Builtin::BI__builtin_constant_p) {
3055 Expr::EvalResult EVResult;
3056 if (!E->Evaluate(EVResult, Ctx) || EVResult.HasSideEffects ||
3057 !EVResult.Val.isInt()) {
3058 return ICEDiag(2, E->getLocStart());
3059 }
3060 return NoDiag();
3061 }
3062 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00003063 if (CondResult.Val == 2)
3064 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00003065
3066 // C++0x [expr.const]p2:
3067 // subexpressions of [...] conditional (5.16) operations that
3068 // are not evaluated are not considered
3069 bool TrueBranch = Ctx.getLangOptions().CPlusPlus0x
3070 ? Exp->getCond()->EvaluateAsInt(Ctx) != 0
3071 : false;
3072 ICEDiag TrueResult = NoDiag();
3073 if (!Ctx.getLangOptions().CPlusPlus0x || TrueBranch)
3074 TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
3075 ICEDiag FalseResult = NoDiag();
3076 if (!Ctx.getLangOptions().CPlusPlus0x || !TrueBranch)
3077 FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
3078
John McCalld905f5a2010-05-07 05:32:02 +00003079 if (TrueResult.Val == 2)
3080 return TrueResult;
3081 if (FalseResult.Val == 2)
3082 return FalseResult;
3083 if (CondResult.Val == 1)
3084 return CondResult;
3085 if (TrueResult.Val == 0 && FalseResult.Val == 0)
3086 return NoDiag();
3087 // Rare case where the diagnostics depend on which side is evaluated
3088 // Note that if we get here, CondResult is 0, and at least one of
3089 // TrueResult and FalseResult is non-zero.
3090 if (Exp->getCond()->EvaluateAsInt(Ctx) == 0) {
3091 return FalseResult;
3092 }
3093 return TrueResult;
3094 }
3095 case Expr::CXXDefaultArgExprClass:
3096 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
3097 case Expr::ChooseExprClass: {
3098 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
3099 }
3100 }
3101
3102 // Silence a GCC warning
3103 return ICEDiag(2, E->getLocStart());
3104}
3105
3106bool Expr::isIntegerConstantExpr(llvm::APSInt &Result, ASTContext &Ctx,
3107 SourceLocation *Loc, bool isEvaluated) const {
3108 ICEDiag d = CheckICE(this, Ctx);
3109 if (d.Val != 0) {
3110 if (Loc) *Loc = d.Loc;
3111 return false;
3112 }
3113 EvalResult EvalResult;
3114 if (!Evaluate(EvalResult, Ctx))
3115 llvm_unreachable("ICE cannot be evaluated!");
3116 assert(!EvalResult.HasSideEffects && "ICE with side effects!");
3117 assert(EvalResult.Val.isInt() && "ICE that isn't integer!");
3118 Result = EvalResult.Val.getInt();
3119 return true;
3120}